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 << New->getConstexprKind() << Old->getConstexprKind(); 659 Diag(Old->getLocation(), diag::note_previous_declaration); 660 Invalid = true; 661 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 662 Old->isDefined(Def) && 663 // If a friend function is inlined but does not have 'inline' 664 // specifier, it is a definition. Do not report attribute conflict 665 // in this case, redefinition will be diagnosed later. 666 (New->isInlineSpecified() || 667 New->getFriendObjectKind() == Decl::FOK_None)) { 668 // C++11 [dcl.fcn.spec]p4: 669 // If the definition of a function appears in a translation unit before its 670 // first declaration as inline, the program is ill-formed. 671 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 672 Diag(Def->getLocation(), diag::note_previous_definition); 673 Invalid = true; 674 } 675 676 // C++17 [temp.deduct.guide]p3: 677 // Two deduction guide declarations in the same translation unit 678 // for the same class template shall not have equivalent 679 // parameter-declaration-clauses. 680 if (isa<CXXDeductionGuideDecl>(New) && 681 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 682 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 683 Diag(Old->getLocation(), diag::note_previous_declaration); 684 } 685 686 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 687 // argument expression, that declaration shall be a definition and shall be 688 // the only declaration of the function or function template in the 689 // translation unit. 690 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 691 functionDeclHasDefaultArgument(Old)) { 692 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 693 Diag(Old->getLocation(), diag::note_previous_declaration); 694 Invalid = true; 695 } 696 697 return Invalid; 698 } 699 700 NamedDecl * 701 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 702 MultiTemplateParamsArg TemplateParamLists) { 703 assert(D.isDecompositionDeclarator()); 704 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 705 706 // The syntax only allows a decomposition declarator as a simple-declaration, 707 // a for-range-declaration, or a condition in Clang, but we parse it in more 708 // cases than that. 709 if (!D.mayHaveDecompositionDeclarator()) { 710 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 711 << Decomp.getSourceRange(); 712 return nullptr; 713 } 714 715 if (!TemplateParamLists.empty()) { 716 // FIXME: There's no rule against this, but there are also no rules that 717 // would actually make it usable, so we reject it for now. 718 Diag(TemplateParamLists.front()->getTemplateLoc(), 719 diag::err_decomp_decl_template); 720 return nullptr; 721 } 722 723 Diag(Decomp.getLSquareLoc(), 724 !getLangOpts().CPlusPlus17 725 ? diag::ext_decomp_decl 726 : D.getContext() == DeclaratorContext::ConditionContext 727 ? diag::ext_decomp_decl_cond 728 : diag::warn_cxx14_compat_decomp_decl) 729 << Decomp.getSourceRange(); 730 731 // The semantic context is always just the current context. 732 DeclContext *const DC = CurContext; 733 734 // C++17 [dcl.dcl]/8: 735 // The decl-specifier-seq shall contain only the type-specifier auto 736 // and cv-qualifiers. 737 // C++2a [dcl.dcl]/8: 738 // If decl-specifier-seq contains any decl-specifier other than static, 739 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 740 auto &DS = D.getDeclSpec(); 741 { 742 SmallVector<StringRef, 8> BadSpecifiers; 743 SmallVector<SourceLocation, 8> BadSpecifierLocs; 744 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 745 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 746 if (auto SCS = DS.getStorageClassSpec()) { 747 if (SCS == DeclSpec::SCS_static) { 748 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 749 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 750 } else { 751 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 752 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 753 } 754 } 755 if (auto TSCS = DS.getThreadStorageClassSpec()) { 756 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 757 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 758 } 759 if (DS.hasConstexprSpecifier()) { 760 BadSpecifiers.push_back( 761 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 762 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 763 } 764 if (DS.isInlineSpecified()) { 765 BadSpecifiers.push_back("inline"); 766 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 767 } 768 if (!BadSpecifiers.empty()) { 769 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 770 Err << (int)BadSpecifiers.size() 771 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 772 // Don't add FixItHints to remove the specifiers; we do still respect 773 // them when building the underlying variable. 774 for (auto Loc : BadSpecifierLocs) 775 Err << SourceRange(Loc, Loc); 776 } else if (!CPlusPlus20Specifiers.empty()) { 777 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 778 getLangOpts().CPlusPlus20 779 ? diag::warn_cxx17_compat_decomp_decl_spec 780 : diag::ext_decomp_decl_spec); 781 Warn << (int)CPlusPlus20Specifiers.size() 782 << llvm::join(CPlusPlus20Specifiers.begin(), 783 CPlusPlus20Specifiers.end(), " "); 784 for (auto Loc : CPlusPlus20SpecifierLocs) 785 Warn << SourceRange(Loc, Loc); 786 } 787 // We can't recover from it being declared as a typedef. 788 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 789 return nullptr; 790 } 791 792 // C++2a [dcl.struct.bind]p1: 793 // A cv that includes volatile is deprecated 794 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 795 getLangOpts().CPlusPlus20) 796 Diag(DS.getVolatileSpecLoc(), 797 diag::warn_deprecated_volatile_structured_binding); 798 799 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 800 QualType R = TInfo->getType(); 801 802 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 803 UPPC_DeclarationType)) 804 D.setInvalidType(); 805 806 // The syntax only allows a single ref-qualifier prior to the decomposition 807 // declarator. No other declarator chunks are permitted. Also check the type 808 // specifier here. 809 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 810 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 811 (D.getNumTypeObjects() == 1 && 812 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 813 Diag(Decomp.getLSquareLoc(), 814 (D.hasGroupingParens() || 815 (D.getNumTypeObjects() && 816 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 817 ? diag::err_decomp_decl_parens 818 : diag::err_decomp_decl_type) 819 << R; 820 821 // In most cases, there's no actual problem with an explicitly-specified 822 // type, but a function type won't work here, and ActOnVariableDeclarator 823 // shouldn't be called for such a type. 824 if (R->isFunctionType()) 825 D.setInvalidType(); 826 } 827 828 // Build the BindingDecls. 829 SmallVector<BindingDecl*, 8> Bindings; 830 831 // Build the BindingDecls. 832 for (auto &B : D.getDecompositionDeclarator().bindings()) { 833 // Check for name conflicts. 834 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 835 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 836 ForVisibleRedeclaration); 837 LookupName(Previous, S, 838 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 839 840 // It's not permitted to shadow a template parameter name. 841 if (Previous.isSingleResult() && 842 Previous.getFoundDecl()->isTemplateParameter()) { 843 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 844 Previous.getFoundDecl()); 845 Previous.clear(); 846 } 847 848 bool ConsiderLinkage = DC->isFunctionOrMethod() && 849 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 850 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 851 /*AllowInlineNamespace*/false); 852 if (!Previous.empty()) { 853 auto *Old = Previous.getRepresentativeDecl(); 854 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 855 Diag(Old->getLocation(), diag::note_previous_definition); 856 } 857 858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 859 PushOnScopeChains(BD, S, true); 860 Bindings.push_back(BD); 861 ParsingInitForAutoVars.insert(BD); 862 } 863 864 // There are no prior lookup results for the variable itself, because it 865 // is unnamed. 866 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 867 Decomp.getLSquareLoc()); 868 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 869 ForVisibleRedeclaration); 870 871 // Build the variable that holds the non-decomposed object. 872 bool AddToScope = true; 873 NamedDecl *New = 874 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 875 MultiTemplateParamsArg(), AddToScope, Bindings); 876 if (AddToScope) { 877 S->AddDecl(New); 878 CurContext->addHiddenDecl(New); 879 } 880 881 if (isInOpenMPDeclareTargetContext()) 882 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 883 884 return New; 885 } 886 887 static bool checkSimpleDecomposition( 888 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 889 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 890 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 891 if ((int64_t)Bindings.size() != NumElems) { 892 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 893 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 894 << (NumElems < Bindings.size()); 895 return true; 896 } 897 898 unsigned I = 0; 899 for (auto *B : Bindings) { 900 SourceLocation Loc = B->getLocation(); 901 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 902 if (E.isInvalid()) 903 return true; 904 E = GetInit(Loc, E.get(), I++); 905 if (E.isInvalid()) 906 return true; 907 B->setBinding(ElemType, E.get()); 908 } 909 910 return false; 911 } 912 913 static bool checkArrayLikeDecomposition(Sema &S, 914 ArrayRef<BindingDecl *> Bindings, 915 ValueDecl *Src, QualType DecompType, 916 const llvm::APSInt &NumElems, 917 QualType ElemType) { 918 return checkSimpleDecomposition( 919 S, Bindings, Src, DecompType, NumElems, ElemType, 920 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 921 ExprResult E = S.ActOnIntegerConstant(Loc, I); 922 if (E.isInvalid()) 923 return ExprError(); 924 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 925 }); 926 } 927 928 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 929 ValueDecl *Src, QualType DecompType, 930 const ConstantArrayType *CAT) { 931 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 932 llvm::APSInt(CAT->getSize()), 933 CAT->getElementType()); 934 } 935 936 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 937 ValueDecl *Src, QualType DecompType, 938 const VectorType *VT) { 939 return checkArrayLikeDecomposition( 940 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 941 S.Context.getQualifiedType(VT->getElementType(), 942 DecompType.getQualifiers())); 943 } 944 945 static bool checkComplexDecomposition(Sema &S, 946 ArrayRef<BindingDecl *> Bindings, 947 ValueDecl *Src, QualType DecompType, 948 const ComplexType *CT) { 949 return checkSimpleDecomposition( 950 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 951 S.Context.getQualifiedType(CT->getElementType(), 952 DecompType.getQualifiers()), 953 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 954 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 955 }); 956 } 957 958 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 959 TemplateArgumentListInfo &Args) { 960 SmallString<128> SS; 961 llvm::raw_svector_ostream OS(SS); 962 bool First = true; 963 for (auto &Arg : Args.arguments()) { 964 if (!First) 965 OS << ", "; 966 Arg.getArgument().print(PrintingPolicy, OS); 967 First = false; 968 } 969 return std::string(OS.str()); 970 } 971 972 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 973 SourceLocation Loc, StringRef Trait, 974 TemplateArgumentListInfo &Args, 975 unsigned DiagID) { 976 auto DiagnoseMissing = [&] { 977 if (DiagID) 978 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 979 Args); 980 return true; 981 }; 982 983 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 984 NamespaceDecl *Std = S.getStdNamespace(); 985 if (!Std) 986 return DiagnoseMissing(); 987 988 // Look up the trait itself, within namespace std. We can diagnose various 989 // problems with this lookup even if we've been asked to not diagnose a 990 // missing specialization, because this can only fail if the user has been 991 // declaring their own names in namespace std or we don't support the 992 // standard library implementation in use. 993 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 994 Loc, Sema::LookupOrdinaryName); 995 if (!S.LookupQualifiedName(Result, Std)) 996 return DiagnoseMissing(); 997 if (Result.isAmbiguous()) 998 return true; 999 1000 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1001 if (!TraitTD) { 1002 Result.suppressDiagnostics(); 1003 NamedDecl *Found = *Result.begin(); 1004 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1005 S.Diag(Found->getLocation(), diag::note_declared_at); 1006 return true; 1007 } 1008 1009 // Build the template-id. 1010 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1011 if (TraitTy.isNull()) 1012 return true; 1013 if (!S.isCompleteType(Loc, TraitTy)) { 1014 if (DiagID) 1015 S.RequireCompleteType( 1016 Loc, TraitTy, DiagID, 1017 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1018 return true; 1019 } 1020 1021 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1022 assert(RD && "specialization of class template is not a class?"); 1023 1024 // Look up the member of the trait type. 1025 S.LookupQualifiedName(TraitMemberLookup, RD); 1026 return TraitMemberLookup.isAmbiguous(); 1027 } 1028 1029 static TemplateArgumentLoc 1030 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1031 uint64_t I) { 1032 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1033 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1034 } 1035 1036 static TemplateArgumentLoc 1037 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1038 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1039 } 1040 1041 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1042 1043 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1044 llvm::APSInt &Size) { 1045 EnterExpressionEvaluationContext ContextRAII( 1046 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1047 1048 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1049 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1050 1051 // Form template argument list for tuple_size<T>. 1052 TemplateArgumentListInfo Args(Loc, Loc); 1053 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1054 1055 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1056 // it's not tuple-like. 1057 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1058 R.empty()) 1059 return IsTupleLike::NotTupleLike; 1060 1061 // If we get this far, we've committed to the tuple interpretation, but 1062 // we can still fail if there actually isn't a usable ::value. 1063 1064 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1065 LookupResult &R; 1066 TemplateArgumentListInfo &Args; 1067 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1068 : R(R), Args(Args) {} 1069 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1070 SourceLocation Loc) override { 1071 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1072 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1073 } 1074 } Diagnoser(R, Args); 1075 1076 ExprResult E = 1077 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1078 if (E.isInvalid()) 1079 return IsTupleLike::Error; 1080 1081 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1082 if (E.isInvalid()) 1083 return IsTupleLike::Error; 1084 1085 return IsTupleLike::TupleLike; 1086 } 1087 1088 /// \return std::tuple_element<I, T>::type. 1089 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1090 unsigned I, QualType T) { 1091 // Form template argument list for tuple_element<I, T>. 1092 TemplateArgumentListInfo Args(Loc, Loc); 1093 Args.addArgument( 1094 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1095 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1096 1097 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1098 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1099 if (lookupStdTypeTraitMember( 1100 S, R, Loc, "tuple_element", Args, 1101 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1102 return QualType(); 1103 1104 auto *TD = R.getAsSingle<TypeDecl>(); 1105 if (!TD) { 1106 R.suppressDiagnostics(); 1107 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1108 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1109 if (!R.empty()) 1110 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1111 return QualType(); 1112 } 1113 1114 return S.Context.getTypeDeclType(TD); 1115 } 1116 1117 namespace { 1118 struct InitializingBinding { 1119 Sema &S; 1120 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1121 Sema::CodeSynthesisContext Ctx; 1122 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1123 Ctx.PointOfInstantiation = BD->getLocation(); 1124 Ctx.Entity = BD; 1125 S.pushCodeSynthesisContext(Ctx); 1126 } 1127 ~InitializingBinding() { 1128 S.popCodeSynthesisContext(); 1129 } 1130 }; 1131 } 1132 1133 static bool checkTupleLikeDecomposition(Sema &S, 1134 ArrayRef<BindingDecl *> Bindings, 1135 VarDecl *Src, QualType DecompType, 1136 const llvm::APSInt &TupleSize) { 1137 if ((int64_t)Bindings.size() != TupleSize) { 1138 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1139 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1140 << (TupleSize < Bindings.size()); 1141 return true; 1142 } 1143 1144 if (Bindings.empty()) 1145 return false; 1146 1147 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1148 1149 // [dcl.decomp]p3: 1150 // The unqualified-id get is looked up in the scope of E by class member 1151 // access lookup ... 1152 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1153 bool UseMemberGet = false; 1154 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1155 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1156 S.LookupQualifiedName(MemberGet, RD); 1157 if (MemberGet.isAmbiguous()) 1158 return true; 1159 // ... and if that finds at least one declaration that is a function 1160 // template whose first template parameter is a non-type parameter ... 1161 for (NamedDecl *D : MemberGet) { 1162 if (FunctionTemplateDecl *FTD = 1163 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1164 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1165 if (TPL->size() != 0 && 1166 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1167 // ... the initializer is e.get<i>(). 1168 UseMemberGet = true; 1169 break; 1170 } 1171 } 1172 } 1173 } 1174 1175 unsigned I = 0; 1176 for (auto *B : Bindings) { 1177 InitializingBinding InitContext(S, B); 1178 SourceLocation Loc = B->getLocation(); 1179 1180 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1181 if (E.isInvalid()) 1182 return true; 1183 1184 // e is an lvalue if the type of the entity is an lvalue reference and 1185 // an xvalue otherwise 1186 if (!Src->getType()->isLValueReferenceType()) 1187 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1188 E.get(), nullptr, VK_XValue); 1189 1190 TemplateArgumentListInfo Args(Loc, Loc); 1191 Args.addArgument( 1192 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1193 1194 if (UseMemberGet) { 1195 // if [lookup of member get] finds at least one declaration, the 1196 // initializer is e.get<i-1>(). 1197 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1198 CXXScopeSpec(), SourceLocation(), nullptr, 1199 MemberGet, &Args, nullptr); 1200 if (E.isInvalid()) 1201 return true; 1202 1203 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1204 } else { 1205 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1206 // in the associated namespaces. 1207 Expr *Get = UnresolvedLookupExpr::Create( 1208 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1209 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1210 UnresolvedSetIterator(), UnresolvedSetIterator()); 1211 1212 Expr *Arg = E.get(); 1213 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1214 } 1215 if (E.isInvalid()) 1216 return true; 1217 Expr *Init = E.get(); 1218 1219 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1220 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1221 if (T.isNull()) 1222 return true; 1223 1224 // each vi is a variable of type "reference to T" initialized with the 1225 // initializer, where the reference is an lvalue reference if the 1226 // initializer is an lvalue and an rvalue reference otherwise 1227 QualType RefType = 1228 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1229 if (RefType.isNull()) 1230 return true; 1231 auto *RefVD = VarDecl::Create( 1232 S.Context, Src->getDeclContext(), Loc, Loc, 1233 B->getDeclName().getAsIdentifierInfo(), RefType, 1234 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1235 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1236 RefVD->setTSCSpec(Src->getTSCSpec()); 1237 RefVD->setImplicit(); 1238 if (Src->isInlineSpecified()) 1239 RefVD->setInlineSpecified(); 1240 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1241 1242 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1243 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1244 InitializationSequence Seq(S, Entity, Kind, Init); 1245 E = Seq.Perform(S, Entity, Kind, Init); 1246 if (E.isInvalid()) 1247 return true; 1248 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1249 if (E.isInvalid()) 1250 return true; 1251 RefVD->setInit(E.get()); 1252 if (!E.get()->isValueDependent()) 1253 RefVD->checkInitIsICE(); 1254 1255 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1256 DeclarationNameInfo(B->getDeclName(), Loc), 1257 RefVD); 1258 if (E.isInvalid()) 1259 return true; 1260 1261 B->setBinding(T, E.get()); 1262 I++; 1263 } 1264 1265 return false; 1266 } 1267 1268 /// Find the base class to decompose in a built-in decomposition of a class type. 1269 /// This base class search is, unfortunately, not quite like any other that we 1270 /// perform anywhere else in C++. 1271 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1272 const CXXRecordDecl *RD, 1273 CXXCastPath &BasePath) { 1274 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1275 CXXBasePath &Path) { 1276 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1277 }; 1278 1279 const CXXRecordDecl *ClassWithFields = nullptr; 1280 AccessSpecifier AS = AS_public; 1281 if (RD->hasDirectFields()) 1282 // [dcl.decomp]p4: 1283 // Otherwise, all of E's non-static data members shall be public direct 1284 // members of E ... 1285 ClassWithFields = RD; 1286 else { 1287 // ... or of ... 1288 CXXBasePaths Paths; 1289 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1290 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1291 // If no classes have fields, just decompose RD itself. (This will work 1292 // if and only if zero bindings were provided.) 1293 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1294 } 1295 1296 CXXBasePath *BestPath = nullptr; 1297 for (auto &P : Paths) { 1298 if (!BestPath) 1299 BestPath = &P; 1300 else if (!S.Context.hasSameType(P.back().Base->getType(), 1301 BestPath->back().Base->getType())) { 1302 // ... the same ... 1303 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1304 << false << RD << BestPath->back().Base->getType() 1305 << P.back().Base->getType(); 1306 return DeclAccessPair(); 1307 } else if (P.Access < BestPath->Access) { 1308 BestPath = &P; 1309 } 1310 } 1311 1312 // ... unambiguous ... 1313 QualType BaseType = BestPath->back().Base->getType(); 1314 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1315 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1316 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1317 return DeclAccessPair(); 1318 } 1319 1320 // ... [accessible, implied by other rules] base class of E. 1321 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1322 *BestPath, diag::err_decomp_decl_inaccessible_base); 1323 AS = BestPath->Access; 1324 1325 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1326 S.BuildBasePathArray(Paths, BasePath); 1327 } 1328 1329 // The above search did not check whether the selected class itself has base 1330 // classes with fields, so check that now. 1331 CXXBasePaths Paths; 1332 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1333 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1334 << (ClassWithFields == RD) << RD << ClassWithFields 1335 << Paths.front().back().Base->getType(); 1336 return DeclAccessPair(); 1337 } 1338 1339 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1340 } 1341 1342 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1343 ValueDecl *Src, QualType DecompType, 1344 const CXXRecordDecl *OrigRD) { 1345 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1346 diag::err_incomplete_type)) 1347 return true; 1348 1349 CXXCastPath BasePath; 1350 DeclAccessPair BasePair = 1351 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1352 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1353 if (!RD) 1354 return true; 1355 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1356 DecompType.getQualifiers()); 1357 1358 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1359 unsigned NumFields = 1360 std::count_if(RD->field_begin(), RD->field_end(), 1361 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1362 assert(Bindings.size() != NumFields); 1363 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1364 << DecompType << (unsigned)Bindings.size() << NumFields 1365 << (NumFields < Bindings.size()); 1366 return true; 1367 }; 1368 1369 // all of E's non-static data members shall be [...] well-formed 1370 // when named as e.name in the context of the structured binding, 1371 // E shall not have an anonymous union member, ... 1372 unsigned I = 0; 1373 for (auto *FD : RD->fields()) { 1374 if (FD->isUnnamedBitfield()) 1375 continue; 1376 1377 if (FD->isAnonymousStructOrUnion()) { 1378 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1379 << DecompType << FD->getType()->isUnionType(); 1380 S.Diag(FD->getLocation(), diag::note_declared_at); 1381 return true; 1382 } 1383 1384 // We have a real field to bind. 1385 if (I >= Bindings.size()) 1386 return DiagnoseBadNumberOfBindings(); 1387 auto *B = Bindings[I++]; 1388 SourceLocation Loc = B->getLocation(); 1389 1390 // The field must be accessible in the context of the structured binding. 1391 // We already checked that the base class is accessible. 1392 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1393 // const_cast here. 1394 S.CheckStructuredBindingMemberAccess( 1395 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1396 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1397 BasePair.getAccess(), FD->getAccess()))); 1398 1399 // Initialize the binding to Src.FD. 1400 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1401 if (E.isInvalid()) 1402 return true; 1403 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1404 VK_LValue, &BasePath); 1405 if (E.isInvalid()) 1406 return true; 1407 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1408 CXXScopeSpec(), FD, 1409 DeclAccessPair::make(FD, FD->getAccess()), 1410 DeclarationNameInfo(FD->getDeclName(), Loc)); 1411 if (E.isInvalid()) 1412 return true; 1413 1414 // If the type of the member is T, the referenced type is cv T, where cv is 1415 // the cv-qualification of the decomposition expression. 1416 // 1417 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1418 // 'const' to the type of the field. 1419 Qualifiers Q = DecompType.getQualifiers(); 1420 if (FD->isMutable()) 1421 Q.removeConst(); 1422 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1423 } 1424 1425 if (I != Bindings.size()) 1426 return DiagnoseBadNumberOfBindings(); 1427 1428 return false; 1429 } 1430 1431 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1432 QualType DecompType = DD->getType(); 1433 1434 // If the type of the decomposition is dependent, then so is the type of 1435 // each binding. 1436 if (DecompType->isDependentType()) { 1437 for (auto *B : DD->bindings()) 1438 B->setType(Context.DependentTy); 1439 return; 1440 } 1441 1442 DecompType = DecompType.getNonReferenceType(); 1443 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1444 1445 // C++1z [dcl.decomp]/2: 1446 // If E is an array type [...] 1447 // As an extension, we also support decomposition of built-in complex and 1448 // vector types. 1449 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1450 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1451 DD->setInvalidDecl(); 1452 return; 1453 } 1454 if (auto *VT = DecompType->getAs<VectorType>()) { 1455 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1456 DD->setInvalidDecl(); 1457 return; 1458 } 1459 if (auto *CT = DecompType->getAs<ComplexType>()) { 1460 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1461 DD->setInvalidDecl(); 1462 return; 1463 } 1464 1465 // C++1z [dcl.decomp]/3: 1466 // if the expression std::tuple_size<E>::value is a well-formed integral 1467 // constant expression, [...] 1468 llvm::APSInt TupleSize(32); 1469 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1470 case IsTupleLike::Error: 1471 DD->setInvalidDecl(); 1472 return; 1473 1474 case IsTupleLike::TupleLike: 1475 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1476 DD->setInvalidDecl(); 1477 return; 1478 1479 case IsTupleLike::NotTupleLike: 1480 break; 1481 } 1482 1483 // C++1z [dcl.dcl]/8: 1484 // [E shall be of array or non-union class type] 1485 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1486 if (!RD || RD->isUnion()) { 1487 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1488 << DD << !RD << DecompType; 1489 DD->setInvalidDecl(); 1490 return; 1491 } 1492 1493 // C++1z [dcl.decomp]/4: 1494 // all of E's non-static data members shall be [...] direct members of 1495 // E or of the same unambiguous public base class of E, ... 1496 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1497 DD->setInvalidDecl(); 1498 } 1499 1500 /// Merge the exception specifications of two variable declarations. 1501 /// 1502 /// This is called when there's a redeclaration of a VarDecl. The function 1503 /// checks if the redeclaration might have an exception specification and 1504 /// validates compatibility and merges the specs if necessary. 1505 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1506 // Shortcut if exceptions are disabled. 1507 if (!getLangOpts().CXXExceptions) 1508 return; 1509 1510 assert(Context.hasSameType(New->getType(), Old->getType()) && 1511 "Should only be called if types are otherwise the same."); 1512 1513 QualType NewType = New->getType(); 1514 QualType OldType = Old->getType(); 1515 1516 // We're only interested in pointers and references to functions, as well 1517 // as pointers to member functions. 1518 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1519 NewType = R->getPointeeType(); 1520 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1521 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1522 NewType = P->getPointeeType(); 1523 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1524 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1525 NewType = M->getPointeeType(); 1526 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1527 } 1528 1529 if (!NewType->isFunctionProtoType()) 1530 return; 1531 1532 // There's lots of special cases for functions. For function pointers, system 1533 // libraries are hopefully not as broken so that we don't need these 1534 // workarounds. 1535 if (CheckEquivalentExceptionSpec( 1536 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1537 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1538 New->setInvalidDecl(); 1539 } 1540 } 1541 1542 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1543 /// function declaration are well-formed according to C++ 1544 /// [dcl.fct.default]. 1545 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1546 unsigned NumParams = FD->getNumParams(); 1547 unsigned ParamIdx = 0; 1548 1549 // This checking doesn't make sense for explicit specializations; their 1550 // default arguments are determined by the declaration we're specializing, 1551 // not by FD. 1552 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1553 return; 1554 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1555 if (FTD->isMemberSpecialization()) 1556 return; 1557 1558 // Find first parameter with a default argument 1559 for (; ParamIdx < NumParams; ++ParamIdx) { 1560 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1561 if (Param->hasDefaultArg()) 1562 break; 1563 } 1564 1565 // C++20 [dcl.fct.default]p4: 1566 // In a given function declaration, each parameter subsequent to a parameter 1567 // with a default argument shall have a default argument supplied in this or 1568 // a previous declaration, unless the parameter was expanded from a 1569 // parameter pack, or shall be a function parameter pack. 1570 for (; ParamIdx < NumParams; ++ParamIdx) { 1571 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1572 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1573 !(CurrentInstantiationScope && 1574 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1575 if (Param->isInvalidDecl()) 1576 /* We already complained about this parameter. */; 1577 else if (Param->getIdentifier()) 1578 Diag(Param->getLocation(), 1579 diag::err_param_default_argument_missing_name) 1580 << Param->getIdentifier(); 1581 else 1582 Diag(Param->getLocation(), 1583 diag::err_param_default_argument_missing); 1584 } 1585 } 1586 } 1587 1588 /// Check that the given type is a literal type. Issue a diagnostic if not, 1589 /// if Kind is Diagnose. 1590 /// \return \c true if a problem has been found (and optionally diagnosed). 1591 template <typename... Ts> 1592 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1593 SourceLocation Loc, QualType T, unsigned DiagID, 1594 Ts &&...DiagArgs) { 1595 if (T->isDependentType()) 1596 return false; 1597 1598 switch (Kind) { 1599 case Sema::CheckConstexprKind::Diagnose: 1600 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1601 std::forward<Ts>(DiagArgs)...); 1602 1603 case Sema::CheckConstexprKind::CheckValid: 1604 return !T->isLiteralType(SemaRef.Context); 1605 } 1606 1607 llvm_unreachable("unknown CheckConstexprKind"); 1608 } 1609 1610 /// Determine whether a destructor cannot be constexpr due to 1611 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1612 const CXXDestructorDecl *DD, 1613 Sema::CheckConstexprKind Kind) { 1614 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1615 const CXXRecordDecl *RD = 1616 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1617 if (!RD || RD->hasConstexprDestructor()) 1618 return true; 1619 1620 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1621 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1622 << DD->getConstexprKind() << !FD 1623 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1624 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1625 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1626 } 1627 return false; 1628 }; 1629 1630 const CXXRecordDecl *RD = DD->getParent(); 1631 for (const CXXBaseSpecifier &B : RD->bases()) 1632 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1633 return false; 1634 for (const FieldDecl *FD : RD->fields()) 1635 if (!Check(FD->getLocation(), FD->getType(), FD)) 1636 return false; 1637 return true; 1638 } 1639 1640 /// Check whether a function's parameter types are all literal types. If so, 1641 /// return true. If not, produce a suitable diagnostic and return false. 1642 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1643 const FunctionDecl *FD, 1644 Sema::CheckConstexprKind Kind) { 1645 unsigned ArgIndex = 0; 1646 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1647 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1648 e = FT->param_type_end(); 1649 i != e; ++i, ++ArgIndex) { 1650 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1651 SourceLocation ParamLoc = PD->getLocation(); 1652 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1653 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1654 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1655 FD->isConsteval())) 1656 return false; 1657 } 1658 return true; 1659 } 1660 1661 /// Check whether a function's return type is a literal type. If so, return 1662 /// true. If not, produce a suitable diagnostic and return false. 1663 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1664 Sema::CheckConstexprKind Kind) { 1665 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1666 diag::err_constexpr_non_literal_return, 1667 FD->isConsteval())) 1668 return false; 1669 return true; 1670 } 1671 1672 /// Get diagnostic %select index for tag kind for 1673 /// record diagnostic message. 1674 /// WARNING: Indexes apply to particular diagnostics only! 1675 /// 1676 /// \returns diagnostic %select index. 1677 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1678 switch (Tag) { 1679 case TTK_Struct: return 0; 1680 case TTK_Interface: return 1; 1681 case TTK_Class: return 2; 1682 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1683 } 1684 } 1685 1686 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1687 Stmt *Body, 1688 Sema::CheckConstexprKind Kind); 1689 1690 // Check whether a function declaration satisfies the requirements of a 1691 // constexpr function definition or a constexpr constructor definition. If so, 1692 // return true. If not, produce appropriate diagnostics (unless asked not to by 1693 // Kind) and return false. 1694 // 1695 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1696 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1697 CheckConstexprKind Kind) { 1698 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1699 if (MD && MD->isInstance()) { 1700 // C++11 [dcl.constexpr]p4: 1701 // The definition of a constexpr constructor shall satisfy the following 1702 // constraints: 1703 // - the class shall not have any virtual base classes; 1704 // 1705 // FIXME: This only applies to constructors and destructors, not arbitrary 1706 // member functions. 1707 const CXXRecordDecl *RD = MD->getParent(); 1708 if (RD->getNumVBases()) { 1709 if (Kind == CheckConstexprKind::CheckValid) 1710 return false; 1711 1712 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1713 << isa<CXXConstructorDecl>(NewFD) 1714 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1715 for (const auto &I : RD->vbases()) 1716 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1717 << I.getSourceRange(); 1718 return false; 1719 } 1720 } 1721 1722 if (!isa<CXXConstructorDecl>(NewFD)) { 1723 // C++11 [dcl.constexpr]p3: 1724 // The definition of a constexpr function shall satisfy the following 1725 // constraints: 1726 // - it shall not be virtual; (removed in C++20) 1727 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1728 if (Method && Method->isVirtual()) { 1729 if (getLangOpts().CPlusPlus20) { 1730 if (Kind == CheckConstexprKind::Diagnose) 1731 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1732 } else { 1733 if (Kind == CheckConstexprKind::CheckValid) 1734 return false; 1735 1736 Method = Method->getCanonicalDecl(); 1737 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1738 1739 // If it's not obvious why this function is virtual, find an overridden 1740 // function which uses the 'virtual' keyword. 1741 const CXXMethodDecl *WrittenVirtual = Method; 1742 while (!WrittenVirtual->isVirtualAsWritten()) 1743 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1744 if (WrittenVirtual != Method) 1745 Diag(WrittenVirtual->getLocation(), 1746 diag::note_overridden_virtual_function); 1747 return false; 1748 } 1749 } 1750 1751 // - its return type shall be a literal type; 1752 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1753 return false; 1754 } 1755 1756 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1757 // A destructor can be constexpr only if the defaulted destructor could be; 1758 // we don't need to check the members and bases if we already know they all 1759 // have constexpr destructors. 1760 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1761 if (Kind == CheckConstexprKind::CheckValid) 1762 return false; 1763 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1764 return false; 1765 } 1766 } 1767 1768 // - each of its parameter types shall be a literal type; 1769 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1770 return false; 1771 1772 Stmt *Body = NewFD->getBody(); 1773 assert(Body && 1774 "CheckConstexprFunctionDefinition called on function with no body"); 1775 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1776 } 1777 1778 /// Check the given declaration statement is legal within a constexpr function 1779 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1780 /// 1781 /// \return true if the body is OK (maybe only as an extension), false if we 1782 /// have diagnosed a problem. 1783 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1784 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1785 Sema::CheckConstexprKind Kind) { 1786 // C++11 [dcl.constexpr]p3 and p4: 1787 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1788 // contain only 1789 for (const auto *DclIt : DS->decls()) { 1790 switch (DclIt->getKind()) { 1791 case Decl::StaticAssert: 1792 case Decl::Using: 1793 case Decl::UsingShadow: 1794 case Decl::UsingDirective: 1795 case Decl::UnresolvedUsingTypename: 1796 case Decl::UnresolvedUsingValue: 1797 // - static_assert-declarations 1798 // - using-declarations, 1799 // - using-directives, 1800 continue; 1801 1802 case Decl::Typedef: 1803 case Decl::TypeAlias: { 1804 // - typedef declarations and alias-declarations that do not define 1805 // classes or enumerations, 1806 const auto *TN = cast<TypedefNameDecl>(DclIt); 1807 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1808 // Don't allow variably-modified types in constexpr functions. 1809 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1810 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1811 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1812 << TL.getSourceRange() << TL.getType() 1813 << isa<CXXConstructorDecl>(Dcl); 1814 } 1815 return false; 1816 } 1817 continue; 1818 } 1819 1820 case Decl::Enum: 1821 case Decl::CXXRecord: 1822 // C++1y allows types to be defined, not just declared. 1823 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1824 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1825 SemaRef.Diag(DS->getBeginLoc(), 1826 SemaRef.getLangOpts().CPlusPlus14 1827 ? diag::warn_cxx11_compat_constexpr_type_definition 1828 : diag::ext_constexpr_type_definition) 1829 << isa<CXXConstructorDecl>(Dcl); 1830 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1831 return false; 1832 } 1833 } 1834 continue; 1835 1836 case Decl::EnumConstant: 1837 case Decl::IndirectField: 1838 case Decl::ParmVar: 1839 // These can only appear with other declarations which are banned in 1840 // C++11 and permitted in C++1y, so ignore them. 1841 continue; 1842 1843 case Decl::Var: 1844 case Decl::Decomposition: { 1845 // C++1y [dcl.constexpr]p3 allows anything except: 1846 // a definition of a variable of non-literal type or of static or 1847 // thread storage duration or [before C++2a] for which no 1848 // initialization is performed. 1849 const auto *VD = cast<VarDecl>(DclIt); 1850 if (VD->isThisDeclarationADefinition()) { 1851 if (VD->isStaticLocal()) { 1852 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1853 SemaRef.Diag(VD->getLocation(), 1854 diag::err_constexpr_local_var_static) 1855 << isa<CXXConstructorDecl>(Dcl) 1856 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1857 } 1858 return false; 1859 } 1860 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1861 diag::err_constexpr_local_var_non_literal_type, 1862 isa<CXXConstructorDecl>(Dcl))) 1863 return false; 1864 if (!VD->getType()->isDependentType() && 1865 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1866 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1867 SemaRef.Diag( 1868 VD->getLocation(), 1869 SemaRef.getLangOpts().CPlusPlus20 1870 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1871 : diag::ext_constexpr_local_var_no_init) 1872 << isa<CXXConstructorDecl>(Dcl); 1873 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1874 return false; 1875 } 1876 continue; 1877 } 1878 } 1879 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1880 SemaRef.Diag(VD->getLocation(), 1881 SemaRef.getLangOpts().CPlusPlus14 1882 ? diag::warn_cxx11_compat_constexpr_local_var 1883 : diag::ext_constexpr_local_var) 1884 << isa<CXXConstructorDecl>(Dcl); 1885 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1886 return false; 1887 } 1888 continue; 1889 } 1890 1891 case Decl::NamespaceAlias: 1892 case Decl::Function: 1893 // These are disallowed in C++11 and permitted in C++1y. Allow them 1894 // everywhere as an extension. 1895 if (!Cxx1yLoc.isValid()) 1896 Cxx1yLoc = DS->getBeginLoc(); 1897 continue; 1898 1899 default: 1900 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1901 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1902 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1903 } 1904 return false; 1905 } 1906 } 1907 1908 return true; 1909 } 1910 1911 /// Check that the given field is initialized within a constexpr constructor. 1912 /// 1913 /// \param Dcl The constexpr constructor being checked. 1914 /// \param Field The field being checked. This may be a member of an anonymous 1915 /// struct or union nested within the class being checked. 1916 /// \param Inits All declarations, including anonymous struct/union members and 1917 /// indirect members, for which any initialization was provided. 1918 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1919 /// multiple notes for different members to the same error. 1920 /// \param Kind Whether we're diagnosing a constructor as written or determining 1921 /// whether the formal requirements are satisfied. 1922 /// \return \c false if we're checking for validity and the constructor does 1923 /// not satisfy the requirements on a constexpr constructor. 1924 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1925 const FunctionDecl *Dcl, 1926 FieldDecl *Field, 1927 llvm::SmallSet<Decl*, 16> &Inits, 1928 bool &Diagnosed, 1929 Sema::CheckConstexprKind Kind) { 1930 // In C++20 onwards, there's nothing to check for validity. 1931 if (Kind == Sema::CheckConstexprKind::CheckValid && 1932 SemaRef.getLangOpts().CPlusPlus20) 1933 return true; 1934 1935 if (Field->isInvalidDecl()) 1936 return true; 1937 1938 if (Field->isUnnamedBitfield()) 1939 return true; 1940 1941 // Anonymous unions with no variant members and empty anonymous structs do not 1942 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1943 // indirect fields don't need initializing. 1944 if (Field->isAnonymousStructOrUnion() && 1945 (Field->getType()->isUnionType() 1946 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1947 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1948 return true; 1949 1950 if (!Inits.count(Field)) { 1951 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1952 if (!Diagnosed) { 1953 SemaRef.Diag(Dcl->getLocation(), 1954 SemaRef.getLangOpts().CPlusPlus20 1955 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1956 : diag::ext_constexpr_ctor_missing_init); 1957 Diagnosed = true; 1958 } 1959 SemaRef.Diag(Field->getLocation(), 1960 diag::note_constexpr_ctor_missing_init); 1961 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1962 return false; 1963 } 1964 } else if (Field->isAnonymousStructOrUnion()) { 1965 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1966 for (auto *I : RD->fields()) 1967 // If an anonymous union contains an anonymous struct of which any member 1968 // is initialized, all members must be initialized. 1969 if (!RD->isUnion() || Inits.count(I)) 1970 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1971 Kind)) 1972 return false; 1973 } 1974 return true; 1975 } 1976 1977 /// Check the provided statement is allowed in a constexpr function 1978 /// definition. 1979 static bool 1980 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1981 SmallVectorImpl<SourceLocation> &ReturnStmts, 1982 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1983 Sema::CheckConstexprKind Kind) { 1984 // - its function-body shall be [...] a compound-statement that contains only 1985 switch (S->getStmtClass()) { 1986 case Stmt::NullStmtClass: 1987 // - null statements, 1988 return true; 1989 1990 case Stmt::DeclStmtClass: 1991 // - static_assert-declarations 1992 // - using-declarations, 1993 // - using-directives, 1994 // - typedef declarations and alias-declarations that do not define 1995 // classes or enumerations, 1996 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1997 return false; 1998 return true; 1999 2000 case Stmt::ReturnStmtClass: 2001 // - and exactly one return statement; 2002 if (isa<CXXConstructorDecl>(Dcl)) { 2003 // C++1y allows return statements in constexpr constructors. 2004 if (!Cxx1yLoc.isValid()) 2005 Cxx1yLoc = S->getBeginLoc(); 2006 return true; 2007 } 2008 2009 ReturnStmts.push_back(S->getBeginLoc()); 2010 return true; 2011 2012 case Stmt::CompoundStmtClass: { 2013 // C++1y allows compound-statements. 2014 if (!Cxx1yLoc.isValid()) 2015 Cxx1yLoc = S->getBeginLoc(); 2016 2017 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2018 for (auto *BodyIt : CompStmt->body()) { 2019 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2020 Cxx1yLoc, Cxx2aLoc, Kind)) 2021 return false; 2022 } 2023 return true; 2024 } 2025 2026 case Stmt::AttributedStmtClass: 2027 if (!Cxx1yLoc.isValid()) 2028 Cxx1yLoc = S->getBeginLoc(); 2029 return true; 2030 2031 case Stmt::IfStmtClass: { 2032 // C++1y allows if-statements. 2033 if (!Cxx1yLoc.isValid()) 2034 Cxx1yLoc = S->getBeginLoc(); 2035 2036 IfStmt *If = cast<IfStmt>(S); 2037 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2038 Cxx1yLoc, Cxx2aLoc, Kind)) 2039 return false; 2040 if (If->getElse() && 2041 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2042 Cxx1yLoc, Cxx2aLoc, Kind)) 2043 return false; 2044 return true; 2045 } 2046 2047 case Stmt::WhileStmtClass: 2048 case Stmt::DoStmtClass: 2049 case Stmt::ForStmtClass: 2050 case Stmt::CXXForRangeStmtClass: 2051 case Stmt::ContinueStmtClass: 2052 // C++1y allows all of these. We don't allow them as extensions in C++11, 2053 // because they don't make sense without variable mutation. 2054 if (!SemaRef.getLangOpts().CPlusPlus14) 2055 break; 2056 if (!Cxx1yLoc.isValid()) 2057 Cxx1yLoc = S->getBeginLoc(); 2058 for (Stmt *SubStmt : S->children()) 2059 if (SubStmt && 2060 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2061 Cxx1yLoc, Cxx2aLoc, Kind)) 2062 return false; 2063 return true; 2064 2065 case Stmt::SwitchStmtClass: 2066 case Stmt::CaseStmtClass: 2067 case Stmt::DefaultStmtClass: 2068 case Stmt::BreakStmtClass: 2069 // C++1y allows switch-statements, and since they don't need variable 2070 // mutation, we can reasonably allow them in C++11 as an extension. 2071 if (!Cxx1yLoc.isValid()) 2072 Cxx1yLoc = S->getBeginLoc(); 2073 for (Stmt *SubStmt : S->children()) 2074 if (SubStmt && 2075 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2076 Cxx1yLoc, Cxx2aLoc, Kind)) 2077 return false; 2078 return true; 2079 2080 case Stmt::GCCAsmStmtClass: 2081 case Stmt::MSAsmStmtClass: 2082 // C++2a allows inline assembly statements. 2083 case Stmt::CXXTryStmtClass: 2084 if (Cxx2aLoc.isInvalid()) 2085 Cxx2aLoc = S->getBeginLoc(); 2086 for (Stmt *SubStmt : S->children()) { 2087 if (SubStmt && 2088 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2089 Cxx1yLoc, Cxx2aLoc, Kind)) 2090 return false; 2091 } 2092 return true; 2093 2094 case Stmt::CXXCatchStmtClass: 2095 // Do not bother checking the language mode (already covered by the 2096 // try block check). 2097 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2098 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2099 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2100 return false; 2101 return true; 2102 2103 default: 2104 if (!isa<Expr>(S)) 2105 break; 2106 2107 // C++1y allows expression-statements. 2108 if (!Cxx1yLoc.isValid()) 2109 Cxx1yLoc = S->getBeginLoc(); 2110 return true; 2111 } 2112 2113 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2114 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2115 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2116 } 2117 return false; 2118 } 2119 2120 /// Check the body for the given constexpr function declaration only contains 2121 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2122 /// 2123 /// \return true if the body is OK, false if we have found or diagnosed a 2124 /// problem. 2125 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2126 Stmt *Body, 2127 Sema::CheckConstexprKind Kind) { 2128 SmallVector<SourceLocation, 4> ReturnStmts; 2129 2130 if (isa<CXXTryStmt>(Body)) { 2131 // C++11 [dcl.constexpr]p3: 2132 // The definition of a constexpr function shall satisfy the following 2133 // constraints: [...] 2134 // - its function-body shall be = delete, = default, or a 2135 // compound-statement 2136 // 2137 // C++11 [dcl.constexpr]p4: 2138 // In the definition of a constexpr constructor, [...] 2139 // - its function-body shall not be a function-try-block; 2140 // 2141 // This restriction is lifted in C++2a, as long as inner statements also 2142 // apply the general constexpr rules. 2143 switch (Kind) { 2144 case Sema::CheckConstexprKind::CheckValid: 2145 if (!SemaRef.getLangOpts().CPlusPlus20) 2146 return false; 2147 break; 2148 2149 case Sema::CheckConstexprKind::Diagnose: 2150 SemaRef.Diag(Body->getBeginLoc(), 2151 !SemaRef.getLangOpts().CPlusPlus20 2152 ? diag::ext_constexpr_function_try_block_cxx20 2153 : diag::warn_cxx17_compat_constexpr_function_try_block) 2154 << isa<CXXConstructorDecl>(Dcl); 2155 break; 2156 } 2157 } 2158 2159 // - its function-body shall be [...] a compound-statement that contains only 2160 // [... list of cases ...] 2161 // 2162 // Note that walking the children here is enough to properly check for 2163 // CompoundStmt and CXXTryStmt body. 2164 SourceLocation Cxx1yLoc, Cxx2aLoc; 2165 for (Stmt *SubStmt : Body->children()) { 2166 if (SubStmt && 2167 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2168 Cxx1yLoc, Cxx2aLoc, Kind)) 2169 return false; 2170 } 2171 2172 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2173 // If this is only valid as an extension, report that we don't satisfy the 2174 // constraints of the current language. 2175 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2176 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2177 return false; 2178 } else if (Cxx2aLoc.isValid()) { 2179 SemaRef.Diag(Cxx2aLoc, 2180 SemaRef.getLangOpts().CPlusPlus20 2181 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2182 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2183 << isa<CXXConstructorDecl>(Dcl); 2184 } else if (Cxx1yLoc.isValid()) { 2185 SemaRef.Diag(Cxx1yLoc, 2186 SemaRef.getLangOpts().CPlusPlus14 2187 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2188 : diag::ext_constexpr_body_invalid_stmt) 2189 << isa<CXXConstructorDecl>(Dcl); 2190 } 2191 2192 if (const CXXConstructorDecl *Constructor 2193 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2194 const CXXRecordDecl *RD = Constructor->getParent(); 2195 // DR1359: 2196 // - every non-variant non-static data member and base class sub-object 2197 // shall be initialized; 2198 // DR1460: 2199 // - if the class is a union having variant members, exactly one of them 2200 // shall be initialized; 2201 if (RD->isUnion()) { 2202 if (Constructor->getNumCtorInitializers() == 0 && 2203 RD->hasVariantMembers()) { 2204 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2205 SemaRef.Diag( 2206 Dcl->getLocation(), 2207 SemaRef.getLangOpts().CPlusPlus20 2208 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2209 : diag::ext_constexpr_union_ctor_no_init); 2210 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2211 return false; 2212 } 2213 } 2214 } else if (!Constructor->isDependentContext() && 2215 !Constructor->isDelegatingConstructor()) { 2216 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2217 2218 // Skip detailed checking if we have enough initializers, and we would 2219 // allow at most one initializer per member. 2220 bool AnyAnonStructUnionMembers = false; 2221 unsigned Fields = 0; 2222 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2223 E = RD->field_end(); I != E; ++I, ++Fields) { 2224 if (I->isAnonymousStructOrUnion()) { 2225 AnyAnonStructUnionMembers = true; 2226 break; 2227 } 2228 } 2229 // DR1460: 2230 // - if the class is a union-like class, but is not a union, for each of 2231 // its anonymous union members having variant members, exactly one of 2232 // them shall be initialized; 2233 if (AnyAnonStructUnionMembers || 2234 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2235 // Check initialization of non-static data members. Base classes are 2236 // always initialized so do not need to be checked. Dependent bases 2237 // might not have initializers in the member initializer list. 2238 llvm::SmallSet<Decl*, 16> Inits; 2239 for (const auto *I: Constructor->inits()) { 2240 if (FieldDecl *FD = I->getMember()) 2241 Inits.insert(FD); 2242 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2243 Inits.insert(ID->chain_begin(), ID->chain_end()); 2244 } 2245 2246 bool Diagnosed = false; 2247 for (auto *I : RD->fields()) 2248 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2249 Kind)) 2250 return false; 2251 } 2252 } 2253 } else { 2254 if (ReturnStmts.empty()) { 2255 // C++1y doesn't require constexpr functions to contain a 'return' 2256 // statement. We still do, unless the return type might be void, because 2257 // otherwise if there's no return statement, the function cannot 2258 // be used in a core constant expression. 2259 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2260 (Dcl->getReturnType()->isVoidType() || 2261 Dcl->getReturnType()->isDependentType()); 2262 switch (Kind) { 2263 case Sema::CheckConstexprKind::Diagnose: 2264 SemaRef.Diag(Dcl->getLocation(), 2265 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2266 : diag::err_constexpr_body_no_return) 2267 << Dcl->isConsteval(); 2268 if (!OK) 2269 return false; 2270 break; 2271 2272 case Sema::CheckConstexprKind::CheckValid: 2273 // The formal requirements don't include this rule in C++14, even 2274 // though the "must be able to produce a constant expression" rules 2275 // still imply it in some cases. 2276 if (!SemaRef.getLangOpts().CPlusPlus14) 2277 return false; 2278 break; 2279 } 2280 } else if (ReturnStmts.size() > 1) { 2281 switch (Kind) { 2282 case Sema::CheckConstexprKind::Diagnose: 2283 SemaRef.Diag( 2284 ReturnStmts.back(), 2285 SemaRef.getLangOpts().CPlusPlus14 2286 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2287 : diag::ext_constexpr_body_multiple_return); 2288 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2289 SemaRef.Diag(ReturnStmts[I], 2290 diag::note_constexpr_body_previous_return); 2291 break; 2292 2293 case Sema::CheckConstexprKind::CheckValid: 2294 if (!SemaRef.getLangOpts().CPlusPlus14) 2295 return false; 2296 break; 2297 } 2298 } 2299 } 2300 2301 // C++11 [dcl.constexpr]p5: 2302 // if no function argument values exist such that the function invocation 2303 // substitution would produce a constant expression, the program is 2304 // ill-formed; no diagnostic required. 2305 // C++11 [dcl.constexpr]p3: 2306 // - every constructor call and implicit conversion used in initializing the 2307 // return value shall be one of those allowed in a constant expression. 2308 // C++11 [dcl.constexpr]p4: 2309 // - every constructor involved in initializing non-static data members and 2310 // base class sub-objects shall be a constexpr constructor. 2311 // 2312 // Note that this rule is distinct from the "requirements for a constexpr 2313 // function", so is not checked in CheckValid mode. 2314 SmallVector<PartialDiagnosticAt, 8> Diags; 2315 if (Kind == Sema::CheckConstexprKind::Diagnose && 2316 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2317 SemaRef.Diag(Dcl->getLocation(), 2318 diag::ext_constexpr_function_never_constant_expr) 2319 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2320 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2321 SemaRef.Diag(Diags[I].first, Diags[I].second); 2322 // Don't return false here: we allow this for compatibility in 2323 // system headers. 2324 } 2325 2326 return true; 2327 } 2328 2329 /// Get the class that is directly named by the current context. This is the 2330 /// class for which an unqualified-id in this scope could name a constructor 2331 /// or destructor. 2332 /// 2333 /// If the scope specifier denotes a class, this will be that class. 2334 /// If the scope specifier is empty, this will be the class whose 2335 /// member-specification we are currently within. Otherwise, there 2336 /// is no such class. 2337 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2338 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2339 2340 if (SS && SS->isInvalid()) 2341 return nullptr; 2342 2343 if (SS && SS->isNotEmpty()) { 2344 DeclContext *DC = computeDeclContext(*SS, true); 2345 return dyn_cast_or_null<CXXRecordDecl>(DC); 2346 } 2347 2348 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2349 } 2350 2351 /// isCurrentClassName - Determine whether the identifier II is the 2352 /// name of the class type currently being defined. In the case of 2353 /// nested classes, this will only return true if II is the name of 2354 /// the innermost class. 2355 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2356 const CXXScopeSpec *SS) { 2357 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2358 return CurDecl && &II == CurDecl->getIdentifier(); 2359 } 2360 2361 /// Determine whether the identifier II is a typo for the name of 2362 /// the class type currently being defined. If so, update it to the identifier 2363 /// that should have been used. 2364 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2365 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2366 2367 if (!getLangOpts().SpellChecking) 2368 return false; 2369 2370 CXXRecordDecl *CurDecl; 2371 if (SS && SS->isSet() && !SS->isInvalid()) { 2372 DeclContext *DC = computeDeclContext(*SS, true); 2373 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2374 } else 2375 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2376 2377 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2378 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2379 < II->getLength()) { 2380 II = CurDecl->getIdentifier(); 2381 return true; 2382 } 2383 2384 return false; 2385 } 2386 2387 /// Determine whether the given class is a base class of the given 2388 /// class, including looking at dependent bases. 2389 static bool findCircularInheritance(const CXXRecordDecl *Class, 2390 const CXXRecordDecl *Current) { 2391 SmallVector<const CXXRecordDecl*, 8> Queue; 2392 2393 Class = Class->getCanonicalDecl(); 2394 while (true) { 2395 for (const auto &I : Current->bases()) { 2396 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2397 if (!Base) 2398 continue; 2399 2400 Base = Base->getDefinition(); 2401 if (!Base) 2402 continue; 2403 2404 if (Base->getCanonicalDecl() == Class) 2405 return true; 2406 2407 Queue.push_back(Base); 2408 } 2409 2410 if (Queue.empty()) 2411 return false; 2412 2413 Current = Queue.pop_back_val(); 2414 } 2415 2416 return false; 2417 } 2418 2419 /// Check the validity of a C++ base class specifier. 2420 /// 2421 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2422 /// and returns NULL otherwise. 2423 CXXBaseSpecifier * 2424 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2425 SourceRange SpecifierRange, 2426 bool Virtual, AccessSpecifier Access, 2427 TypeSourceInfo *TInfo, 2428 SourceLocation EllipsisLoc) { 2429 QualType BaseType = TInfo->getType(); 2430 if (BaseType->containsErrors()) { 2431 // Already emitted a diagnostic when parsing the error type. 2432 return nullptr; 2433 } 2434 // C++ [class.union]p1: 2435 // A union shall not have base classes. 2436 if (Class->isUnion()) { 2437 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2438 << SpecifierRange; 2439 return nullptr; 2440 } 2441 2442 if (EllipsisLoc.isValid() && 2443 !TInfo->getType()->containsUnexpandedParameterPack()) { 2444 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2445 << TInfo->getTypeLoc().getSourceRange(); 2446 EllipsisLoc = SourceLocation(); 2447 } 2448 2449 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2450 2451 if (BaseType->isDependentType()) { 2452 // Make sure that we don't have circular inheritance among our dependent 2453 // bases. For non-dependent bases, the check for completeness below handles 2454 // this. 2455 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2456 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2457 ((BaseDecl = BaseDecl->getDefinition()) && 2458 findCircularInheritance(Class, BaseDecl))) { 2459 Diag(BaseLoc, diag::err_circular_inheritance) 2460 << BaseType << Context.getTypeDeclType(Class); 2461 2462 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2463 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2464 << BaseType; 2465 2466 return nullptr; 2467 } 2468 } 2469 2470 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2471 Class->getTagKind() == TTK_Class, 2472 Access, TInfo, EllipsisLoc); 2473 } 2474 2475 // Base specifiers must be record types. 2476 if (!BaseType->isRecordType()) { 2477 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2478 return nullptr; 2479 } 2480 2481 // C++ [class.union]p1: 2482 // A union shall not be used as a base class. 2483 if (BaseType->isUnionType()) { 2484 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2485 return nullptr; 2486 } 2487 2488 // For the MS ABI, propagate DLL attributes to base class templates. 2489 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2490 if (Attr *ClassAttr = getDLLAttr(Class)) { 2491 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2492 BaseType->getAsCXXRecordDecl())) { 2493 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2494 BaseLoc); 2495 } 2496 } 2497 } 2498 2499 // C++ [class.derived]p2: 2500 // The class-name in a base-specifier shall not be an incompletely 2501 // defined class. 2502 if (RequireCompleteType(BaseLoc, BaseType, 2503 diag::err_incomplete_base_class, SpecifierRange)) { 2504 Class->setInvalidDecl(); 2505 return nullptr; 2506 } 2507 2508 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2509 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2510 assert(BaseDecl && "Record type has no declaration"); 2511 BaseDecl = BaseDecl->getDefinition(); 2512 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2513 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2514 assert(CXXBaseDecl && "Base type is not a C++ type"); 2515 2516 // Microsoft docs say: 2517 // "If a base-class has a code_seg attribute, derived classes must have the 2518 // same attribute." 2519 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2520 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2521 if ((DerivedCSA || BaseCSA) && 2522 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2523 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2524 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2525 << CXXBaseDecl; 2526 return nullptr; 2527 } 2528 2529 // A class which contains a flexible array member is not suitable for use as a 2530 // base class: 2531 // - If the layout determines that a base comes before another base, 2532 // the flexible array member would index into the subsequent base. 2533 // - If the layout determines that base comes before the derived class, 2534 // the flexible array member would index into the derived class. 2535 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2536 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2537 << CXXBaseDecl->getDeclName(); 2538 return nullptr; 2539 } 2540 2541 // C++ [class]p3: 2542 // If a class is marked final and it appears as a base-type-specifier in 2543 // base-clause, the program is ill-formed. 2544 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2545 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2546 << CXXBaseDecl->getDeclName() 2547 << FA->isSpelledAsSealed(); 2548 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2549 << CXXBaseDecl->getDeclName() << FA->getRange(); 2550 return nullptr; 2551 } 2552 2553 if (BaseDecl->isInvalidDecl()) 2554 Class->setInvalidDecl(); 2555 2556 // Create the base specifier. 2557 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2558 Class->getTagKind() == TTK_Class, 2559 Access, TInfo, EllipsisLoc); 2560 } 2561 2562 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2563 /// one entry in the base class list of a class specifier, for 2564 /// example: 2565 /// class foo : public bar, virtual private baz { 2566 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2567 BaseResult 2568 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2569 ParsedAttributes &Attributes, 2570 bool Virtual, AccessSpecifier Access, 2571 ParsedType basetype, SourceLocation BaseLoc, 2572 SourceLocation EllipsisLoc) { 2573 if (!classdecl) 2574 return true; 2575 2576 AdjustDeclIfTemplate(classdecl); 2577 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2578 if (!Class) 2579 return true; 2580 2581 // We haven't yet attached the base specifiers. 2582 Class->setIsParsingBaseSpecifiers(); 2583 2584 // We do not support any C++11 attributes on base-specifiers yet. 2585 // Diagnose any attributes we see. 2586 for (const ParsedAttr &AL : Attributes) { 2587 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2588 continue; 2589 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2590 ? (unsigned)diag::warn_unknown_attribute_ignored 2591 : (unsigned)diag::err_base_specifier_attribute) 2592 << AL; 2593 } 2594 2595 TypeSourceInfo *TInfo = nullptr; 2596 GetTypeFromParser(basetype, &TInfo); 2597 2598 if (EllipsisLoc.isInvalid() && 2599 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2600 UPPC_BaseType)) 2601 return true; 2602 2603 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2604 Virtual, Access, TInfo, 2605 EllipsisLoc)) 2606 return BaseSpec; 2607 else 2608 Class->setInvalidDecl(); 2609 2610 return true; 2611 } 2612 2613 /// Use small set to collect indirect bases. As this is only used 2614 /// locally, there's no need to abstract the small size parameter. 2615 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2616 2617 /// Recursively add the bases of Type. Don't add Type itself. 2618 static void 2619 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2620 const QualType &Type) 2621 { 2622 // Even though the incoming type is a base, it might not be 2623 // a class -- it could be a template parm, for instance. 2624 if (auto Rec = Type->getAs<RecordType>()) { 2625 auto Decl = Rec->getAsCXXRecordDecl(); 2626 2627 // Iterate over its bases. 2628 for (const auto &BaseSpec : Decl->bases()) { 2629 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2630 .getUnqualifiedType(); 2631 if (Set.insert(Base).second) 2632 // If we've not already seen it, recurse. 2633 NoteIndirectBases(Context, Set, Base); 2634 } 2635 } 2636 } 2637 2638 /// Performs the actual work of attaching the given base class 2639 /// specifiers to a C++ class. 2640 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2641 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2642 if (Bases.empty()) 2643 return false; 2644 2645 // Used to keep track of which base types we have already seen, so 2646 // that we can properly diagnose redundant direct base types. Note 2647 // that the key is always the unqualified canonical type of the base 2648 // class. 2649 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2650 2651 // Used to track indirect bases so we can see if a direct base is 2652 // ambiguous. 2653 IndirectBaseSet IndirectBaseTypes; 2654 2655 // Copy non-redundant base specifiers into permanent storage. 2656 unsigned NumGoodBases = 0; 2657 bool Invalid = false; 2658 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2659 QualType NewBaseType 2660 = Context.getCanonicalType(Bases[idx]->getType()); 2661 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2662 2663 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2664 if (KnownBase) { 2665 // C++ [class.mi]p3: 2666 // A class shall not be specified as a direct base class of a 2667 // derived class more than once. 2668 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2669 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2670 2671 // Delete the duplicate base class specifier; we're going to 2672 // overwrite its pointer later. 2673 Context.Deallocate(Bases[idx]); 2674 2675 Invalid = true; 2676 } else { 2677 // Okay, add this new base class. 2678 KnownBase = Bases[idx]; 2679 Bases[NumGoodBases++] = Bases[idx]; 2680 2681 // Note this base's direct & indirect bases, if there could be ambiguity. 2682 if (Bases.size() > 1) 2683 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2684 2685 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2686 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2687 if (Class->isInterface() && 2688 (!RD->isInterfaceLike() || 2689 KnownBase->getAccessSpecifier() != AS_public)) { 2690 // The Microsoft extension __interface does not permit bases that 2691 // are not themselves public interfaces. 2692 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2693 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2694 << RD->getSourceRange(); 2695 Invalid = true; 2696 } 2697 if (RD->hasAttr<WeakAttr>()) 2698 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2699 } 2700 } 2701 } 2702 2703 // Attach the remaining base class specifiers to the derived class. 2704 Class->setBases(Bases.data(), NumGoodBases); 2705 2706 // Check that the only base classes that are duplicate are virtual. 2707 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2708 // Check whether this direct base is inaccessible due to ambiguity. 2709 QualType BaseType = Bases[idx]->getType(); 2710 2711 // Skip all dependent types in templates being used as base specifiers. 2712 // Checks below assume that the base specifier is a CXXRecord. 2713 if (BaseType->isDependentType()) 2714 continue; 2715 2716 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2717 .getUnqualifiedType(); 2718 2719 if (IndirectBaseTypes.count(CanonicalBase)) { 2720 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2721 /*DetectVirtual=*/true); 2722 bool found 2723 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2724 assert(found); 2725 (void)found; 2726 2727 if (Paths.isAmbiguous(CanonicalBase)) 2728 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2729 << BaseType << getAmbiguousPathsDisplayString(Paths) 2730 << Bases[idx]->getSourceRange(); 2731 else 2732 assert(Bases[idx]->isVirtual()); 2733 } 2734 2735 // Delete the base class specifier, since its data has been copied 2736 // into the CXXRecordDecl. 2737 Context.Deallocate(Bases[idx]); 2738 } 2739 2740 return Invalid; 2741 } 2742 2743 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2744 /// class, after checking whether there are any duplicate base 2745 /// classes. 2746 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2747 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2748 if (!ClassDecl || Bases.empty()) 2749 return; 2750 2751 AdjustDeclIfTemplate(ClassDecl); 2752 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2753 } 2754 2755 /// Determine whether the type \p Derived is a C++ class that is 2756 /// derived from the type \p Base. 2757 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2758 if (!getLangOpts().CPlusPlus) 2759 return false; 2760 2761 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2762 if (!DerivedRD) 2763 return false; 2764 2765 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2766 if (!BaseRD) 2767 return false; 2768 2769 // If either the base or the derived type is invalid, don't try to 2770 // check whether one is derived from the other. 2771 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2772 return false; 2773 2774 // FIXME: In a modules build, do we need the entire path to be visible for us 2775 // to be able to use the inheritance relationship? 2776 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2777 return false; 2778 2779 return DerivedRD->isDerivedFrom(BaseRD); 2780 } 2781 2782 /// Determine whether the type \p Derived is a C++ class that is 2783 /// derived from the type \p Base. 2784 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2785 CXXBasePaths &Paths) { 2786 if (!getLangOpts().CPlusPlus) 2787 return false; 2788 2789 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2790 if (!DerivedRD) 2791 return false; 2792 2793 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2794 if (!BaseRD) 2795 return false; 2796 2797 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2798 return false; 2799 2800 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2801 } 2802 2803 static void BuildBasePathArray(const CXXBasePath &Path, 2804 CXXCastPath &BasePathArray) { 2805 // We first go backward and check if we have a virtual base. 2806 // FIXME: It would be better if CXXBasePath had the base specifier for 2807 // the nearest virtual base. 2808 unsigned Start = 0; 2809 for (unsigned I = Path.size(); I != 0; --I) { 2810 if (Path[I - 1].Base->isVirtual()) { 2811 Start = I - 1; 2812 break; 2813 } 2814 } 2815 2816 // Now add all bases. 2817 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2818 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2819 } 2820 2821 2822 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2823 CXXCastPath &BasePathArray) { 2824 assert(BasePathArray.empty() && "Base path array must be empty!"); 2825 assert(Paths.isRecordingPaths() && "Must record paths!"); 2826 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2827 } 2828 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2829 /// conversion (where Derived and Base are class types) is 2830 /// well-formed, meaning that the conversion is unambiguous (and 2831 /// that all of the base classes are accessible). Returns true 2832 /// and emits a diagnostic if the code is ill-formed, returns false 2833 /// otherwise. Loc is the location where this routine should point to 2834 /// if there is an error, and Range is the source range to highlight 2835 /// if there is an error. 2836 /// 2837 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2838 /// diagnostic for the respective type of error will be suppressed, but the 2839 /// check for ill-formed code will still be performed. 2840 bool 2841 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2842 unsigned InaccessibleBaseID, 2843 unsigned AmbiguousBaseConvID, 2844 SourceLocation Loc, SourceRange Range, 2845 DeclarationName Name, 2846 CXXCastPath *BasePath, 2847 bool IgnoreAccess) { 2848 // First, determine whether the path from Derived to Base is 2849 // ambiguous. This is slightly more expensive than checking whether 2850 // the Derived to Base conversion exists, because here we need to 2851 // explore multiple paths to determine if there is an ambiguity. 2852 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2853 /*DetectVirtual=*/false); 2854 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2855 if (!DerivationOkay) 2856 return true; 2857 2858 const CXXBasePath *Path = nullptr; 2859 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2860 Path = &Paths.front(); 2861 2862 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2863 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2864 // user to access such bases. 2865 if (!Path && getLangOpts().MSVCCompat) { 2866 for (const CXXBasePath &PossiblePath : Paths) { 2867 if (PossiblePath.size() == 1) { 2868 Path = &PossiblePath; 2869 if (AmbiguousBaseConvID) 2870 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2871 << Base << Derived << Range; 2872 break; 2873 } 2874 } 2875 } 2876 2877 if (Path) { 2878 if (!IgnoreAccess) { 2879 // Check that the base class can be accessed. 2880 switch ( 2881 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2882 case AR_inaccessible: 2883 return true; 2884 case AR_accessible: 2885 case AR_dependent: 2886 case AR_delayed: 2887 break; 2888 } 2889 } 2890 2891 // Build a base path if necessary. 2892 if (BasePath) 2893 ::BuildBasePathArray(*Path, *BasePath); 2894 return false; 2895 } 2896 2897 if (AmbiguousBaseConvID) { 2898 // We know that the derived-to-base conversion is ambiguous, and 2899 // we're going to produce a diagnostic. Perform the derived-to-base 2900 // search just one more time to compute all of the possible paths so 2901 // that we can print them out. This is more expensive than any of 2902 // the previous derived-to-base checks we've done, but at this point 2903 // performance isn't as much of an issue. 2904 Paths.clear(); 2905 Paths.setRecordingPaths(true); 2906 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2907 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2908 (void)StillOkay; 2909 2910 // Build up a textual representation of the ambiguous paths, e.g., 2911 // D -> B -> A, that will be used to illustrate the ambiguous 2912 // conversions in the diagnostic. We only print one of the paths 2913 // to each base class subobject. 2914 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2915 2916 Diag(Loc, AmbiguousBaseConvID) 2917 << Derived << Base << PathDisplayStr << Range << Name; 2918 } 2919 return true; 2920 } 2921 2922 bool 2923 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2924 SourceLocation Loc, SourceRange Range, 2925 CXXCastPath *BasePath, 2926 bool IgnoreAccess) { 2927 return CheckDerivedToBaseConversion( 2928 Derived, Base, diag::err_upcast_to_inaccessible_base, 2929 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2930 BasePath, IgnoreAccess); 2931 } 2932 2933 2934 /// Builds a string representing ambiguous paths from a 2935 /// specific derived class to different subobjects of the same base 2936 /// class. 2937 /// 2938 /// This function builds a string that can be used in error messages 2939 /// to show the different paths that one can take through the 2940 /// inheritance hierarchy to go from the derived class to different 2941 /// subobjects of a base class. The result looks something like this: 2942 /// @code 2943 /// struct D -> struct B -> struct A 2944 /// struct D -> struct C -> struct A 2945 /// @endcode 2946 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2947 std::string PathDisplayStr; 2948 std::set<unsigned> DisplayedPaths; 2949 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2950 Path != Paths.end(); ++Path) { 2951 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2952 // We haven't displayed a path to this particular base 2953 // class subobject yet. 2954 PathDisplayStr += "\n "; 2955 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2956 for (CXXBasePath::const_iterator Element = Path->begin(); 2957 Element != Path->end(); ++Element) 2958 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2959 } 2960 } 2961 2962 return PathDisplayStr; 2963 } 2964 2965 //===----------------------------------------------------------------------===// 2966 // C++ class member Handling 2967 //===----------------------------------------------------------------------===// 2968 2969 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2970 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2971 SourceLocation ColonLoc, 2972 const ParsedAttributesView &Attrs) { 2973 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2974 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2975 ASLoc, ColonLoc); 2976 CurContext->addHiddenDecl(ASDecl); 2977 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2978 } 2979 2980 /// CheckOverrideControl - Check C++11 override control semantics. 2981 void Sema::CheckOverrideControl(NamedDecl *D) { 2982 if (D->isInvalidDecl()) 2983 return; 2984 2985 // We only care about "override" and "final" declarations. 2986 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2987 return; 2988 2989 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2990 2991 // We can't check dependent instance methods. 2992 if (MD && MD->isInstance() && 2993 (MD->getParent()->hasAnyDependentBases() || 2994 MD->getType()->isDependentType())) 2995 return; 2996 2997 if (MD && !MD->isVirtual()) { 2998 // If we have a non-virtual method, check if if hides a virtual method. 2999 // (In that case, it's most likely the method has the wrong type.) 3000 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3001 FindHiddenVirtualMethods(MD, OverloadedMethods); 3002 3003 if (!OverloadedMethods.empty()) { 3004 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3005 Diag(OA->getLocation(), 3006 diag::override_keyword_hides_virtual_member_function) 3007 << "override" << (OverloadedMethods.size() > 1); 3008 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3009 Diag(FA->getLocation(), 3010 diag::override_keyword_hides_virtual_member_function) 3011 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3012 << (OverloadedMethods.size() > 1); 3013 } 3014 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3015 MD->setInvalidDecl(); 3016 return; 3017 } 3018 // Fall through into the general case diagnostic. 3019 // FIXME: We might want to attempt typo correction here. 3020 } 3021 3022 if (!MD || !MD->isVirtual()) { 3023 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3024 Diag(OA->getLocation(), 3025 diag::override_keyword_only_allowed_on_virtual_member_functions) 3026 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3027 D->dropAttr<OverrideAttr>(); 3028 } 3029 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3030 Diag(FA->getLocation(), 3031 diag::override_keyword_only_allowed_on_virtual_member_functions) 3032 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3033 << FixItHint::CreateRemoval(FA->getLocation()); 3034 D->dropAttr<FinalAttr>(); 3035 } 3036 return; 3037 } 3038 3039 // C++11 [class.virtual]p5: 3040 // If a function is marked with the virt-specifier override and 3041 // does not override a member function of a base class, the program is 3042 // ill-formed. 3043 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3044 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3045 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3046 << MD->getDeclName(); 3047 } 3048 3049 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3050 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3051 return; 3052 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3053 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3054 return; 3055 3056 SourceLocation Loc = MD->getLocation(); 3057 SourceLocation SpellingLoc = Loc; 3058 if (getSourceManager().isMacroArgExpansion(Loc)) 3059 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3060 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3061 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3062 return; 3063 3064 if (MD->size_overridden_methods() > 0) { 3065 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3066 unsigned DiagID = 3067 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3068 ? DiagInconsistent 3069 : DiagSuggest; 3070 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3071 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3072 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3073 }; 3074 if (isa<CXXDestructorDecl>(MD)) 3075 EmitDiag( 3076 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3077 diag::warn_suggest_destructor_marked_not_override_overriding); 3078 else 3079 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3080 diag::warn_suggest_function_marked_not_override_overriding); 3081 } 3082 } 3083 3084 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3085 /// function overrides a virtual member function marked 'final', according to 3086 /// C++11 [class.virtual]p4. 3087 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3088 const CXXMethodDecl *Old) { 3089 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3090 if (!FA) 3091 return false; 3092 3093 Diag(New->getLocation(), diag::err_final_function_overridden) 3094 << New->getDeclName() 3095 << FA->isSpelledAsSealed(); 3096 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3097 return true; 3098 } 3099 3100 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3101 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3102 // FIXME: Destruction of ObjC lifetime types has side-effects. 3103 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3104 return !RD->isCompleteDefinition() || 3105 !RD->hasTrivialDefaultConstructor() || 3106 !RD->hasTrivialDestructor(); 3107 return false; 3108 } 3109 3110 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3111 ParsedAttributesView::const_iterator Itr = 3112 llvm::find_if(list, [](const ParsedAttr &AL) { 3113 return AL.isDeclspecPropertyAttribute(); 3114 }); 3115 if (Itr != list.end()) 3116 return &*Itr; 3117 return nullptr; 3118 } 3119 3120 // Check if there is a field shadowing. 3121 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3122 DeclarationName FieldName, 3123 const CXXRecordDecl *RD, 3124 bool DeclIsField) { 3125 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3126 return; 3127 3128 // To record a shadowed field in a base 3129 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3130 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3131 CXXBasePath &Path) { 3132 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3133 // Record an ambiguous path directly 3134 if (Bases.find(Base) != Bases.end()) 3135 return true; 3136 for (const auto Field : Base->lookup(FieldName)) { 3137 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3138 Field->getAccess() != AS_private) { 3139 assert(Field->getAccess() != AS_none); 3140 assert(Bases.find(Base) == Bases.end()); 3141 Bases[Base] = Field; 3142 return true; 3143 } 3144 } 3145 return false; 3146 }; 3147 3148 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3149 /*DetectVirtual=*/true); 3150 if (!RD->lookupInBases(FieldShadowed, Paths)) 3151 return; 3152 3153 for (const auto &P : Paths) { 3154 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3155 auto It = Bases.find(Base); 3156 // Skip duplicated bases 3157 if (It == Bases.end()) 3158 continue; 3159 auto BaseField = It->second; 3160 assert(BaseField->getAccess() != AS_private); 3161 if (AS_none != 3162 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3163 Diag(Loc, diag::warn_shadow_field) 3164 << FieldName << RD << Base << DeclIsField; 3165 Diag(BaseField->getLocation(), diag::note_shadow_field); 3166 Bases.erase(It); 3167 } 3168 } 3169 } 3170 3171 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3172 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3173 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3174 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3175 /// present (but parsing it has been deferred). 3176 NamedDecl * 3177 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3178 MultiTemplateParamsArg TemplateParameterLists, 3179 Expr *BW, const VirtSpecifiers &VS, 3180 InClassInitStyle InitStyle) { 3181 const DeclSpec &DS = D.getDeclSpec(); 3182 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3183 DeclarationName Name = NameInfo.getName(); 3184 SourceLocation Loc = NameInfo.getLoc(); 3185 3186 // For anonymous bitfields, the location should point to the type. 3187 if (Loc.isInvalid()) 3188 Loc = D.getBeginLoc(); 3189 3190 Expr *BitWidth = static_cast<Expr*>(BW); 3191 3192 assert(isa<CXXRecordDecl>(CurContext)); 3193 assert(!DS.isFriendSpecified()); 3194 3195 bool isFunc = D.isDeclarationOfFunction(); 3196 const ParsedAttr *MSPropertyAttr = 3197 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3198 3199 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3200 // The Microsoft extension __interface only permits public member functions 3201 // and prohibits constructors, destructors, operators, non-public member 3202 // functions, static methods and data members. 3203 unsigned InvalidDecl; 3204 bool ShowDeclName = true; 3205 if (!isFunc && 3206 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3207 InvalidDecl = 0; 3208 else if (!isFunc) 3209 InvalidDecl = 1; 3210 else if (AS != AS_public) 3211 InvalidDecl = 2; 3212 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3213 InvalidDecl = 3; 3214 else switch (Name.getNameKind()) { 3215 case DeclarationName::CXXConstructorName: 3216 InvalidDecl = 4; 3217 ShowDeclName = false; 3218 break; 3219 3220 case DeclarationName::CXXDestructorName: 3221 InvalidDecl = 5; 3222 ShowDeclName = false; 3223 break; 3224 3225 case DeclarationName::CXXOperatorName: 3226 case DeclarationName::CXXConversionFunctionName: 3227 InvalidDecl = 6; 3228 break; 3229 3230 default: 3231 InvalidDecl = 0; 3232 break; 3233 } 3234 3235 if (InvalidDecl) { 3236 if (ShowDeclName) 3237 Diag(Loc, diag::err_invalid_member_in_interface) 3238 << (InvalidDecl-1) << Name; 3239 else 3240 Diag(Loc, diag::err_invalid_member_in_interface) 3241 << (InvalidDecl-1) << ""; 3242 return nullptr; 3243 } 3244 } 3245 3246 // C++ 9.2p6: A member shall not be declared to have automatic storage 3247 // duration (auto, register) or with the extern storage-class-specifier. 3248 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3249 // data members and cannot be applied to names declared const or static, 3250 // and cannot be applied to reference members. 3251 switch (DS.getStorageClassSpec()) { 3252 case DeclSpec::SCS_unspecified: 3253 case DeclSpec::SCS_typedef: 3254 case DeclSpec::SCS_static: 3255 break; 3256 case DeclSpec::SCS_mutable: 3257 if (isFunc) { 3258 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3259 3260 // FIXME: It would be nicer if the keyword was ignored only for this 3261 // declarator. Otherwise we could get follow-up errors. 3262 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3263 } 3264 break; 3265 default: 3266 Diag(DS.getStorageClassSpecLoc(), 3267 diag::err_storageclass_invalid_for_member); 3268 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3269 break; 3270 } 3271 3272 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3273 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3274 !isFunc); 3275 3276 if (DS.hasConstexprSpecifier() && isInstField) { 3277 SemaDiagnosticBuilder B = 3278 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3279 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3280 if (InitStyle == ICIS_NoInit) { 3281 B << 0 << 0; 3282 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3283 B << FixItHint::CreateRemoval(ConstexprLoc); 3284 else { 3285 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3286 D.getMutableDeclSpec().ClearConstexprSpec(); 3287 const char *PrevSpec; 3288 unsigned DiagID; 3289 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3290 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3291 (void)Failed; 3292 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3293 } 3294 } else { 3295 B << 1; 3296 const char *PrevSpec; 3297 unsigned DiagID; 3298 if (D.getMutableDeclSpec().SetStorageClassSpec( 3299 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3300 Context.getPrintingPolicy())) { 3301 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3302 "This is the only DeclSpec that should fail to be applied"); 3303 B << 1; 3304 } else { 3305 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3306 isInstField = false; 3307 } 3308 } 3309 } 3310 3311 NamedDecl *Member; 3312 if (isInstField) { 3313 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3314 3315 // Data members must have identifiers for names. 3316 if (!Name.isIdentifier()) { 3317 Diag(Loc, diag::err_bad_variable_name) 3318 << Name; 3319 return nullptr; 3320 } 3321 3322 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3323 3324 // Member field could not be with "template" keyword. 3325 // So TemplateParameterLists should be empty in this case. 3326 if (TemplateParameterLists.size()) { 3327 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3328 if (TemplateParams->size()) { 3329 // There is no such thing as a member field template. 3330 Diag(D.getIdentifierLoc(), diag::err_template_member) 3331 << II 3332 << SourceRange(TemplateParams->getTemplateLoc(), 3333 TemplateParams->getRAngleLoc()); 3334 } else { 3335 // There is an extraneous 'template<>' for this member. 3336 Diag(TemplateParams->getTemplateLoc(), 3337 diag::err_template_member_noparams) 3338 << II 3339 << SourceRange(TemplateParams->getTemplateLoc(), 3340 TemplateParams->getRAngleLoc()); 3341 } 3342 return nullptr; 3343 } 3344 3345 if (SS.isSet() && !SS.isInvalid()) { 3346 // The user provided a superfluous scope specifier inside a class 3347 // definition: 3348 // 3349 // class X { 3350 // int X::member; 3351 // }; 3352 if (DeclContext *DC = computeDeclContext(SS, false)) 3353 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3354 D.getName().getKind() == 3355 UnqualifiedIdKind::IK_TemplateId); 3356 else 3357 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3358 << Name << SS.getRange(); 3359 3360 SS.clear(); 3361 } 3362 3363 if (MSPropertyAttr) { 3364 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3365 BitWidth, InitStyle, AS, *MSPropertyAttr); 3366 if (!Member) 3367 return nullptr; 3368 isInstField = false; 3369 } else { 3370 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3371 BitWidth, InitStyle, AS); 3372 if (!Member) 3373 return nullptr; 3374 } 3375 3376 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3377 } else { 3378 Member = HandleDeclarator(S, D, TemplateParameterLists); 3379 if (!Member) 3380 return nullptr; 3381 3382 // Non-instance-fields can't have a bitfield. 3383 if (BitWidth) { 3384 if (Member->isInvalidDecl()) { 3385 // don't emit another diagnostic. 3386 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3387 // C++ 9.6p3: A bit-field shall not be a static member. 3388 // "static member 'A' cannot be a bit-field" 3389 Diag(Loc, diag::err_static_not_bitfield) 3390 << Name << BitWidth->getSourceRange(); 3391 } else if (isa<TypedefDecl>(Member)) { 3392 // "typedef member 'x' cannot be a bit-field" 3393 Diag(Loc, diag::err_typedef_not_bitfield) 3394 << Name << BitWidth->getSourceRange(); 3395 } else { 3396 // A function typedef ("typedef int f(); f a;"). 3397 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3398 Diag(Loc, diag::err_not_integral_type_bitfield) 3399 << Name << cast<ValueDecl>(Member)->getType() 3400 << BitWidth->getSourceRange(); 3401 } 3402 3403 BitWidth = nullptr; 3404 Member->setInvalidDecl(); 3405 } 3406 3407 NamedDecl *NonTemplateMember = Member; 3408 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3409 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3410 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3411 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3412 3413 Member->setAccess(AS); 3414 3415 // If we have declared a member function template or static data member 3416 // template, set the access of the templated declaration as well. 3417 if (NonTemplateMember != Member) 3418 NonTemplateMember->setAccess(AS); 3419 3420 // C++ [temp.deduct.guide]p3: 3421 // A deduction guide [...] for a member class template [shall be 3422 // declared] with the same access [as the template]. 3423 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3424 auto *TD = DG->getDeducedTemplate(); 3425 // Access specifiers are only meaningful if both the template and the 3426 // deduction guide are from the same scope. 3427 if (AS != TD->getAccess() && 3428 TD->getDeclContext()->getRedeclContext()->Equals( 3429 DG->getDeclContext()->getRedeclContext())) { 3430 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3431 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3432 << TD->getAccess(); 3433 const AccessSpecDecl *LastAccessSpec = nullptr; 3434 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3435 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3436 LastAccessSpec = AccessSpec; 3437 } 3438 assert(LastAccessSpec && "differing access with no access specifier"); 3439 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3440 << AS; 3441 } 3442 } 3443 } 3444 3445 if (VS.isOverrideSpecified()) 3446 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3447 AttributeCommonInfo::AS_Keyword)); 3448 if (VS.isFinalSpecified()) 3449 Member->addAttr(FinalAttr::Create( 3450 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3451 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3452 3453 if (VS.getLastLocation().isValid()) { 3454 // Update the end location of a method that has a virt-specifiers. 3455 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3456 MD->setRangeEnd(VS.getLastLocation()); 3457 } 3458 3459 CheckOverrideControl(Member); 3460 3461 assert((Name || isInstField) && "No identifier for non-field ?"); 3462 3463 if (isInstField) { 3464 FieldDecl *FD = cast<FieldDecl>(Member); 3465 FieldCollector->Add(FD); 3466 3467 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3468 // Remember all explicit private FieldDecls that have a name, no side 3469 // effects and are not part of a dependent type declaration. 3470 if (!FD->isImplicit() && FD->getDeclName() && 3471 FD->getAccess() == AS_private && 3472 !FD->hasAttr<UnusedAttr>() && 3473 !FD->getParent()->isDependentContext() && 3474 !InitializationHasSideEffects(*FD)) 3475 UnusedPrivateFields.insert(FD); 3476 } 3477 } 3478 3479 return Member; 3480 } 3481 3482 namespace { 3483 class UninitializedFieldVisitor 3484 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3485 Sema &S; 3486 // List of Decls to generate a warning on. Also remove Decls that become 3487 // initialized. 3488 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3489 // List of base classes of the record. Classes are removed after their 3490 // initializers. 3491 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3492 // Vector of decls to be removed from the Decl set prior to visiting the 3493 // nodes. These Decls may have been initialized in the prior initializer. 3494 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3495 // If non-null, add a note to the warning pointing back to the constructor. 3496 const CXXConstructorDecl *Constructor; 3497 // Variables to hold state when processing an initializer list. When 3498 // InitList is true, special case initialization of FieldDecls matching 3499 // InitListFieldDecl. 3500 bool InitList; 3501 FieldDecl *InitListFieldDecl; 3502 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3503 3504 public: 3505 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3506 UninitializedFieldVisitor(Sema &S, 3507 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3508 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3509 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3510 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3511 3512 // Returns true if the use of ME is not an uninitialized use. 3513 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3514 bool CheckReferenceOnly) { 3515 llvm::SmallVector<FieldDecl*, 4> Fields; 3516 bool ReferenceField = false; 3517 while (ME) { 3518 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3519 if (!FD) 3520 return false; 3521 Fields.push_back(FD); 3522 if (FD->getType()->isReferenceType()) 3523 ReferenceField = true; 3524 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3525 } 3526 3527 // Binding a reference to an uninitialized field is not an 3528 // uninitialized use. 3529 if (CheckReferenceOnly && !ReferenceField) 3530 return true; 3531 3532 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3533 // Discard the first field since it is the field decl that is being 3534 // initialized. 3535 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3536 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3537 } 3538 3539 for (auto UsedIter = UsedFieldIndex.begin(), 3540 UsedEnd = UsedFieldIndex.end(), 3541 OrigIter = InitFieldIndex.begin(), 3542 OrigEnd = InitFieldIndex.end(); 3543 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3544 if (*UsedIter < *OrigIter) 3545 return true; 3546 if (*UsedIter > *OrigIter) 3547 break; 3548 } 3549 3550 return false; 3551 } 3552 3553 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3554 bool AddressOf) { 3555 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3556 return; 3557 3558 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3559 // or union. 3560 MemberExpr *FieldME = ME; 3561 3562 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3563 3564 Expr *Base = ME; 3565 while (MemberExpr *SubME = 3566 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3567 3568 if (isa<VarDecl>(SubME->getMemberDecl())) 3569 return; 3570 3571 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3572 if (!FD->isAnonymousStructOrUnion()) 3573 FieldME = SubME; 3574 3575 if (!FieldME->getType().isPODType(S.Context)) 3576 AllPODFields = false; 3577 3578 Base = SubME->getBase(); 3579 } 3580 3581 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3582 Visit(Base); 3583 return; 3584 } 3585 3586 if (AddressOf && AllPODFields) 3587 return; 3588 3589 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3590 3591 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3592 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3593 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3594 } 3595 3596 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3597 QualType T = BaseCast->getType(); 3598 if (T->isPointerType() && 3599 BaseClasses.count(T->getPointeeType())) { 3600 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3601 << T->getPointeeType() << FoundVD; 3602 } 3603 } 3604 } 3605 3606 if (!Decls.count(FoundVD)) 3607 return; 3608 3609 const bool IsReference = FoundVD->getType()->isReferenceType(); 3610 3611 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3612 // Special checking for initializer lists. 3613 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3614 return; 3615 } 3616 } else { 3617 // Prevent double warnings on use of unbounded references. 3618 if (CheckReferenceOnly && !IsReference) 3619 return; 3620 } 3621 3622 unsigned diag = IsReference 3623 ? diag::warn_reference_field_is_uninit 3624 : diag::warn_field_is_uninit; 3625 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3626 if (Constructor) 3627 S.Diag(Constructor->getLocation(), 3628 diag::note_uninit_in_this_constructor) 3629 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3630 3631 } 3632 3633 void HandleValue(Expr *E, bool AddressOf) { 3634 E = E->IgnoreParens(); 3635 3636 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3637 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3638 AddressOf /*AddressOf*/); 3639 return; 3640 } 3641 3642 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3643 Visit(CO->getCond()); 3644 HandleValue(CO->getTrueExpr(), AddressOf); 3645 HandleValue(CO->getFalseExpr(), AddressOf); 3646 return; 3647 } 3648 3649 if (BinaryConditionalOperator *BCO = 3650 dyn_cast<BinaryConditionalOperator>(E)) { 3651 Visit(BCO->getCond()); 3652 HandleValue(BCO->getFalseExpr(), AddressOf); 3653 return; 3654 } 3655 3656 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3657 HandleValue(OVE->getSourceExpr(), AddressOf); 3658 return; 3659 } 3660 3661 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3662 switch (BO->getOpcode()) { 3663 default: 3664 break; 3665 case(BO_PtrMemD): 3666 case(BO_PtrMemI): 3667 HandleValue(BO->getLHS(), AddressOf); 3668 Visit(BO->getRHS()); 3669 return; 3670 case(BO_Comma): 3671 Visit(BO->getLHS()); 3672 HandleValue(BO->getRHS(), AddressOf); 3673 return; 3674 } 3675 } 3676 3677 Visit(E); 3678 } 3679 3680 void CheckInitListExpr(InitListExpr *ILE) { 3681 InitFieldIndex.push_back(0); 3682 for (auto Child : ILE->children()) { 3683 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3684 CheckInitListExpr(SubList); 3685 } else { 3686 Visit(Child); 3687 } 3688 ++InitFieldIndex.back(); 3689 } 3690 InitFieldIndex.pop_back(); 3691 } 3692 3693 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3694 FieldDecl *Field, const Type *BaseClass) { 3695 // Remove Decls that may have been initialized in the previous 3696 // initializer. 3697 for (ValueDecl* VD : DeclsToRemove) 3698 Decls.erase(VD); 3699 DeclsToRemove.clear(); 3700 3701 Constructor = FieldConstructor; 3702 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3703 3704 if (ILE && Field) { 3705 InitList = true; 3706 InitListFieldDecl = Field; 3707 InitFieldIndex.clear(); 3708 CheckInitListExpr(ILE); 3709 } else { 3710 InitList = false; 3711 Visit(E); 3712 } 3713 3714 if (Field) 3715 Decls.erase(Field); 3716 if (BaseClass) 3717 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3718 } 3719 3720 void VisitMemberExpr(MemberExpr *ME) { 3721 // All uses of unbounded reference fields will warn. 3722 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3723 } 3724 3725 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3726 if (E->getCastKind() == CK_LValueToRValue) { 3727 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3728 return; 3729 } 3730 3731 Inherited::VisitImplicitCastExpr(E); 3732 } 3733 3734 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3735 if (E->getConstructor()->isCopyConstructor()) { 3736 Expr *ArgExpr = E->getArg(0); 3737 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3738 if (ILE->getNumInits() == 1) 3739 ArgExpr = ILE->getInit(0); 3740 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3741 if (ICE->getCastKind() == CK_NoOp) 3742 ArgExpr = ICE->getSubExpr(); 3743 HandleValue(ArgExpr, false /*AddressOf*/); 3744 return; 3745 } 3746 Inherited::VisitCXXConstructExpr(E); 3747 } 3748 3749 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3750 Expr *Callee = E->getCallee(); 3751 if (isa<MemberExpr>(Callee)) { 3752 HandleValue(Callee, false /*AddressOf*/); 3753 for (auto Arg : E->arguments()) 3754 Visit(Arg); 3755 return; 3756 } 3757 3758 Inherited::VisitCXXMemberCallExpr(E); 3759 } 3760 3761 void VisitCallExpr(CallExpr *E) { 3762 // Treat std::move as a use. 3763 if (E->isCallToStdMove()) { 3764 HandleValue(E->getArg(0), /*AddressOf=*/false); 3765 return; 3766 } 3767 3768 Inherited::VisitCallExpr(E); 3769 } 3770 3771 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3772 Expr *Callee = E->getCallee(); 3773 3774 if (isa<UnresolvedLookupExpr>(Callee)) 3775 return Inherited::VisitCXXOperatorCallExpr(E); 3776 3777 Visit(Callee); 3778 for (auto Arg : E->arguments()) 3779 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3780 } 3781 3782 void VisitBinaryOperator(BinaryOperator *E) { 3783 // If a field assignment is detected, remove the field from the 3784 // uninitiailized field set. 3785 if (E->getOpcode() == BO_Assign) 3786 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3787 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3788 if (!FD->getType()->isReferenceType()) 3789 DeclsToRemove.push_back(FD); 3790 3791 if (E->isCompoundAssignmentOp()) { 3792 HandleValue(E->getLHS(), false /*AddressOf*/); 3793 Visit(E->getRHS()); 3794 return; 3795 } 3796 3797 Inherited::VisitBinaryOperator(E); 3798 } 3799 3800 void VisitUnaryOperator(UnaryOperator *E) { 3801 if (E->isIncrementDecrementOp()) { 3802 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3803 return; 3804 } 3805 if (E->getOpcode() == UO_AddrOf) { 3806 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3807 HandleValue(ME->getBase(), true /*AddressOf*/); 3808 return; 3809 } 3810 } 3811 3812 Inherited::VisitUnaryOperator(E); 3813 } 3814 }; 3815 3816 // Diagnose value-uses of fields to initialize themselves, e.g. 3817 // foo(foo) 3818 // where foo is not also a parameter to the constructor. 3819 // Also diagnose across field uninitialized use such as 3820 // x(y), y(x) 3821 // TODO: implement -Wuninitialized and fold this into that framework. 3822 static void DiagnoseUninitializedFields( 3823 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3824 3825 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3826 Constructor->getLocation())) { 3827 return; 3828 } 3829 3830 if (Constructor->isInvalidDecl()) 3831 return; 3832 3833 const CXXRecordDecl *RD = Constructor->getParent(); 3834 3835 if (RD->isDependentContext()) 3836 return; 3837 3838 // Holds fields that are uninitialized. 3839 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3840 3841 // At the beginning, all fields are uninitialized. 3842 for (auto *I : RD->decls()) { 3843 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3844 UninitializedFields.insert(FD); 3845 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3846 UninitializedFields.insert(IFD->getAnonField()); 3847 } 3848 } 3849 3850 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3851 for (auto I : RD->bases()) 3852 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3853 3854 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3855 return; 3856 3857 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3858 UninitializedFields, 3859 UninitializedBaseClasses); 3860 3861 for (const auto *FieldInit : Constructor->inits()) { 3862 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3863 break; 3864 3865 Expr *InitExpr = FieldInit->getInit(); 3866 if (!InitExpr) 3867 continue; 3868 3869 if (CXXDefaultInitExpr *Default = 3870 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3871 InitExpr = Default->getExpr(); 3872 if (!InitExpr) 3873 continue; 3874 // In class initializers will point to the constructor. 3875 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3876 FieldInit->getAnyMember(), 3877 FieldInit->getBaseClass()); 3878 } else { 3879 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3880 FieldInit->getAnyMember(), 3881 FieldInit->getBaseClass()); 3882 } 3883 } 3884 } 3885 } // namespace 3886 3887 /// Enter a new C++ default initializer scope. After calling this, the 3888 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3889 /// parsing or instantiating the initializer failed. 3890 void Sema::ActOnStartCXXInClassMemberInitializer() { 3891 // Create a synthetic function scope to represent the call to the constructor 3892 // that notionally surrounds a use of this initializer. 3893 PushFunctionScope(); 3894 } 3895 3896 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3897 if (!D.isFunctionDeclarator()) 3898 return; 3899 auto &FTI = D.getFunctionTypeInfo(); 3900 if (!FTI.Params) 3901 return; 3902 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3903 FTI.NumParams)) { 3904 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3905 if (ParamDecl->getDeclName()) 3906 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3907 } 3908 } 3909 3910 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3911 if (ConstraintExpr.isInvalid()) 3912 return ExprError(); 3913 return CorrectDelayedTyposInExpr(ConstraintExpr); 3914 } 3915 3916 /// This is invoked after parsing an in-class initializer for a 3917 /// non-static C++ class member, and after instantiating an in-class initializer 3918 /// in a class template. Such actions are deferred until the class is complete. 3919 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3920 SourceLocation InitLoc, 3921 Expr *InitExpr) { 3922 // Pop the notional constructor scope we created earlier. 3923 PopFunctionScopeInfo(nullptr, D); 3924 3925 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3926 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3927 "must set init style when field is created"); 3928 3929 if (!InitExpr) { 3930 D->setInvalidDecl(); 3931 if (FD) 3932 FD->removeInClassInitializer(); 3933 return; 3934 } 3935 3936 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3937 FD->setInvalidDecl(); 3938 FD->removeInClassInitializer(); 3939 return; 3940 } 3941 3942 ExprResult Init = InitExpr; 3943 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3944 InitializedEntity Entity = 3945 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3946 InitializationKind Kind = 3947 FD->getInClassInitStyle() == ICIS_ListInit 3948 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3949 InitExpr->getBeginLoc(), 3950 InitExpr->getEndLoc()) 3951 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3952 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3953 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3954 if (Init.isInvalid()) { 3955 FD->setInvalidDecl(); 3956 return; 3957 } 3958 } 3959 3960 // C++11 [class.base.init]p7: 3961 // The initialization of each base and member constitutes a 3962 // full-expression. 3963 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3964 if (Init.isInvalid()) { 3965 FD->setInvalidDecl(); 3966 return; 3967 } 3968 3969 InitExpr = Init.get(); 3970 3971 FD->setInClassInitializer(InitExpr); 3972 } 3973 3974 /// Find the direct and/or virtual base specifiers that 3975 /// correspond to the given base type, for use in base initialization 3976 /// within a constructor. 3977 static bool FindBaseInitializer(Sema &SemaRef, 3978 CXXRecordDecl *ClassDecl, 3979 QualType BaseType, 3980 const CXXBaseSpecifier *&DirectBaseSpec, 3981 const CXXBaseSpecifier *&VirtualBaseSpec) { 3982 // First, check for a direct base class. 3983 DirectBaseSpec = nullptr; 3984 for (const auto &Base : ClassDecl->bases()) { 3985 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3986 // We found a direct base of this type. That's what we're 3987 // initializing. 3988 DirectBaseSpec = &Base; 3989 break; 3990 } 3991 } 3992 3993 // Check for a virtual base class. 3994 // FIXME: We might be able to short-circuit this if we know in advance that 3995 // there are no virtual bases. 3996 VirtualBaseSpec = nullptr; 3997 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3998 // We haven't found a base yet; search the class hierarchy for a 3999 // virtual base class. 4000 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4001 /*DetectVirtual=*/false); 4002 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4003 SemaRef.Context.getTypeDeclType(ClassDecl), 4004 BaseType, Paths)) { 4005 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4006 Path != Paths.end(); ++Path) { 4007 if (Path->back().Base->isVirtual()) { 4008 VirtualBaseSpec = Path->back().Base; 4009 break; 4010 } 4011 } 4012 } 4013 } 4014 4015 return DirectBaseSpec || VirtualBaseSpec; 4016 } 4017 4018 /// Handle a C++ member initializer using braced-init-list syntax. 4019 MemInitResult 4020 Sema::ActOnMemInitializer(Decl *ConstructorD, 4021 Scope *S, 4022 CXXScopeSpec &SS, 4023 IdentifierInfo *MemberOrBase, 4024 ParsedType TemplateTypeTy, 4025 const DeclSpec &DS, 4026 SourceLocation IdLoc, 4027 Expr *InitList, 4028 SourceLocation EllipsisLoc) { 4029 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4030 DS, IdLoc, InitList, 4031 EllipsisLoc); 4032 } 4033 4034 /// Handle a C++ member initializer using parentheses syntax. 4035 MemInitResult 4036 Sema::ActOnMemInitializer(Decl *ConstructorD, 4037 Scope *S, 4038 CXXScopeSpec &SS, 4039 IdentifierInfo *MemberOrBase, 4040 ParsedType TemplateTypeTy, 4041 const DeclSpec &DS, 4042 SourceLocation IdLoc, 4043 SourceLocation LParenLoc, 4044 ArrayRef<Expr *> Args, 4045 SourceLocation RParenLoc, 4046 SourceLocation EllipsisLoc) { 4047 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4048 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4049 DS, IdLoc, List, EllipsisLoc); 4050 } 4051 4052 namespace { 4053 4054 // Callback to only accept typo corrections that can be a valid C++ member 4055 // intializer: either a non-static field member or a base class. 4056 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4057 public: 4058 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4059 : ClassDecl(ClassDecl) {} 4060 4061 bool ValidateCandidate(const TypoCorrection &candidate) override { 4062 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4063 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4064 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4065 return isa<TypeDecl>(ND); 4066 } 4067 return false; 4068 } 4069 4070 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4071 return std::make_unique<MemInitializerValidatorCCC>(*this); 4072 } 4073 4074 private: 4075 CXXRecordDecl *ClassDecl; 4076 }; 4077 4078 } 4079 4080 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4081 CXXScopeSpec &SS, 4082 ParsedType TemplateTypeTy, 4083 IdentifierInfo *MemberOrBase) { 4084 if (SS.getScopeRep() || TemplateTypeTy) 4085 return nullptr; 4086 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4087 if (Result.empty()) 4088 return nullptr; 4089 ValueDecl *Member; 4090 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4091 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4092 return Member; 4093 return nullptr; 4094 } 4095 4096 /// Handle a C++ member initializer. 4097 MemInitResult 4098 Sema::BuildMemInitializer(Decl *ConstructorD, 4099 Scope *S, 4100 CXXScopeSpec &SS, 4101 IdentifierInfo *MemberOrBase, 4102 ParsedType TemplateTypeTy, 4103 const DeclSpec &DS, 4104 SourceLocation IdLoc, 4105 Expr *Init, 4106 SourceLocation EllipsisLoc) { 4107 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4108 if (!Res.isUsable()) 4109 return true; 4110 Init = Res.get(); 4111 4112 if (!ConstructorD) 4113 return true; 4114 4115 AdjustDeclIfTemplate(ConstructorD); 4116 4117 CXXConstructorDecl *Constructor 4118 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4119 if (!Constructor) { 4120 // The user wrote a constructor initializer on a function that is 4121 // not a C++ constructor. Ignore the error for now, because we may 4122 // have more member initializers coming; we'll diagnose it just 4123 // once in ActOnMemInitializers. 4124 return true; 4125 } 4126 4127 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4128 4129 // C++ [class.base.init]p2: 4130 // Names in a mem-initializer-id are looked up in the scope of the 4131 // constructor's class and, if not found in that scope, are looked 4132 // up in the scope containing the constructor's definition. 4133 // [Note: if the constructor's class contains a member with the 4134 // same name as a direct or virtual base class of the class, a 4135 // mem-initializer-id naming the member or base class and composed 4136 // of a single identifier refers to the class member. A 4137 // mem-initializer-id for the hidden base class may be specified 4138 // using a qualified name. ] 4139 4140 // Look for a member, first. 4141 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4142 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4143 if (EllipsisLoc.isValid()) 4144 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4145 << MemberOrBase 4146 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4147 4148 return BuildMemberInitializer(Member, Init, IdLoc); 4149 } 4150 // It didn't name a member, so see if it names a class. 4151 QualType BaseType; 4152 TypeSourceInfo *TInfo = nullptr; 4153 4154 if (TemplateTypeTy) { 4155 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4156 if (BaseType.isNull()) 4157 return true; 4158 } else if (DS.getTypeSpecType() == TST_decltype) { 4159 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4160 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4161 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4162 return true; 4163 } else { 4164 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4165 LookupParsedName(R, S, &SS); 4166 4167 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4168 if (!TyD) { 4169 if (R.isAmbiguous()) return true; 4170 4171 // We don't want access-control diagnostics here. 4172 R.suppressDiagnostics(); 4173 4174 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4175 bool NotUnknownSpecialization = false; 4176 DeclContext *DC = computeDeclContext(SS, false); 4177 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4178 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4179 4180 if (!NotUnknownSpecialization) { 4181 // When the scope specifier can refer to a member of an unknown 4182 // specialization, we take it as a type name. 4183 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4184 SS.getWithLocInContext(Context), 4185 *MemberOrBase, IdLoc); 4186 if (BaseType.isNull()) 4187 return true; 4188 4189 TInfo = Context.CreateTypeSourceInfo(BaseType); 4190 DependentNameTypeLoc TL = 4191 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4192 if (!TL.isNull()) { 4193 TL.setNameLoc(IdLoc); 4194 TL.setElaboratedKeywordLoc(SourceLocation()); 4195 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4196 } 4197 4198 R.clear(); 4199 R.setLookupName(MemberOrBase); 4200 } 4201 } 4202 4203 // If no results were found, try to correct typos. 4204 TypoCorrection Corr; 4205 MemInitializerValidatorCCC CCC(ClassDecl); 4206 if (R.empty() && BaseType.isNull() && 4207 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4208 CCC, CTK_ErrorRecovery, ClassDecl))) { 4209 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4210 // We have found a non-static data member with a similar 4211 // name to what was typed; complain and initialize that 4212 // member. 4213 diagnoseTypo(Corr, 4214 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4215 << MemberOrBase << true); 4216 return BuildMemberInitializer(Member, Init, IdLoc); 4217 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4218 const CXXBaseSpecifier *DirectBaseSpec; 4219 const CXXBaseSpecifier *VirtualBaseSpec; 4220 if (FindBaseInitializer(*this, ClassDecl, 4221 Context.getTypeDeclType(Type), 4222 DirectBaseSpec, VirtualBaseSpec)) { 4223 // We have found a direct or virtual base class with a 4224 // similar name to what was typed; complain and initialize 4225 // that base class. 4226 diagnoseTypo(Corr, 4227 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4228 << MemberOrBase << false, 4229 PDiag() /*Suppress note, we provide our own.*/); 4230 4231 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4232 : VirtualBaseSpec; 4233 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4234 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4235 4236 TyD = Type; 4237 } 4238 } 4239 } 4240 4241 if (!TyD && BaseType.isNull()) { 4242 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4243 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4244 return true; 4245 } 4246 } 4247 4248 if (BaseType.isNull()) { 4249 BaseType = Context.getTypeDeclType(TyD); 4250 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4251 if (SS.isSet()) { 4252 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4253 BaseType); 4254 TInfo = Context.CreateTypeSourceInfo(BaseType); 4255 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4256 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4257 TL.setElaboratedKeywordLoc(SourceLocation()); 4258 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4259 } 4260 } 4261 } 4262 4263 if (!TInfo) 4264 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4265 4266 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4267 } 4268 4269 MemInitResult 4270 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4271 SourceLocation IdLoc) { 4272 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4273 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4274 assert((DirectMember || IndirectMember) && 4275 "Member must be a FieldDecl or IndirectFieldDecl"); 4276 4277 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4278 return true; 4279 4280 if (Member->isInvalidDecl()) 4281 return true; 4282 4283 MultiExprArg Args; 4284 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4285 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4286 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4287 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4288 } else { 4289 // Template instantiation doesn't reconstruct ParenListExprs for us. 4290 Args = Init; 4291 } 4292 4293 SourceRange InitRange = Init->getSourceRange(); 4294 4295 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4296 // Can't check initialization for a member of dependent type or when 4297 // any of the arguments are type-dependent expressions. 4298 DiscardCleanupsInEvaluationContext(); 4299 } else { 4300 bool InitList = false; 4301 if (isa<InitListExpr>(Init)) { 4302 InitList = true; 4303 Args = Init; 4304 } 4305 4306 // Initialize the member. 4307 InitializedEntity MemberEntity = 4308 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4309 : InitializedEntity::InitializeMember(IndirectMember, 4310 nullptr); 4311 InitializationKind Kind = 4312 InitList ? InitializationKind::CreateDirectList( 4313 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4314 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4315 InitRange.getEnd()); 4316 4317 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4318 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4319 nullptr); 4320 if (MemberInit.isInvalid()) 4321 return true; 4322 4323 // C++11 [class.base.init]p7: 4324 // The initialization of each base and member constitutes a 4325 // full-expression. 4326 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4327 /*DiscardedValue*/ false); 4328 if (MemberInit.isInvalid()) 4329 return true; 4330 4331 Init = MemberInit.get(); 4332 } 4333 4334 if (DirectMember) { 4335 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4336 InitRange.getBegin(), Init, 4337 InitRange.getEnd()); 4338 } else { 4339 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4340 InitRange.getBegin(), Init, 4341 InitRange.getEnd()); 4342 } 4343 } 4344 4345 MemInitResult 4346 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4347 CXXRecordDecl *ClassDecl) { 4348 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4349 if (!LangOpts.CPlusPlus11) 4350 return Diag(NameLoc, diag::err_delegating_ctor) 4351 << TInfo->getTypeLoc().getLocalSourceRange(); 4352 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4353 4354 bool InitList = true; 4355 MultiExprArg Args = Init; 4356 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4357 InitList = false; 4358 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4359 } 4360 4361 SourceRange InitRange = Init->getSourceRange(); 4362 // Initialize the object. 4363 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4364 QualType(ClassDecl->getTypeForDecl(), 0)); 4365 InitializationKind Kind = 4366 InitList ? InitializationKind::CreateDirectList( 4367 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4368 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4369 InitRange.getEnd()); 4370 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4371 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4372 Args, nullptr); 4373 if (DelegationInit.isInvalid()) 4374 return true; 4375 4376 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4377 "Delegating constructor with no target?"); 4378 4379 // C++11 [class.base.init]p7: 4380 // The initialization of each base and member constitutes a 4381 // full-expression. 4382 DelegationInit = ActOnFinishFullExpr( 4383 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4384 if (DelegationInit.isInvalid()) 4385 return true; 4386 4387 // If we are in a dependent context, template instantiation will 4388 // perform this type-checking again. Just save the arguments that we 4389 // received in a ParenListExpr. 4390 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4391 // of the information that we have about the base 4392 // initializer. However, deconstructing the ASTs is a dicey process, 4393 // and this approach is far more likely to get the corner cases right. 4394 if (CurContext->isDependentContext()) 4395 DelegationInit = Init; 4396 4397 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4398 DelegationInit.getAs<Expr>(), 4399 InitRange.getEnd()); 4400 } 4401 4402 MemInitResult 4403 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4404 Expr *Init, CXXRecordDecl *ClassDecl, 4405 SourceLocation EllipsisLoc) { 4406 SourceLocation BaseLoc 4407 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4408 4409 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4410 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4411 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4412 4413 // C++ [class.base.init]p2: 4414 // [...] Unless the mem-initializer-id names a nonstatic data 4415 // member of the constructor's class or a direct or virtual base 4416 // of that class, the mem-initializer is ill-formed. A 4417 // mem-initializer-list can initialize a base class using any 4418 // name that denotes that base class type. 4419 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4420 4421 SourceRange InitRange = Init->getSourceRange(); 4422 if (EllipsisLoc.isValid()) { 4423 // This is a pack expansion. 4424 if (!BaseType->containsUnexpandedParameterPack()) { 4425 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4426 << SourceRange(BaseLoc, InitRange.getEnd()); 4427 4428 EllipsisLoc = SourceLocation(); 4429 } 4430 } else { 4431 // Check for any unexpanded parameter packs. 4432 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4433 return true; 4434 4435 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4436 return true; 4437 } 4438 4439 // Check for direct and virtual base classes. 4440 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4441 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4442 if (!Dependent) { 4443 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4444 BaseType)) 4445 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4446 4447 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4448 VirtualBaseSpec); 4449 4450 // C++ [base.class.init]p2: 4451 // Unless the mem-initializer-id names a nonstatic data member of the 4452 // constructor's class or a direct or virtual base of that class, the 4453 // mem-initializer is ill-formed. 4454 if (!DirectBaseSpec && !VirtualBaseSpec) { 4455 // If the class has any dependent bases, then it's possible that 4456 // one of those types will resolve to the same type as 4457 // BaseType. Therefore, just treat this as a dependent base 4458 // class initialization. FIXME: Should we try to check the 4459 // initialization anyway? It seems odd. 4460 if (ClassDecl->hasAnyDependentBases()) 4461 Dependent = true; 4462 else 4463 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4464 << BaseType << Context.getTypeDeclType(ClassDecl) 4465 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4466 } 4467 } 4468 4469 if (Dependent) { 4470 DiscardCleanupsInEvaluationContext(); 4471 4472 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4473 /*IsVirtual=*/false, 4474 InitRange.getBegin(), Init, 4475 InitRange.getEnd(), EllipsisLoc); 4476 } 4477 4478 // C++ [base.class.init]p2: 4479 // If a mem-initializer-id is ambiguous because it designates both 4480 // a direct non-virtual base class and an inherited virtual base 4481 // class, the mem-initializer is ill-formed. 4482 if (DirectBaseSpec && VirtualBaseSpec) 4483 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4484 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4485 4486 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4487 if (!BaseSpec) 4488 BaseSpec = VirtualBaseSpec; 4489 4490 // Initialize the base. 4491 bool InitList = true; 4492 MultiExprArg Args = Init; 4493 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4494 InitList = false; 4495 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4496 } 4497 4498 InitializedEntity BaseEntity = 4499 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4500 InitializationKind Kind = 4501 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4502 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4503 InitRange.getEnd()); 4504 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4505 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4506 if (BaseInit.isInvalid()) 4507 return true; 4508 4509 // C++11 [class.base.init]p7: 4510 // The initialization of each base and member constitutes a 4511 // full-expression. 4512 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4513 /*DiscardedValue*/ false); 4514 if (BaseInit.isInvalid()) 4515 return true; 4516 4517 // If we are in a dependent context, template instantiation will 4518 // perform this type-checking again. Just save the arguments that we 4519 // received in a ParenListExpr. 4520 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4521 // of the information that we have about the base 4522 // initializer. However, deconstructing the ASTs is a dicey process, 4523 // and this approach is far more likely to get the corner cases right. 4524 if (CurContext->isDependentContext()) 4525 BaseInit = Init; 4526 4527 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4528 BaseSpec->isVirtual(), 4529 InitRange.getBegin(), 4530 BaseInit.getAs<Expr>(), 4531 InitRange.getEnd(), EllipsisLoc); 4532 } 4533 4534 // Create a static_cast\<T&&>(expr). 4535 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4536 if (T.isNull()) T = E->getType(); 4537 QualType TargetType = SemaRef.BuildReferenceType( 4538 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4539 SourceLocation ExprLoc = E->getBeginLoc(); 4540 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4541 TargetType, ExprLoc); 4542 4543 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4544 SourceRange(ExprLoc, ExprLoc), 4545 E->getSourceRange()).get(); 4546 } 4547 4548 /// ImplicitInitializerKind - How an implicit base or member initializer should 4549 /// initialize its base or member. 4550 enum ImplicitInitializerKind { 4551 IIK_Default, 4552 IIK_Copy, 4553 IIK_Move, 4554 IIK_Inherit 4555 }; 4556 4557 static bool 4558 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4559 ImplicitInitializerKind ImplicitInitKind, 4560 CXXBaseSpecifier *BaseSpec, 4561 bool IsInheritedVirtualBase, 4562 CXXCtorInitializer *&CXXBaseInit) { 4563 InitializedEntity InitEntity 4564 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4565 IsInheritedVirtualBase); 4566 4567 ExprResult BaseInit; 4568 4569 switch (ImplicitInitKind) { 4570 case IIK_Inherit: 4571 case IIK_Default: { 4572 InitializationKind InitKind 4573 = InitializationKind::CreateDefault(Constructor->getLocation()); 4574 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4575 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4576 break; 4577 } 4578 4579 case IIK_Move: 4580 case IIK_Copy: { 4581 bool Moving = ImplicitInitKind == IIK_Move; 4582 ParmVarDecl *Param = Constructor->getParamDecl(0); 4583 QualType ParamType = Param->getType().getNonReferenceType(); 4584 4585 Expr *CopyCtorArg = 4586 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4587 SourceLocation(), Param, false, 4588 Constructor->getLocation(), ParamType, 4589 VK_LValue, nullptr); 4590 4591 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4592 4593 // Cast to the base class to avoid ambiguities. 4594 QualType ArgTy = 4595 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4596 ParamType.getQualifiers()); 4597 4598 if (Moving) { 4599 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4600 } 4601 4602 CXXCastPath BasePath; 4603 BasePath.push_back(BaseSpec); 4604 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4605 CK_UncheckedDerivedToBase, 4606 Moving ? VK_XValue : VK_LValue, 4607 &BasePath).get(); 4608 4609 InitializationKind InitKind 4610 = InitializationKind::CreateDirect(Constructor->getLocation(), 4611 SourceLocation(), SourceLocation()); 4612 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4613 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4614 break; 4615 } 4616 } 4617 4618 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4619 if (BaseInit.isInvalid()) 4620 return true; 4621 4622 CXXBaseInit = 4623 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4624 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4625 SourceLocation()), 4626 BaseSpec->isVirtual(), 4627 SourceLocation(), 4628 BaseInit.getAs<Expr>(), 4629 SourceLocation(), 4630 SourceLocation()); 4631 4632 return false; 4633 } 4634 4635 static bool RefersToRValueRef(Expr *MemRef) { 4636 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4637 return Referenced->getType()->isRValueReferenceType(); 4638 } 4639 4640 static bool 4641 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4642 ImplicitInitializerKind ImplicitInitKind, 4643 FieldDecl *Field, IndirectFieldDecl *Indirect, 4644 CXXCtorInitializer *&CXXMemberInit) { 4645 if (Field->isInvalidDecl()) 4646 return true; 4647 4648 SourceLocation Loc = Constructor->getLocation(); 4649 4650 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4651 bool Moving = ImplicitInitKind == IIK_Move; 4652 ParmVarDecl *Param = Constructor->getParamDecl(0); 4653 QualType ParamType = Param->getType().getNonReferenceType(); 4654 4655 // Suppress copying zero-width bitfields. 4656 if (Field->isZeroLengthBitField(SemaRef.Context)) 4657 return false; 4658 4659 Expr *MemberExprBase = 4660 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4661 SourceLocation(), Param, false, 4662 Loc, ParamType, VK_LValue, nullptr); 4663 4664 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4665 4666 if (Moving) { 4667 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4668 } 4669 4670 // Build a reference to this field within the parameter. 4671 CXXScopeSpec SS; 4672 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4673 Sema::LookupMemberName); 4674 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4675 : cast<ValueDecl>(Field), AS_public); 4676 MemberLookup.resolveKind(); 4677 ExprResult CtorArg 4678 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4679 ParamType, Loc, 4680 /*IsArrow=*/false, 4681 SS, 4682 /*TemplateKWLoc=*/SourceLocation(), 4683 /*FirstQualifierInScope=*/nullptr, 4684 MemberLookup, 4685 /*TemplateArgs=*/nullptr, 4686 /*S*/nullptr); 4687 if (CtorArg.isInvalid()) 4688 return true; 4689 4690 // C++11 [class.copy]p15: 4691 // - if a member m has rvalue reference type T&&, it is direct-initialized 4692 // with static_cast<T&&>(x.m); 4693 if (RefersToRValueRef(CtorArg.get())) { 4694 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4695 } 4696 4697 InitializedEntity Entity = 4698 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4699 /*Implicit*/ true) 4700 : InitializedEntity::InitializeMember(Field, nullptr, 4701 /*Implicit*/ true); 4702 4703 // Direct-initialize to use the copy constructor. 4704 InitializationKind InitKind = 4705 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4706 4707 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4708 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4709 ExprResult MemberInit = 4710 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4711 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4712 if (MemberInit.isInvalid()) 4713 return true; 4714 4715 if (Indirect) 4716 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4717 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4718 else 4719 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4720 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4721 return false; 4722 } 4723 4724 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4725 "Unhandled implicit init kind!"); 4726 4727 QualType FieldBaseElementType = 4728 SemaRef.Context.getBaseElementType(Field->getType()); 4729 4730 if (FieldBaseElementType->isRecordType()) { 4731 InitializedEntity InitEntity = 4732 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4733 /*Implicit*/ true) 4734 : InitializedEntity::InitializeMember(Field, nullptr, 4735 /*Implicit*/ true); 4736 InitializationKind InitKind = 4737 InitializationKind::CreateDefault(Loc); 4738 4739 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4740 ExprResult MemberInit = 4741 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4742 4743 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4744 if (MemberInit.isInvalid()) 4745 return true; 4746 4747 if (Indirect) 4748 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4749 Indirect, Loc, 4750 Loc, 4751 MemberInit.get(), 4752 Loc); 4753 else 4754 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4755 Field, Loc, Loc, 4756 MemberInit.get(), 4757 Loc); 4758 return false; 4759 } 4760 4761 if (!Field->getParent()->isUnion()) { 4762 if (FieldBaseElementType->isReferenceType()) { 4763 SemaRef.Diag(Constructor->getLocation(), 4764 diag::err_uninitialized_member_in_ctor) 4765 << (int)Constructor->isImplicit() 4766 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4767 << 0 << Field->getDeclName(); 4768 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4769 return true; 4770 } 4771 4772 if (FieldBaseElementType.isConstQualified()) { 4773 SemaRef.Diag(Constructor->getLocation(), 4774 diag::err_uninitialized_member_in_ctor) 4775 << (int)Constructor->isImplicit() 4776 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4777 << 1 << Field->getDeclName(); 4778 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4779 return true; 4780 } 4781 } 4782 4783 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4784 // ARC and Weak: 4785 // Default-initialize Objective-C pointers to NULL. 4786 CXXMemberInit 4787 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4788 Loc, Loc, 4789 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4790 Loc); 4791 return false; 4792 } 4793 4794 // Nothing to initialize. 4795 CXXMemberInit = nullptr; 4796 return false; 4797 } 4798 4799 namespace { 4800 struct BaseAndFieldInfo { 4801 Sema &S; 4802 CXXConstructorDecl *Ctor; 4803 bool AnyErrorsInInits; 4804 ImplicitInitializerKind IIK; 4805 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4806 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4807 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4808 4809 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4810 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4811 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4812 if (Ctor->getInheritedConstructor()) 4813 IIK = IIK_Inherit; 4814 else if (Generated && Ctor->isCopyConstructor()) 4815 IIK = IIK_Copy; 4816 else if (Generated && Ctor->isMoveConstructor()) 4817 IIK = IIK_Move; 4818 else 4819 IIK = IIK_Default; 4820 } 4821 4822 bool isImplicitCopyOrMove() const { 4823 switch (IIK) { 4824 case IIK_Copy: 4825 case IIK_Move: 4826 return true; 4827 4828 case IIK_Default: 4829 case IIK_Inherit: 4830 return false; 4831 } 4832 4833 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4834 } 4835 4836 bool addFieldInitializer(CXXCtorInitializer *Init) { 4837 AllToInit.push_back(Init); 4838 4839 // Check whether this initializer makes the field "used". 4840 if (Init->getInit()->HasSideEffects(S.Context)) 4841 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4842 4843 return false; 4844 } 4845 4846 bool isInactiveUnionMember(FieldDecl *Field) { 4847 RecordDecl *Record = Field->getParent(); 4848 if (!Record->isUnion()) 4849 return false; 4850 4851 if (FieldDecl *Active = 4852 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4853 return Active != Field->getCanonicalDecl(); 4854 4855 // In an implicit copy or move constructor, ignore any in-class initializer. 4856 if (isImplicitCopyOrMove()) 4857 return true; 4858 4859 // If there's no explicit initialization, the field is active only if it 4860 // has an in-class initializer... 4861 if (Field->hasInClassInitializer()) 4862 return false; 4863 // ... or it's an anonymous struct or union whose class has an in-class 4864 // initializer. 4865 if (!Field->isAnonymousStructOrUnion()) 4866 return true; 4867 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4868 return !FieldRD->hasInClassInitializer(); 4869 } 4870 4871 /// Determine whether the given field is, or is within, a union member 4872 /// that is inactive (because there was an initializer given for a different 4873 /// member of the union, or because the union was not initialized at all). 4874 bool isWithinInactiveUnionMember(FieldDecl *Field, 4875 IndirectFieldDecl *Indirect) { 4876 if (!Indirect) 4877 return isInactiveUnionMember(Field); 4878 4879 for (auto *C : Indirect->chain()) { 4880 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4881 if (Field && isInactiveUnionMember(Field)) 4882 return true; 4883 } 4884 return false; 4885 } 4886 }; 4887 } 4888 4889 /// Determine whether the given type is an incomplete or zero-lenfgth 4890 /// array type. 4891 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4892 if (T->isIncompleteArrayType()) 4893 return true; 4894 4895 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4896 if (!ArrayT->getSize()) 4897 return true; 4898 4899 T = ArrayT->getElementType(); 4900 } 4901 4902 return false; 4903 } 4904 4905 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4906 FieldDecl *Field, 4907 IndirectFieldDecl *Indirect = nullptr) { 4908 if (Field->isInvalidDecl()) 4909 return false; 4910 4911 // Overwhelmingly common case: we have a direct initializer for this field. 4912 if (CXXCtorInitializer *Init = 4913 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4914 return Info.addFieldInitializer(Init); 4915 4916 // C++11 [class.base.init]p8: 4917 // if the entity is a non-static data member that has a 4918 // brace-or-equal-initializer and either 4919 // -- the constructor's class is a union and no other variant member of that 4920 // union is designated by a mem-initializer-id or 4921 // -- the constructor's class is not a union, and, if the entity is a member 4922 // of an anonymous union, no other member of that union is designated by 4923 // a mem-initializer-id, 4924 // the entity is initialized as specified in [dcl.init]. 4925 // 4926 // We also apply the same rules to handle anonymous structs within anonymous 4927 // unions. 4928 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4929 return false; 4930 4931 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4932 ExprResult DIE = 4933 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4934 if (DIE.isInvalid()) 4935 return true; 4936 4937 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4938 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4939 4940 CXXCtorInitializer *Init; 4941 if (Indirect) 4942 Init = new (SemaRef.Context) 4943 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4944 SourceLocation(), DIE.get(), SourceLocation()); 4945 else 4946 Init = new (SemaRef.Context) 4947 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4948 SourceLocation(), DIE.get(), SourceLocation()); 4949 return Info.addFieldInitializer(Init); 4950 } 4951 4952 // Don't initialize incomplete or zero-length arrays. 4953 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4954 return false; 4955 4956 // Don't try to build an implicit initializer if there were semantic 4957 // errors in any of the initializers (and therefore we might be 4958 // missing some that the user actually wrote). 4959 if (Info.AnyErrorsInInits) 4960 return false; 4961 4962 CXXCtorInitializer *Init = nullptr; 4963 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4964 Indirect, Init)) 4965 return true; 4966 4967 if (!Init) 4968 return false; 4969 4970 return Info.addFieldInitializer(Init); 4971 } 4972 4973 bool 4974 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4975 CXXCtorInitializer *Initializer) { 4976 assert(Initializer->isDelegatingInitializer()); 4977 Constructor->setNumCtorInitializers(1); 4978 CXXCtorInitializer **initializer = 4979 new (Context) CXXCtorInitializer*[1]; 4980 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4981 Constructor->setCtorInitializers(initializer); 4982 4983 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4984 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4985 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4986 } 4987 4988 DelegatingCtorDecls.push_back(Constructor); 4989 4990 DiagnoseUninitializedFields(*this, Constructor); 4991 4992 return false; 4993 } 4994 4995 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4996 ArrayRef<CXXCtorInitializer *> Initializers) { 4997 if (Constructor->isDependentContext()) { 4998 // Just store the initializers as written, they will be checked during 4999 // instantiation. 5000 if (!Initializers.empty()) { 5001 Constructor->setNumCtorInitializers(Initializers.size()); 5002 CXXCtorInitializer **baseOrMemberInitializers = 5003 new (Context) CXXCtorInitializer*[Initializers.size()]; 5004 memcpy(baseOrMemberInitializers, Initializers.data(), 5005 Initializers.size() * sizeof(CXXCtorInitializer*)); 5006 Constructor->setCtorInitializers(baseOrMemberInitializers); 5007 } 5008 5009 // Let template instantiation know whether we had errors. 5010 if (AnyErrors) 5011 Constructor->setInvalidDecl(); 5012 5013 return false; 5014 } 5015 5016 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5017 5018 // We need to build the initializer AST according to order of construction 5019 // and not what user specified in the Initializers list. 5020 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5021 if (!ClassDecl) 5022 return true; 5023 5024 bool HadError = false; 5025 5026 for (unsigned i = 0; i < Initializers.size(); i++) { 5027 CXXCtorInitializer *Member = Initializers[i]; 5028 5029 if (Member->isBaseInitializer()) 5030 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5031 else { 5032 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5033 5034 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5035 for (auto *C : F->chain()) { 5036 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5037 if (FD && FD->getParent()->isUnion()) 5038 Info.ActiveUnionMember.insert(std::make_pair( 5039 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5040 } 5041 } else if (FieldDecl *FD = Member->getMember()) { 5042 if (FD->getParent()->isUnion()) 5043 Info.ActiveUnionMember.insert(std::make_pair( 5044 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5045 } 5046 } 5047 } 5048 5049 // Keep track of the direct virtual bases. 5050 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5051 for (auto &I : ClassDecl->bases()) { 5052 if (I.isVirtual()) 5053 DirectVBases.insert(&I); 5054 } 5055 5056 // Push virtual bases before others. 5057 for (auto &VBase : ClassDecl->vbases()) { 5058 if (CXXCtorInitializer *Value 5059 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5060 // [class.base.init]p7, per DR257: 5061 // A mem-initializer where the mem-initializer-id names a virtual base 5062 // class is ignored during execution of a constructor of any class that 5063 // is not the most derived class. 5064 if (ClassDecl->isAbstract()) { 5065 // FIXME: Provide a fixit to remove the base specifier. This requires 5066 // tracking the location of the associated comma for a base specifier. 5067 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5068 << VBase.getType() << ClassDecl; 5069 DiagnoseAbstractType(ClassDecl); 5070 } 5071 5072 Info.AllToInit.push_back(Value); 5073 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5074 // [class.base.init]p8, per DR257: 5075 // If a given [...] base class is not named by a mem-initializer-id 5076 // [...] and the entity is not a virtual base class of an abstract 5077 // class, then [...] the entity is default-initialized. 5078 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5079 CXXCtorInitializer *CXXBaseInit; 5080 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5081 &VBase, IsInheritedVirtualBase, 5082 CXXBaseInit)) { 5083 HadError = true; 5084 continue; 5085 } 5086 5087 Info.AllToInit.push_back(CXXBaseInit); 5088 } 5089 } 5090 5091 // Non-virtual bases. 5092 for (auto &Base : ClassDecl->bases()) { 5093 // Virtuals are in the virtual base list and already constructed. 5094 if (Base.isVirtual()) 5095 continue; 5096 5097 if (CXXCtorInitializer *Value 5098 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5099 Info.AllToInit.push_back(Value); 5100 } else if (!AnyErrors) { 5101 CXXCtorInitializer *CXXBaseInit; 5102 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5103 &Base, /*IsInheritedVirtualBase=*/false, 5104 CXXBaseInit)) { 5105 HadError = true; 5106 continue; 5107 } 5108 5109 Info.AllToInit.push_back(CXXBaseInit); 5110 } 5111 } 5112 5113 // Fields. 5114 for (auto *Mem : ClassDecl->decls()) { 5115 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5116 // C++ [class.bit]p2: 5117 // A declaration for a bit-field that omits the identifier declares an 5118 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5119 // initialized. 5120 if (F->isUnnamedBitfield()) 5121 continue; 5122 5123 // If we're not generating the implicit copy/move constructor, then we'll 5124 // handle anonymous struct/union fields based on their individual 5125 // indirect fields. 5126 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5127 continue; 5128 5129 if (CollectFieldInitializer(*this, Info, F)) 5130 HadError = true; 5131 continue; 5132 } 5133 5134 // Beyond this point, we only consider default initialization. 5135 if (Info.isImplicitCopyOrMove()) 5136 continue; 5137 5138 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5139 if (F->getType()->isIncompleteArrayType()) { 5140 assert(ClassDecl->hasFlexibleArrayMember() && 5141 "Incomplete array type is not valid"); 5142 continue; 5143 } 5144 5145 // Initialize each field of an anonymous struct individually. 5146 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5147 HadError = true; 5148 5149 continue; 5150 } 5151 } 5152 5153 unsigned NumInitializers = Info.AllToInit.size(); 5154 if (NumInitializers > 0) { 5155 Constructor->setNumCtorInitializers(NumInitializers); 5156 CXXCtorInitializer **baseOrMemberInitializers = 5157 new (Context) CXXCtorInitializer*[NumInitializers]; 5158 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5159 NumInitializers * sizeof(CXXCtorInitializer*)); 5160 Constructor->setCtorInitializers(baseOrMemberInitializers); 5161 5162 // Constructors implicitly reference the base and member 5163 // destructors. 5164 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5165 Constructor->getParent()); 5166 } 5167 5168 return HadError; 5169 } 5170 5171 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5172 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5173 const RecordDecl *RD = RT->getDecl(); 5174 if (RD->isAnonymousStructOrUnion()) { 5175 for (auto *Field : RD->fields()) 5176 PopulateKeysForFields(Field, IdealInits); 5177 return; 5178 } 5179 } 5180 IdealInits.push_back(Field->getCanonicalDecl()); 5181 } 5182 5183 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5184 return Context.getCanonicalType(BaseType).getTypePtr(); 5185 } 5186 5187 static const void *GetKeyForMember(ASTContext &Context, 5188 CXXCtorInitializer *Member) { 5189 if (!Member->isAnyMemberInitializer()) 5190 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5191 5192 return Member->getAnyMember()->getCanonicalDecl(); 5193 } 5194 5195 static void DiagnoseBaseOrMemInitializerOrder( 5196 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5197 ArrayRef<CXXCtorInitializer *> Inits) { 5198 if (Constructor->getDeclContext()->isDependentContext()) 5199 return; 5200 5201 // Don't check initializers order unless the warning is enabled at the 5202 // location of at least one initializer. 5203 bool ShouldCheckOrder = false; 5204 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5205 CXXCtorInitializer *Init = Inits[InitIndex]; 5206 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5207 Init->getSourceLocation())) { 5208 ShouldCheckOrder = true; 5209 break; 5210 } 5211 } 5212 if (!ShouldCheckOrder) 5213 return; 5214 5215 // Build the list of bases and members in the order that they'll 5216 // actually be initialized. The explicit initializers should be in 5217 // this same order but may be missing things. 5218 SmallVector<const void*, 32> IdealInitKeys; 5219 5220 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5221 5222 // 1. Virtual bases. 5223 for (const auto &VBase : ClassDecl->vbases()) 5224 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5225 5226 // 2. Non-virtual bases. 5227 for (const auto &Base : ClassDecl->bases()) { 5228 if (Base.isVirtual()) 5229 continue; 5230 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5231 } 5232 5233 // 3. Direct fields. 5234 for (auto *Field : ClassDecl->fields()) { 5235 if (Field->isUnnamedBitfield()) 5236 continue; 5237 5238 PopulateKeysForFields(Field, IdealInitKeys); 5239 } 5240 5241 unsigned NumIdealInits = IdealInitKeys.size(); 5242 unsigned IdealIndex = 0; 5243 5244 CXXCtorInitializer *PrevInit = nullptr; 5245 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5246 CXXCtorInitializer *Init = Inits[InitIndex]; 5247 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5248 5249 // Scan forward to try to find this initializer in the idealized 5250 // initializers list. 5251 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5252 if (InitKey == IdealInitKeys[IdealIndex]) 5253 break; 5254 5255 // If we didn't find this initializer, it must be because we 5256 // scanned past it on a previous iteration. That can only 5257 // happen if we're out of order; emit a warning. 5258 if (IdealIndex == NumIdealInits && PrevInit) { 5259 Sema::SemaDiagnosticBuilder D = 5260 SemaRef.Diag(PrevInit->getSourceLocation(), 5261 diag::warn_initializer_out_of_order); 5262 5263 if (PrevInit->isAnyMemberInitializer()) 5264 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5265 else 5266 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5267 5268 if (Init->isAnyMemberInitializer()) 5269 D << 0 << Init->getAnyMember()->getDeclName(); 5270 else 5271 D << 1 << Init->getTypeSourceInfo()->getType(); 5272 5273 // Move back to the initializer's location in the ideal list. 5274 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5275 if (InitKey == IdealInitKeys[IdealIndex]) 5276 break; 5277 5278 assert(IdealIndex < NumIdealInits && 5279 "initializer not found in initializer list"); 5280 } 5281 5282 PrevInit = Init; 5283 } 5284 } 5285 5286 namespace { 5287 bool CheckRedundantInit(Sema &S, 5288 CXXCtorInitializer *Init, 5289 CXXCtorInitializer *&PrevInit) { 5290 if (!PrevInit) { 5291 PrevInit = Init; 5292 return false; 5293 } 5294 5295 if (FieldDecl *Field = Init->getAnyMember()) 5296 S.Diag(Init->getSourceLocation(), 5297 diag::err_multiple_mem_initialization) 5298 << Field->getDeclName() 5299 << Init->getSourceRange(); 5300 else { 5301 const Type *BaseClass = Init->getBaseClass(); 5302 assert(BaseClass && "neither field nor base"); 5303 S.Diag(Init->getSourceLocation(), 5304 diag::err_multiple_base_initialization) 5305 << QualType(BaseClass, 0) 5306 << Init->getSourceRange(); 5307 } 5308 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5309 << 0 << PrevInit->getSourceRange(); 5310 5311 return true; 5312 } 5313 5314 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5315 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5316 5317 bool CheckRedundantUnionInit(Sema &S, 5318 CXXCtorInitializer *Init, 5319 RedundantUnionMap &Unions) { 5320 FieldDecl *Field = Init->getAnyMember(); 5321 RecordDecl *Parent = Field->getParent(); 5322 NamedDecl *Child = Field; 5323 5324 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5325 if (Parent->isUnion()) { 5326 UnionEntry &En = Unions[Parent]; 5327 if (En.first && En.first != Child) { 5328 S.Diag(Init->getSourceLocation(), 5329 diag::err_multiple_mem_union_initialization) 5330 << Field->getDeclName() 5331 << Init->getSourceRange(); 5332 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5333 << 0 << En.second->getSourceRange(); 5334 return true; 5335 } 5336 if (!En.first) { 5337 En.first = Child; 5338 En.second = Init; 5339 } 5340 if (!Parent->isAnonymousStructOrUnion()) 5341 return false; 5342 } 5343 5344 Child = Parent; 5345 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5346 } 5347 5348 return false; 5349 } 5350 } 5351 5352 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5353 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5354 SourceLocation ColonLoc, 5355 ArrayRef<CXXCtorInitializer*> MemInits, 5356 bool AnyErrors) { 5357 if (!ConstructorDecl) 5358 return; 5359 5360 AdjustDeclIfTemplate(ConstructorDecl); 5361 5362 CXXConstructorDecl *Constructor 5363 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5364 5365 if (!Constructor) { 5366 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5367 return; 5368 } 5369 5370 // Mapping for the duplicate initializers check. 5371 // For member initializers, this is keyed with a FieldDecl*. 5372 // For base initializers, this is keyed with a Type*. 5373 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5374 5375 // Mapping for the inconsistent anonymous-union initializers check. 5376 RedundantUnionMap MemberUnions; 5377 5378 bool HadError = false; 5379 for (unsigned i = 0; i < MemInits.size(); i++) { 5380 CXXCtorInitializer *Init = MemInits[i]; 5381 5382 // Set the source order index. 5383 Init->setSourceOrder(i); 5384 5385 if (Init->isAnyMemberInitializer()) { 5386 const void *Key = GetKeyForMember(Context, Init); 5387 if (CheckRedundantInit(*this, Init, Members[Key]) || 5388 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5389 HadError = true; 5390 } else if (Init->isBaseInitializer()) { 5391 const void *Key = GetKeyForMember(Context, Init); 5392 if (CheckRedundantInit(*this, Init, Members[Key])) 5393 HadError = true; 5394 } else { 5395 assert(Init->isDelegatingInitializer()); 5396 // This must be the only initializer 5397 if (MemInits.size() != 1) { 5398 Diag(Init->getSourceLocation(), 5399 diag::err_delegating_initializer_alone) 5400 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5401 // We will treat this as being the only initializer. 5402 } 5403 SetDelegatingInitializer(Constructor, MemInits[i]); 5404 // Return immediately as the initializer is set. 5405 return; 5406 } 5407 } 5408 5409 if (HadError) 5410 return; 5411 5412 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5413 5414 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5415 5416 DiagnoseUninitializedFields(*this, Constructor); 5417 } 5418 5419 void 5420 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5421 CXXRecordDecl *ClassDecl) { 5422 // Ignore dependent contexts. Also ignore unions, since their members never 5423 // have destructors implicitly called. 5424 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5425 return; 5426 5427 // FIXME: all the access-control diagnostics are positioned on the 5428 // field/base declaration. That's probably good; that said, the 5429 // user might reasonably want to know why the destructor is being 5430 // emitted, and we currently don't say. 5431 5432 // Non-static data members. 5433 for (auto *Field : ClassDecl->fields()) { 5434 if (Field->isInvalidDecl()) 5435 continue; 5436 5437 // Don't destroy incomplete or zero-length arrays. 5438 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5439 continue; 5440 5441 QualType FieldType = Context.getBaseElementType(Field->getType()); 5442 5443 const RecordType* RT = FieldType->getAs<RecordType>(); 5444 if (!RT) 5445 continue; 5446 5447 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5448 if (FieldClassDecl->isInvalidDecl()) 5449 continue; 5450 if (FieldClassDecl->hasIrrelevantDestructor()) 5451 continue; 5452 // The destructor for an implicit anonymous union member is never invoked. 5453 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5454 continue; 5455 5456 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5457 assert(Dtor && "No dtor found for FieldClassDecl!"); 5458 CheckDestructorAccess(Field->getLocation(), Dtor, 5459 PDiag(diag::err_access_dtor_field) 5460 << Field->getDeclName() 5461 << FieldType); 5462 5463 MarkFunctionReferenced(Location, Dtor); 5464 DiagnoseUseOfDecl(Dtor, Location); 5465 } 5466 5467 // We only potentially invoke the destructors of potentially constructed 5468 // subobjects. 5469 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5470 5471 // If the destructor exists and has already been marked used in the MS ABI, 5472 // then virtual base destructors have already been checked and marked used. 5473 // Skip checking them again to avoid duplicate diagnostics. 5474 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5475 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5476 if (Dtor && Dtor->isUsed()) 5477 VisitVirtualBases = false; 5478 } 5479 5480 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5481 5482 // Bases. 5483 for (const auto &Base : ClassDecl->bases()) { 5484 // Bases are always records in a well-formed non-dependent class. 5485 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5486 5487 // Remember direct virtual bases. 5488 if (Base.isVirtual()) { 5489 if (!VisitVirtualBases) 5490 continue; 5491 DirectVirtualBases.insert(RT); 5492 } 5493 5494 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5495 // If our base class is invalid, we probably can't get its dtor anyway. 5496 if (BaseClassDecl->isInvalidDecl()) 5497 continue; 5498 if (BaseClassDecl->hasIrrelevantDestructor()) 5499 continue; 5500 5501 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5502 assert(Dtor && "No dtor found for BaseClassDecl!"); 5503 5504 // FIXME: caret should be on the start of the class name 5505 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5506 PDiag(diag::err_access_dtor_base) 5507 << Base.getType() << Base.getSourceRange(), 5508 Context.getTypeDeclType(ClassDecl)); 5509 5510 MarkFunctionReferenced(Location, Dtor); 5511 DiagnoseUseOfDecl(Dtor, Location); 5512 } 5513 5514 if (VisitVirtualBases) 5515 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5516 &DirectVirtualBases); 5517 } 5518 5519 void Sema::MarkVirtualBaseDestructorsReferenced( 5520 SourceLocation Location, CXXRecordDecl *ClassDecl, 5521 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5522 // Virtual bases. 5523 for (const auto &VBase : ClassDecl->vbases()) { 5524 // Bases are always records in a well-formed non-dependent class. 5525 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5526 5527 // Ignore already visited direct virtual bases. 5528 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5529 continue; 5530 5531 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5532 // If our base class is invalid, we probably can't get its dtor anyway. 5533 if (BaseClassDecl->isInvalidDecl()) 5534 continue; 5535 if (BaseClassDecl->hasIrrelevantDestructor()) 5536 continue; 5537 5538 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5539 assert(Dtor && "No dtor found for BaseClassDecl!"); 5540 if (CheckDestructorAccess( 5541 ClassDecl->getLocation(), Dtor, 5542 PDiag(diag::err_access_dtor_vbase) 5543 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5544 Context.getTypeDeclType(ClassDecl)) == 5545 AR_accessible) { 5546 CheckDerivedToBaseConversion( 5547 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5548 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5549 SourceRange(), DeclarationName(), nullptr); 5550 } 5551 5552 MarkFunctionReferenced(Location, Dtor); 5553 DiagnoseUseOfDecl(Dtor, Location); 5554 } 5555 } 5556 5557 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5558 if (!CDtorDecl) 5559 return; 5560 5561 if (CXXConstructorDecl *Constructor 5562 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5563 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5564 DiagnoseUninitializedFields(*this, Constructor); 5565 } 5566 } 5567 5568 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5569 if (!getLangOpts().CPlusPlus) 5570 return false; 5571 5572 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5573 if (!RD) 5574 return false; 5575 5576 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5577 // class template specialization here, but doing so breaks a lot of code. 5578 5579 // We can't answer whether something is abstract until it has a 5580 // definition. If it's currently being defined, we'll walk back 5581 // over all the declarations when we have a full definition. 5582 const CXXRecordDecl *Def = RD->getDefinition(); 5583 if (!Def || Def->isBeingDefined()) 5584 return false; 5585 5586 return RD->isAbstract(); 5587 } 5588 5589 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5590 TypeDiagnoser &Diagnoser) { 5591 if (!isAbstractType(Loc, T)) 5592 return false; 5593 5594 T = Context.getBaseElementType(T); 5595 Diagnoser.diagnose(*this, Loc, T); 5596 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5597 return true; 5598 } 5599 5600 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5601 // Check if we've already emitted the list of pure virtual functions 5602 // for this class. 5603 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5604 return; 5605 5606 // If the diagnostic is suppressed, don't emit the notes. We're only 5607 // going to emit them once, so try to attach them to a diagnostic we're 5608 // actually going to show. 5609 if (Diags.isLastDiagnosticIgnored()) 5610 return; 5611 5612 CXXFinalOverriderMap FinalOverriders; 5613 RD->getFinalOverriders(FinalOverriders); 5614 5615 // Keep a set of seen pure methods so we won't diagnose the same method 5616 // more than once. 5617 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5618 5619 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5620 MEnd = FinalOverriders.end(); 5621 M != MEnd; 5622 ++M) { 5623 for (OverridingMethods::iterator SO = M->second.begin(), 5624 SOEnd = M->second.end(); 5625 SO != SOEnd; ++SO) { 5626 // C++ [class.abstract]p4: 5627 // A class is abstract if it contains or inherits at least one 5628 // pure virtual function for which the final overrider is pure 5629 // virtual. 5630 5631 // 5632 if (SO->second.size() != 1) 5633 continue; 5634 5635 if (!SO->second.front().Method->isPure()) 5636 continue; 5637 5638 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5639 continue; 5640 5641 Diag(SO->second.front().Method->getLocation(), 5642 diag::note_pure_virtual_function) 5643 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5644 } 5645 } 5646 5647 if (!PureVirtualClassDiagSet) 5648 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5649 PureVirtualClassDiagSet->insert(RD); 5650 } 5651 5652 namespace { 5653 struct AbstractUsageInfo { 5654 Sema &S; 5655 CXXRecordDecl *Record; 5656 CanQualType AbstractType; 5657 bool Invalid; 5658 5659 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5660 : S(S), Record(Record), 5661 AbstractType(S.Context.getCanonicalType( 5662 S.Context.getTypeDeclType(Record))), 5663 Invalid(false) {} 5664 5665 void DiagnoseAbstractType() { 5666 if (Invalid) return; 5667 S.DiagnoseAbstractType(Record); 5668 Invalid = true; 5669 } 5670 5671 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5672 }; 5673 5674 struct CheckAbstractUsage { 5675 AbstractUsageInfo &Info; 5676 const NamedDecl *Ctx; 5677 5678 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5679 : Info(Info), Ctx(Ctx) {} 5680 5681 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5682 switch (TL.getTypeLocClass()) { 5683 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5684 #define TYPELOC(CLASS, PARENT) \ 5685 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5686 #include "clang/AST/TypeLocNodes.def" 5687 } 5688 } 5689 5690 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5691 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5692 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5693 if (!TL.getParam(I)) 5694 continue; 5695 5696 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5697 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5698 } 5699 } 5700 5701 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5702 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5703 } 5704 5705 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5706 // Visit the type parameters from a permissive context. 5707 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5708 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5709 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5710 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5711 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5712 // TODO: other template argument types? 5713 } 5714 } 5715 5716 // Visit pointee types from a permissive context. 5717 #define CheckPolymorphic(Type) \ 5718 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5719 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5720 } 5721 CheckPolymorphic(PointerTypeLoc) 5722 CheckPolymorphic(ReferenceTypeLoc) 5723 CheckPolymorphic(MemberPointerTypeLoc) 5724 CheckPolymorphic(BlockPointerTypeLoc) 5725 CheckPolymorphic(AtomicTypeLoc) 5726 5727 /// Handle all the types we haven't given a more specific 5728 /// implementation for above. 5729 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5730 // Every other kind of type that we haven't called out already 5731 // that has an inner type is either (1) sugar or (2) contains that 5732 // inner type in some way as a subobject. 5733 if (TypeLoc Next = TL.getNextTypeLoc()) 5734 return Visit(Next, Sel); 5735 5736 // If there's no inner type and we're in a permissive context, 5737 // don't diagnose. 5738 if (Sel == Sema::AbstractNone) return; 5739 5740 // Check whether the type matches the abstract type. 5741 QualType T = TL.getType(); 5742 if (T->isArrayType()) { 5743 Sel = Sema::AbstractArrayType; 5744 T = Info.S.Context.getBaseElementType(T); 5745 } 5746 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5747 if (CT != Info.AbstractType) return; 5748 5749 // It matched; do some magic. 5750 if (Sel == Sema::AbstractArrayType) { 5751 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5752 << T << TL.getSourceRange(); 5753 } else { 5754 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5755 << Sel << T << TL.getSourceRange(); 5756 } 5757 Info.DiagnoseAbstractType(); 5758 } 5759 }; 5760 5761 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5762 Sema::AbstractDiagSelID Sel) { 5763 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5764 } 5765 5766 } 5767 5768 /// Check for invalid uses of an abstract type in a method declaration. 5769 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5770 CXXMethodDecl *MD) { 5771 // No need to do the check on definitions, which require that 5772 // the return/param types be complete. 5773 if (MD->doesThisDeclarationHaveABody()) 5774 return; 5775 5776 // For safety's sake, just ignore it if we don't have type source 5777 // information. This should never happen for non-implicit methods, 5778 // but... 5779 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5780 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5781 } 5782 5783 /// Check for invalid uses of an abstract type within a class definition. 5784 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5785 CXXRecordDecl *RD) { 5786 for (auto *D : RD->decls()) { 5787 if (D->isImplicit()) continue; 5788 5789 // Methods and method templates. 5790 if (isa<CXXMethodDecl>(D)) { 5791 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5792 } else if (isa<FunctionTemplateDecl>(D)) { 5793 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5794 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5795 5796 // Fields and static variables. 5797 } else if (isa<FieldDecl>(D)) { 5798 FieldDecl *FD = cast<FieldDecl>(D); 5799 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5800 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5801 } else if (isa<VarDecl>(D)) { 5802 VarDecl *VD = cast<VarDecl>(D); 5803 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5804 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5805 5806 // Nested classes and class templates. 5807 } else if (isa<CXXRecordDecl>(D)) { 5808 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5809 } else if (isa<ClassTemplateDecl>(D)) { 5810 CheckAbstractClassUsage(Info, 5811 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5812 } 5813 } 5814 } 5815 5816 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5817 Attr *ClassAttr = getDLLAttr(Class); 5818 if (!ClassAttr) 5819 return; 5820 5821 assert(ClassAttr->getKind() == attr::DLLExport); 5822 5823 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5824 5825 if (TSK == TSK_ExplicitInstantiationDeclaration) 5826 // Don't go any further if this is just an explicit instantiation 5827 // declaration. 5828 return; 5829 5830 // Add a context note to explain how we got to any diagnostics produced below. 5831 struct MarkingClassDllexported { 5832 Sema &S; 5833 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5834 SourceLocation AttrLoc) 5835 : S(S) { 5836 Sema::CodeSynthesisContext Ctx; 5837 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5838 Ctx.PointOfInstantiation = AttrLoc; 5839 Ctx.Entity = Class; 5840 S.pushCodeSynthesisContext(Ctx); 5841 } 5842 ~MarkingClassDllexported() { 5843 S.popCodeSynthesisContext(); 5844 } 5845 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5846 5847 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5848 S.MarkVTableUsed(Class->getLocation(), Class, true); 5849 5850 for (Decl *Member : Class->decls()) { 5851 // Defined static variables that are members of an exported base 5852 // class must be marked export too. 5853 auto *VD = dyn_cast<VarDecl>(Member); 5854 if (VD && Member->getAttr<DLLExportAttr>() && 5855 VD->getStorageClass() == SC_Static && 5856 TSK == TSK_ImplicitInstantiation) 5857 S.MarkVariableReferenced(VD->getLocation(), VD); 5858 5859 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5860 if (!MD) 5861 continue; 5862 5863 if (Member->getAttr<DLLExportAttr>()) { 5864 if (MD->isUserProvided()) { 5865 // Instantiate non-default class member functions ... 5866 5867 // .. except for certain kinds of template specializations. 5868 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5869 continue; 5870 5871 S.MarkFunctionReferenced(Class->getLocation(), MD); 5872 5873 // The function will be passed to the consumer when its definition is 5874 // encountered. 5875 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5876 MD->isCopyAssignmentOperator() || 5877 MD->isMoveAssignmentOperator()) { 5878 // Synthesize and instantiate non-trivial implicit methods, explicitly 5879 // defaulted methods, and the copy and move assignment operators. The 5880 // latter are exported even if they are trivial, because the address of 5881 // an operator can be taken and should compare equal across libraries. 5882 S.MarkFunctionReferenced(Class->getLocation(), MD); 5883 5884 // There is no later point when we will see the definition of this 5885 // function, so pass it to the consumer now. 5886 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5887 } 5888 } 5889 } 5890 } 5891 5892 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5893 CXXRecordDecl *Class) { 5894 // Only the MS ABI has default constructor closures, so we don't need to do 5895 // this semantic checking anywhere else. 5896 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5897 return; 5898 5899 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5900 for (Decl *Member : Class->decls()) { 5901 // Look for exported default constructors. 5902 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5903 if (!CD || !CD->isDefaultConstructor()) 5904 continue; 5905 auto *Attr = CD->getAttr<DLLExportAttr>(); 5906 if (!Attr) 5907 continue; 5908 5909 // If the class is non-dependent, mark the default arguments as ODR-used so 5910 // that we can properly codegen the constructor closure. 5911 if (!Class->isDependentContext()) { 5912 for (ParmVarDecl *PD : CD->parameters()) { 5913 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5914 S.DiscardCleanupsInEvaluationContext(); 5915 } 5916 } 5917 5918 if (LastExportedDefaultCtor) { 5919 S.Diag(LastExportedDefaultCtor->getLocation(), 5920 diag::err_attribute_dll_ambiguous_default_ctor) 5921 << Class; 5922 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5923 << CD->getDeclName(); 5924 return; 5925 } 5926 LastExportedDefaultCtor = CD; 5927 } 5928 } 5929 5930 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 5931 CXXRecordDecl *Class) { 5932 bool ErrorReported = false; 5933 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5934 ClassTemplateDecl *TD) { 5935 if (ErrorReported) 5936 return; 5937 S.Diag(TD->getLocation(), 5938 diag::err_cuda_device_builtin_surftex_cls_template) 5939 << /*surface*/ 0 << TD; 5940 ErrorReported = true; 5941 }; 5942 5943 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5944 if (!TD) { 5945 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 5946 if (!SD) { 5947 S.Diag(Class->getLocation(), 5948 diag::err_cuda_device_builtin_surftex_ref_decl) 5949 << /*surface*/ 0 << Class; 5950 S.Diag(Class->getLocation(), 5951 diag::note_cuda_device_builtin_surftex_should_be_template_class) 5952 << Class; 5953 return; 5954 } 5955 TD = SD->getSpecializedTemplate(); 5956 } 5957 5958 TemplateParameterList *Params = TD->getTemplateParameters(); 5959 unsigned N = Params->size(); 5960 5961 if (N != 2) { 5962 reportIllegalClassTemplate(S, TD); 5963 S.Diag(TD->getLocation(), 5964 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 5965 << TD << 2; 5966 } 5967 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 5968 reportIllegalClassTemplate(S, TD); 5969 S.Diag(TD->getLocation(), 5970 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 5971 << TD << /*1st*/ 0 << /*type*/ 0; 5972 } 5973 if (N > 1) { 5974 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 5975 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 5976 reportIllegalClassTemplate(S, TD); 5977 S.Diag(TD->getLocation(), 5978 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 5979 << TD << /*2nd*/ 1 << /*integer*/ 1; 5980 } 5981 } 5982 } 5983 5984 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 5985 CXXRecordDecl *Class) { 5986 bool ErrorReported = false; 5987 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5988 ClassTemplateDecl *TD) { 5989 if (ErrorReported) 5990 return; 5991 S.Diag(TD->getLocation(), 5992 diag::err_cuda_device_builtin_surftex_cls_template) 5993 << /*texture*/ 1 << TD; 5994 ErrorReported = true; 5995 }; 5996 5997 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5998 if (!TD) { 5999 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6000 if (!SD) { 6001 S.Diag(Class->getLocation(), 6002 diag::err_cuda_device_builtin_surftex_ref_decl) 6003 << /*texture*/ 1 << Class; 6004 S.Diag(Class->getLocation(), 6005 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6006 << Class; 6007 return; 6008 } 6009 TD = SD->getSpecializedTemplate(); 6010 } 6011 6012 TemplateParameterList *Params = TD->getTemplateParameters(); 6013 unsigned N = Params->size(); 6014 6015 if (N != 3) { 6016 reportIllegalClassTemplate(S, TD); 6017 S.Diag(TD->getLocation(), 6018 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6019 << TD << 3; 6020 } 6021 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6022 reportIllegalClassTemplate(S, TD); 6023 S.Diag(TD->getLocation(), 6024 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6025 << TD << /*1st*/ 0 << /*type*/ 0; 6026 } 6027 if (N > 1) { 6028 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6029 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6030 reportIllegalClassTemplate(S, TD); 6031 S.Diag(TD->getLocation(), 6032 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6033 << TD << /*2nd*/ 1 << /*integer*/ 1; 6034 } 6035 } 6036 if (N > 2) { 6037 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6038 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6039 reportIllegalClassTemplate(S, TD); 6040 S.Diag(TD->getLocation(), 6041 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6042 << TD << /*3rd*/ 2 << /*integer*/ 1; 6043 } 6044 } 6045 } 6046 6047 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6048 // Mark any compiler-generated routines with the implicit code_seg attribute. 6049 for (auto *Method : Class->methods()) { 6050 if (Method->isUserProvided()) 6051 continue; 6052 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6053 Method->addAttr(A); 6054 } 6055 } 6056 6057 /// Check class-level dllimport/dllexport attribute. 6058 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6059 Attr *ClassAttr = getDLLAttr(Class); 6060 6061 // MSVC inherits DLL attributes to partial class template specializations. 6062 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 6063 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6064 if (Attr *TemplateAttr = 6065 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6066 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6067 A->setInherited(true); 6068 ClassAttr = A; 6069 } 6070 } 6071 } 6072 6073 if (!ClassAttr) 6074 return; 6075 6076 if (!Class->isExternallyVisible()) { 6077 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6078 << Class << ClassAttr; 6079 return; 6080 } 6081 6082 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 6083 !ClassAttr->isInherited()) { 6084 // Diagnose dll attributes on members of class with dll attribute. 6085 for (Decl *Member : Class->decls()) { 6086 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6087 continue; 6088 InheritableAttr *MemberAttr = getDLLAttr(Member); 6089 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6090 continue; 6091 6092 Diag(MemberAttr->getLocation(), 6093 diag::err_attribute_dll_member_of_dll_class) 6094 << MemberAttr << ClassAttr; 6095 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6096 Member->setInvalidDecl(); 6097 } 6098 } 6099 6100 if (Class->getDescribedClassTemplate()) 6101 // Don't inherit dll attribute until the template is instantiated. 6102 return; 6103 6104 // The class is either imported or exported. 6105 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6106 6107 // Check if this was a dllimport attribute propagated from a derived class to 6108 // a base class template specialization. We don't apply these attributes to 6109 // static data members. 6110 const bool PropagatedImport = 6111 !ClassExported && 6112 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6113 6114 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6115 6116 // Ignore explicit dllexport on explicit class template instantiation 6117 // declarations, except in MinGW mode. 6118 if (ClassExported && !ClassAttr->isInherited() && 6119 TSK == TSK_ExplicitInstantiationDeclaration && 6120 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6121 Class->dropAttr<DLLExportAttr>(); 6122 return; 6123 } 6124 6125 // Force declaration of implicit members so they can inherit the attribute. 6126 ForceDeclarationOfImplicitMembers(Class); 6127 6128 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6129 // seem to be true in practice? 6130 6131 for (Decl *Member : Class->decls()) { 6132 VarDecl *VD = dyn_cast<VarDecl>(Member); 6133 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6134 6135 // Only methods and static fields inherit the attributes. 6136 if (!VD && !MD) 6137 continue; 6138 6139 if (MD) { 6140 // Don't process deleted methods. 6141 if (MD->isDeleted()) 6142 continue; 6143 6144 if (MD->isInlined()) { 6145 // MinGW does not import or export inline methods. But do it for 6146 // template instantiations. 6147 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 6148 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 6149 TSK != TSK_ExplicitInstantiationDeclaration && 6150 TSK != TSK_ExplicitInstantiationDefinition) 6151 continue; 6152 6153 // MSVC versions before 2015 don't export the move assignment operators 6154 // and move constructor, so don't attempt to import/export them if 6155 // we have a definition. 6156 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6157 if ((MD->isMoveAssignmentOperator() || 6158 (Ctor && Ctor->isMoveConstructor())) && 6159 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6160 continue; 6161 6162 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6163 // operator is exported anyway. 6164 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6165 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6166 continue; 6167 } 6168 } 6169 6170 // Don't apply dllimport attributes to static data members of class template 6171 // instantiations when the attribute is propagated from a derived class. 6172 if (VD && PropagatedImport) 6173 continue; 6174 6175 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6176 continue; 6177 6178 if (!getDLLAttr(Member)) { 6179 InheritableAttr *NewAttr = nullptr; 6180 6181 // Do not export/import inline function when -fno-dllexport-inlines is 6182 // passed. But add attribute for later local static var check. 6183 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6184 TSK != TSK_ExplicitInstantiationDeclaration && 6185 TSK != TSK_ExplicitInstantiationDefinition) { 6186 if (ClassExported) { 6187 NewAttr = ::new (getASTContext()) 6188 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6189 } else { 6190 NewAttr = ::new (getASTContext()) 6191 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6192 } 6193 } else { 6194 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6195 } 6196 6197 NewAttr->setInherited(true); 6198 Member->addAttr(NewAttr); 6199 6200 if (MD) { 6201 // Propagate DLLAttr to friend re-declarations of MD that have already 6202 // been constructed. 6203 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6204 FD = FD->getPreviousDecl()) { 6205 if (FD->getFriendObjectKind() == Decl::FOK_None) 6206 continue; 6207 assert(!getDLLAttr(FD) && 6208 "friend re-decl should not already have a DLLAttr"); 6209 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6210 NewAttr->setInherited(true); 6211 FD->addAttr(NewAttr); 6212 } 6213 } 6214 } 6215 } 6216 6217 if (ClassExported) 6218 DelayedDllExportClasses.push_back(Class); 6219 } 6220 6221 /// Perform propagation of DLL attributes from a derived class to a 6222 /// templated base class for MS compatibility. 6223 void Sema::propagateDLLAttrToBaseClassTemplate( 6224 CXXRecordDecl *Class, Attr *ClassAttr, 6225 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6226 if (getDLLAttr( 6227 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6228 // If the base class template has a DLL attribute, don't try to change it. 6229 return; 6230 } 6231 6232 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6233 if (!getDLLAttr(BaseTemplateSpec) && 6234 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6235 TSK == TSK_ImplicitInstantiation)) { 6236 // The template hasn't been instantiated yet (or it has, but only as an 6237 // explicit instantiation declaration or implicit instantiation, which means 6238 // we haven't codegenned any members yet), so propagate the attribute. 6239 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6240 NewAttr->setInherited(true); 6241 BaseTemplateSpec->addAttr(NewAttr); 6242 6243 // If this was an import, mark that we propagated it from a derived class to 6244 // a base class template specialization. 6245 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6246 ImportAttr->setPropagatedToBaseTemplate(); 6247 6248 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6249 // needs to be run again to work see the new attribute. Otherwise this will 6250 // get run whenever the template is instantiated. 6251 if (TSK != TSK_Undeclared) 6252 checkClassLevelDLLAttribute(BaseTemplateSpec); 6253 6254 return; 6255 } 6256 6257 if (getDLLAttr(BaseTemplateSpec)) { 6258 // The template has already been specialized or instantiated with an 6259 // attribute, explicitly or through propagation. We should not try to change 6260 // it. 6261 return; 6262 } 6263 6264 // The template was previously instantiated or explicitly specialized without 6265 // a dll attribute, It's too late for us to add an attribute, so warn that 6266 // this is unsupported. 6267 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6268 << BaseTemplateSpec->isExplicitSpecialization(); 6269 Diag(ClassAttr->getLocation(), diag::note_attribute); 6270 if (BaseTemplateSpec->isExplicitSpecialization()) { 6271 Diag(BaseTemplateSpec->getLocation(), 6272 diag::note_template_class_explicit_specialization_was_here) 6273 << BaseTemplateSpec; 6274 } else { 6275 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6276 diag::note_template_class_instantiation_was_here) 6277 << BaseTemplateSpec; 6278 } 6279 } 6280 6281 /// Determine the kind of defaulting that would be done for a given function. 6282 /// 6283 /// If the function is both a default constructor and a copy / move constructor 6284 /// (due to having a default argument for the first parameter), this picks 6285 /// CXXDefaultConstructor. 6286 /// 6287 /// FIXME: Check that case is properly handled by all callers. 6288 Sema::DefaultedFunctionKind 6289 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6290 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6291 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6292 if (Ctor->isDefaultConstructor()) 6293 return Sema::CXXDefaultConstructor; 6294 6295 if (Ctor->isCopyConstructor()) 6296 return Sema::CXXCopyConstructor; 6297 6298 if (Ctor->isMoveConstructor()) 6299 return Sema::CXXMoveConstructor; 6300 } 6301 6302 if (MD->isCopyAssignmentOperator()) 6303 return Sema::CXXCopyAssignment; 6304 6305 if (MD->isMoveAssignmentOperator()) 6306 return Sema::CXXMoveAssignment; 6307 6308 if (isa<CXXDestructorDecl>(FD)) 6309 return Sema::CXXDestructor; 6310 } 6311 6312 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6313 case OO_EqualEqual: 6314 return DefaultedComparisonKind::Equal; 6315 6316 case OO_ExclaimEqual: 6317 return DefaultedComparisonKind::NotEqual; 6318 6319 case OO_Spaceship: 6320 // No point allowing this if <=> doesn't exist in the current language mode. 6321 if (!getLangOpts().CPlusPlus20) 6322 break; 6323 return DefaultedComparisonKind::ThreeWay; 6324 6325 case OO_Less: 6326 case OO_LessEqual: 6327 case OO_Greater: 6328 case OO_GreaterEqual: 6329 // No point allowing this if <=> doesn't exist in the current language mode. 6330 if (!getLangOpts().CPlusPlus20) 6331 break; 6332 return DefaultedComparisonKind::Relational; 6333 6334 default: 6335 break; 6336 } 6337 6338 // Not defaultable. 6339 return DefaultedFunctionKind(); 6340 } 6341 6342 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6343 SourceLocation DefaultLoc) { 6344 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6345 if (DFK.isComparison()) 6346 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6347 6348 switch (DFK.asSpecialMember()) { 6349 case Sema::CXXDefaultConstructor: 6350 S.DefineImplicitDefaultConstructor(DefaultLoc, 6351 cast<CXXConstructorDecl>(FD)); 6352 break; 6353 case Sema::CXXCopyConstructor: 6354 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6355 break; 6356 case Sema::CXXCopyAssignment: 6357 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6358 break; 6359 case Sema::CXXDestructor: 6360 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6361 break; 6362 case Sema::CXXMoveConstructor: 6363 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6364 break; 6365 case Sema::CXXMoveAssignment: 6366 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6367 break; 6368 case Sema::CXXInvalid: 6369 llvm_unreachable("Invalid special member."); 6370 } 6371 } 6372 6373 /// Determine whether a type is permitted to be passed or returned in 6374 /// registers, per C++ [class.temporary]p3. 6375 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6376 TargetInfo::CallingConvKind CCK) { 6377 if (D->isDependentType() || D->isInvalidDecl()) 6378 return false; 6379 6380 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6381 // The PS4 platform ABI follows the behavior of Clang 3.2. 6382 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6383 return !D->hasNonTrivialDestructorForCall() && 6384 !D->hasNonTrivialCopyConstructorForCall(); 6385 6386 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6387 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6388 bool DtorIsTrivialForCall = false; 6389 6390 // If a class has at least one non-deleted, trivial copy constructor, it 6391 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6392 // 6393 // Note: This permits classes with non-trivial copy or move ctors to be 6394 // passed in registers, so long as they *also* have a trivial copy ctor, 6395 // which is non-conforming. 6396 if (D->needsImplicitCopyConstructor()) { 6397 if (!D->defaultedCopyConstructorIsDeleted()) { 6398 if (D->hasTrivialCopyConstructor()) 6399 CopyCtorIsTrivial = true; 6400 if (D->hasTrivialCopyConstructorForCall()) 6401 CopyCtorIsTrivialForCall = true; 6402 } 6403 } else { 6404 for (const CXXConstructorDecl *CD : D->ctors()) { 6405 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6406 if (CD->isTrivial()) 6407 CopyCtorIsTrivial = true; 6408 if (CD->isTrivialForCall()) 6409 CopyCtorIsTrivialForCall = true; 6410 } 6411 } 6412 } 6413 6414 if (D->needsImplicitDestructor()) { 6415 if (!D->defaultedDestructorIsDeleted() && 6416 D->hasTrivialDestructorForCall()) 6417 DtorIsTrivialForCall = true; 6418 } else if (const auto *DD = D->getDestructor()) { 6419 if (!DD->isDeleted() && DD->isTrivialForCall()) 6420 DtorIsTrivialForCall = true; 6421 } 6422 6423 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6424 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6425 return true; 6426 6427 // If a class has a destructor, we'd really like to pass it indirectly 6428 // because it allows us to elide copies. Unfortunately, MSVC makes that 6429 // impossible for small types, which it will pass in a single register or 6430 // stack slot. Most objects with dtors are large-ish, so handle that early. 6431 // We can't call out all large objects as being indirect because there are 6432 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6433 // how we pass large POD types. 6434 6435 // Note: This permits small classes with nontrivial destructors to be 6436 // passed in registers, which is non-conforming. 6437 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6438 uint64_t TypeSize = isAArch64 ? 128 : 64; 6439 6440 if (CopyCtorIsTrivial && 6441 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6442 return true; 6443 return false; 6444 } 6445 6446 // Per C++ [class.temporary]p3, the relevant condition is: 6447 // each copy constructor, move constructor, and destructor of X is 6448 // either trivial or deleted, and X has at least one non-deleted copy 6449 // or move constructor 6450 bool HasNonDeletedCopyOrMove = false; 6451 6452 if (D->needsImplicitCopyConstructor() && 6453 !D->defaultedCopyConstructorIsDeleted()) { 6454 if (!D->hasTrivialCopyConstructorForCall()) 6455 return false; 6456 HasNonDeletedCopyOrMove = true; 6457 } 6458 6459 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6460 !D->defaultedMoveConstructorIsDeleted()) { 6461 if (!D->hasTrivialMoveConstructorForCall()) 6462 return false; 6463 HasNonDeletedCopyOrMove = true; 6464 } 6465 6466 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6467 !D->hasTrivialDestructorForCall()) 6468 return false; 6469 6470 for (const CXXMethodDecl *MD : D->methods()) { 6471 if (MD->isDeleted()) 6472 continue; 6473 6474 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6475 if (CD && CD->isCopyOrMoveConstructor()) 6476 HasNonDeletedCopyOrMove = true; 6477 else if (!isa<CXXDestructorDecl>(MD)) 6478 continue; 6479 6480 if (!MD->isTrivialForCall()) 6481 return false; 6482 } 6483 6484 return HasNonDeletedCopyOrMove; 6485 } 6486 6487 /// Report an error regarding overriding, along with any relevant 6488 /// overridden methods. 6489 /// 6490 /// \param DiagID the primary error to report. 6491 /// \param MD the overriding method. 6492 static bool 6493 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6494 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6495 bool IssuedDiagnostic = false; 6496 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6497 if (Report(O)) { 6498 if (!IssuedDiagnostic) { 6499 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6500 IssuedDiagnostic = true; 6501 } 6502 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6503 } 6504 } 6505 return IssuedDiagnostic; 6506 } 6507 6508 /// Perform semantic checks on a class definition that has been 6509 /// completing, introducing implicitly-declared members, checking for 6510 /// abstract types, etc. 6511 /// 6512 /// \param S The scope in which the class was parsed. Null if we didn't just 6513 /// parse a class definition. 6514 /// \param Record The completed class. 6515 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6516 if (!Record) 6517 return; 6518 6519 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6520 AbstractUsageInfo Info(*this, Record); 6521 CheckAbstractClassUsage(Info, Record); 6522 } 6523 6524 // If this is not an aggregate type and has no user-declared constructor, 6525 // complain about any non-static data members of reference or const scalar 6526 // type, since they will never get initializers. 6527 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6528 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6529 !Record->isLambda()) { 6530 bool Complained = false; 6531 for (const auto *F : Record->fields()) { 6532 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6533 continue; 6534 6535 if (F->getType()->isReferenceType() || 6536 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6537 if (!Complained) { 6538 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6539 << Record->getTagKind() << Record; 6540 Complained = true; 6541 } 6542 6543 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6544 << F->getType()->isReferenceType() 6545 << F->getDeclName(); 6546 } 6547 } 6548 } 6549 6550 if (Record->getIdentifier()) { 6551 // C++ [class.mem]p13: 6552 // If T is the name of a class, then each of the following shall have a 6553 // name different from T: 6554 // - every member of every anonymous union that is a member of class T. 6555 // 6556 // C++ [class.mem]p14: 6557 // In addition, if class T has a user-declared constructor (12.1), every 6558 // non-static data member of class T shall have a name different from T. 6559 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6560 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6561 ++I) { 6562 NamedDecl *D = (*I)->getUnderlyingDecl(); 6563 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6564 Record->hasUserDeclaredConstructor()) || 6565 isa<IndirectFieldDecl>(D)) { 6566 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6567 << D->getDeclName(); 6568 break; 6569 } 6570 } 6571 } 6572 6573 // Warn if the class has virtual methods but non-virtual public destructor. 6574 if (Record->isPolymorphic() && !Record->isDependentType()) { 6575 CXXDestructorDecl *dtor = Record->getDestructor(); 6576 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6577 !Record->hasAttr<FinalAttr>()) 6578 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6579 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6580 } 6581 6582 if (Record->isAbstract()) { 6583 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6584 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6585 << FA->isSpelledAsSealed(); 6586 DiagnoseAbstractType(Record); 6587 } 6588 } 6589 6590 // Warn if the class has a final destructor but is not itself marked final. 6591 if (!Record->hasAttr<FinalAttr>()) { 6592 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6593 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6594 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6595 << FA->isSpelledAsSealed() 6596 << FixItHint::CreateInsertion( 6597 getLocForEndOfToken(Record->getLocation()), 6598 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6599 Diag(Record->getLocation(), 6600 diag::note_final_dtor_non_final_class_silence) 6601 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6602 } 6603 } 6604 } 6605 6606 // See if trivial_abi has to be dropped. 6607 if (Record->hasAttr<TrivialABIAttr>()) 6608 checkIllFormedTrivialABIStruct(*Record); 6609 6610 // Set HasTrivialSpecialMemberForCall if the record has attribute 6611 // "trivial_abi". 6612 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6613 6614 if (HasTrivialABI) 6615 Record->setHasTrivialSpecialMemberForCall(); 6616 6617 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6618 // We check these last because they can depend on the properties of the 6619 // primary comparison functions (==, <=>). 6620 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6621 6622 // Perform checks that can't be done until we know all the properties of a 6623 // member function (whether it's defaulted, deleted, virtual, overriding, 6624 // ...). 6625 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6626 // A static function cannot override anything. 6627 if (MD->getStorageClass() == SC_Static) { 6628 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6629 [](const CXXMethodDecl *) { return true; })) 6630 return; 6631 } 6632 6633 // A deleted function cannot override a non-deleted function and vice 6634 // versa. 6635 if (ReportOverrides(*this, 6636 MD->isDeleted() ? diag::err_deleted_override 6637 : diag::err_non_deleted_override, 6638 MD, [&](const CXXMethodDecl *V) { 6639 return MD->isDeleted() != V->isDeleted(); 6640 })) { 6641 if (MD->isDefaulted() && MD->isDeleted()) 6642 // Explain why this defaulted function was deleted. 6643 DiagnoseDeletedDefaultedFunction(MD); 6644 return; 6645 } 6646 6647 // A consteval function cannot override a non-consteval function and vice 6648 // versa. 6649 if (ReportOverrides(*this, 6650 MD->isConsteval() ? diag::err_consteval_override 6651 : diag::err_non_consteval_override, 6652 MD, [&](const CXXMethodDecl *V) { 6653 return MD->isConsteval() != V->isConsteval(); 6654 })) { 6655 if (MD->isDefaulted() && MD->isDeleted()) 6656 // Explain why this defaulted function was deleted. 6657 DiagnoseDeletedDefaultedFunction(MD); 6658 return; 6659 } 6660 }; 6661 6662 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6663 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6664 return false; 6665 6666 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6667 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6668 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6669 DefaultedSecondaryComparisons.push_back(FD); 6670 return true; 6671 } 6672 6673 CheckExplicitlyDefaultedFunction(S, FD); 6674 return false; 6675 }; 6676 6677 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6678 // Check whether the explicitly-defaulted members are valid. 6679 bool Incomplete = CheckForDefaultedFunction(M); 6680 6681 // Skip the rest of the checks for a member of a dependent class. 6682 if (Record->isDependentType()) 6683 return; 6684 6685 // For an explicitly defaulted or deleted special member, we defer 6686 // determining triviality until the class is complete. That time is now! 6687 CXXSpecialMember CSM = getSpecialMember(M); 6688 if (!M->isImplicit() && !M->isUserProvided()) { 6689 if (CSM != CXXInvalid) { 6690 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6691 // Inform the class that we've finished declaring this member. 6692 Record->finishedDefaultedOrDeletedMember(M); 6693 M->setTrivialForCall( 6694 HasTrivialABI || 6695 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6696 Record->setTrivialForCallFlags(M); 6697 } 6698 } 6699 6700 // Set triviality for the purpose of calls if this is a user-provided 6701 // copy/move constructor or destructor. 6702 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6703 CSM == CXXDestructor) && M->isUserProvided()) { 6704 M->setTrivialForCall(HasTrivialABI); 6705 Record->setTrivialForCallFlags(M); 6706 } 6707 6708 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6709 M->hasAttr<DLLExportAttr>()) { 6710 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6711 M->isTrivial() && 6712 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6713 CSM == CXXDestructor)) 6714 M->dropAttr<DLLExportAttr>(); 6715 6716 if (M->hasAttr<DLLExportAttr>()) { 6717 // Define after any fields with in-class initializers have been parsed. 6718 DelayedDllExportMemberFunctions.push_back(M); 6719 } 6720 } 6721 6722 // Define defaulted constexpr virtual functions that override a base class 6723 // function right away. 6724 // FIXME: We can defer doing this until the vtable is marked as used. 6725 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6726 DefineDefaultedFunction(*this, M, M->getLocation()); 6727 6728 if (!Incomplete) 6729 CheckCompletedMemberFunction(M); 6730 }; 6731 6732 // Check the destructor before any other member function. We need to 6733 // determine whether it's trivial in order to determine whether the claas 6734 // type is a literal type, which is a prerequisite for determining whether 6735 // other special member functions are valid and whether they're implicitly 6736 // 'constexpr'. 6737 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6738 CompleteMemberFunction(Dtor); 6739 6740 bool HasMethodWithOverrideControl = false, 6741 HasOverridingMethodWithoutOverrideControl = false; 6742 for (auto *D : Record->decls()) { 6743 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6744 // FIXME: We could do this check for dependent types with non-dependent 6745 // bases. 6746 if (!Record->isDependentType()) { 6747 // See if a method overloads virtual methods in a base 6748 // class without overriding any. 6749 if (!M->isStatic()) 6750 DiagnoseHiddenVirtualMethods(M); 6751 if (M->hasAttr<OverrideAttr>()) 6752 HasMethodWithOverrideControl = true; 6753 else if (M->size_overridden_methods() > 0) 6754 HasOverridingMethodWithoutOverrideControl = true; 6755 } 6756 6757 if (!isa<CXXDestructorDecl>(M)) 6758 CompleteMemberFunction(M); 6759 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6760 CheckForDefaultedFunction( 6761 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6762 } 6763 } 6764 6765 if (HasOverridingMethodWithoutOverrideControl) { 6766 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6767 for (auto *M : Record->methods()) 6768 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6769 } 6770 6771 // Check the defaulted secondary comparisons after any other member functions. 6772 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6773 CheckExplicitlyDefaultedFunction(S, FD); 6774 6775 // If this is a member function, we deferred checking it until now. 6776 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6777 CheckCompletedMemberFunction(MD); 6778 } 6779 6780 // ms_struct is a request to use the same ABI rules as MSVC. Check 6781 // whether this class uses any C++ features that are implemented 6782 // completely differently in MSVC, and if so, emit a diagnostic. 6783 // That diagnostic defaults to an error, but we allow projects to 6784 // map it down to a warning (or ignore it). It's a fairly common 6785 // practice among users of the ms_struct pragma to mass-annotate 6786 // headers, sweeping up a bunch of types that the project doesn't 6787 // really rely on MSVC-compatible layout for. We must therefore 6788 // support "ms_struct except for C++ stuff" as a secondary ABI. 6789 // Don't emit this diagnostic if the feature was enabled as a 6790 // language option (as opposed to via a pragma or attribute), as 6791 // the option -mms-bitfields otherwise essentially makes it impossible 6792 // to build C++ code, unless this diagnostic is turned off. 6793 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6794 (Record->isPolymorphic() || Record->getNumBases())) { 6795 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6796 } 6797 6798 checkClassLevelDLLAttribute(Record); 6799 checkClassLevelCodeSegAttribute(Record); 6800 6801 bool ClangABICompat4 = 6802 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6803 TargetInfo::CallingConvKind CCK = 6804 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6805 bool CanPass = canPassInRegisters(*this, Record, CCK); 6806 6807 // Do not change ArgPassingRestrictions if it has already been set to 6808 // APK_CanNeverPassInRegs. 6809 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6810 Record->setArgPassingRestrictions(CanPass 6811 ? RecordDecl::APK_CanPassInRegs 6812 : RecordDecl::APK_CannotPassInRegs); 6813 6814 // If canPassInRegisters returns true despite the record having a non-trivial 6815 // destructor, the record is destructed in the callee. This happens only when 6816 // the record or one of its subobjects has a field annotated with trivial_abi 6817 // or a field qualified with ObjC __strong/__weak. 6818 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6819 Record->setParamDestroyedInCallee(true); 6820 else if (Record->hasNonTrivialDestructor()) 6821 Record->setParamDestroyedInCallee(CanPass); 6822 6823 if (getLangOpts().ForceEmitVTables) { 6824 // If we want to emit all the vtables, we need to mark it as used. This 6825 // is especially required for cases like vtable assumption loads. 6826 MarkVTableUsed(Record->getInnerLocStart(), Record); 6827 } 6828 6829 if (getLangOpts().CUDA) { 6830 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6831 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6832 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6833 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6834 } 6835 } 6836 6837 /// Look up the special member function that would be called by a special 6838 /// member function for a subobject of class type. 6839 /// 6840 /// \param Class The class type of the subobject. 6841 /// \param CSM The kind of special member function. 6842 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6843 /// \param ConstRHS True if this is a copy operation with a const object 6844 /// on its RHS, that is, if the argument to the outer special member 6845 /// function is 'const' and this is not a field marked 'mutable'. 6846 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6847 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6848 unsigned FieldQuals, bool ConstRHS) { 6849 unsigned LHSQuals = 0; 6850 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6851 LHSQuals = FieldQuals; 6852 6853 unsigned RHSQuals = FieldQuals; 6854 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6855 RHSQuals = 0; 6856 else if (ConstRHS) 6857 RHSQuals |= Qualifiers::Const; 6858 6859 return S.LookupSpecialMember(Class, CSM, 6860 RHSQuals & Qualifiers::Const, 6861 RHSQuals & Qualifiers::Volatile, 6862 false, 6863 LHSQuals & Qualifiers::Const, 6864 LHSQuals & Qualifiers::Volatile); 6865 } 6866 6867 class Sema::InheritedConstructorInfo { 6868 Sema &S; 6869 SourceLocation UseLoc; 6870 6871 /// A mapping from the base classes through which the constructor was 6872 /// inherited to the using shadow declaration in that base class (or a null 6873 /// pointer if the constructor was declared in that base class). 6874 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6875 InheritedFromBases; 6876 6877 public: 6878 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6879 ConstructorUsingShadowDecl *Shadow) 6880 : S(S), UseLoc(UseLoc) { 6881 bool DiagnosedMultipleConstructedBases = false; 6882 CXXRecordDecl *ConstructedBase = nullptr; 6883 UsingDecl *ConstructedBaseUsing = nullptr; 6884 6885 // Find the set of such base class subobjects and check that there's a 6886 // unique constructed subobject. 6887 for (auto *D : Shadow->redecls()) { 6888 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6889 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6890 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6891 6892 InheritedFromBases.insert( 6893 std::make_pair(DNominatedBase->getCanonicalDecl(), 6894 DShadow->getNominatedBaseClassShadowDecl())); 6895 if (DShadow->constructsVirtualBase()) 6896 InheritedFromBases.insert( 6897 std::make_pair(DConstructedBase->getCanonicalDecl(), 6898 DShadow->getConstructedBaseClassShadowDecl())); 6899 else 6900 assert(DNominatedBase == DConstructedBase); 6901 6902 // [class.inhctor.init]p2: 6903 // If the constructor was inherited from multiple base class subobjects 6904 // of type B, the program is ill-formed. 6905 if (!ConstructedBase) { 6906 ConstructedBase = DConstructedBase; 6907 ConstructedBaseUsing = D->getUsingDecl(); 6908 } else if (ConstructedBase != DConstructedBase && 6909 !Shadow->isInvalidDecl()) { 6910 if (!DiagnosedMultipleConstructedBases) { 6911 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6912 << Shadow->getTargetDecl(); 6913 S.Diag(ConstructedBaseUsing->getLocation(), 6914 diag::note_ambiguous_inherited_constructor_using) 6915 << ConstructedBase; 6916 DiagnosedMultipleConstructedBases = true; 6917 } 6918 S.Diag(D->getUsingDecl()->getLocation(), 6919 diag::note_ambiguous_inherited_constructor_using) 6920 << DConstructedBase; 6921 } 6922 } 6923 6924 if (DiagnosedMultipleConstructedBases) 6925 Shadow->setInvalidDecl(); 6926 } 6927 6928 /// Find the constructor to use for inherited construction of a base class, 6929 /// and whether that base class constructor inherits the constructor from a 6930 /// virtual base class (in which case it won't actually invoke it). 6931 std::pair<CXXConstructorDecl *, bool> 6932 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6933 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6934 if (It == InheritedFromBases.end()) 6935 return std::make_pair(nullptr, false); 6936 6937 // This is an intermediary class. 6938 if (It->second) 6939 return std::make_pair( 6940 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6941 It->second->constructsVirtualBase()); 6942 6943 // This is the base class from which the constructor was inherited. 6944 return std::make_pair(Ctor, false); 6945 } 6946 }; 6947 6948 /// Is the special member function which would be selected to perform the 6949 /// specified operation on the specified class type a constexpr constructor? 6950 static bool 6951 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6952 Sema::CXXSpecialMember CSM, unsigned Quals, 6953 bool ConstRHS, 6954 CXXConstructorDecl *InheritedCtor = nullptr, 6955 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6956 // If we're inheriting a constructor, see if we need to call it for this base 6957 // class. 6958 if (InheritedCtor) { 6959 assert(CSM == Sema::CXXDefaultConstructor); 6960 auto BaseCtor = 6961 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6962 if (BaseCtor) 6963 return BaseCtor->isConstexpr(); 6964 } 6965 6966 if (CSM == Sema::CXXDefaultConstructor) 6967 return ClassDecl->hasConstexprDefaultConstructor(); 6968 if (CSM == Sema::CXXDestructor) 6969 return ClassDecl->hasConstexprDestructor(); 6970 6971 Sema::SpecialMemberOverloadResult SMOR = 6972 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6973 if (!SMOR.getMethod()) 6974 // A constructor we wouldn't select can't be "involved in initializing" 6975 // anything. 6976 return true; 6977 return SMOR.getMethod()->isConstexpr(); 6978 } 6979 6980 /// Determine whether the specified special member function would be constexpr 6981 /// if it were implicitly defined. 6982 static bool defaultedSpecialMemberIsConstexpr( 6983 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6984 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6985 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6986 if (!S.getLangOpts().CPlusPlus11) 6987 return false; 6988 6989 // C++11 [dcl.constexpr]p4: 6990 // In the definition of a constexpr constructor [...] 6991 bool Ctor = true; 6992 switch (CSM) { 6993 case Sema::CXXDefaultConstructor: 6994 if (Inherited) 6995 break; 6996 // Since default constructor lookup is essentially trivial (and cannot 6997 // involve, for instance, template instantiation), we compute whether a 6998 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6999 // 7000 // This is important for performance; we need to know whether the default 7001 // constructor is constexpr to determine whether the type is a literal type. 7002 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7003 7004 case Sema::CXXCopyConstructor: 7005 case Sema::CXXMoveConstructor: 7006 // For copy or move constructors, we need to perform overload resolution. 7007 break; 7008 7009 case Sema::CXXCopyAssignment: 7010 case Sema::CXXMoveAssignment: 7011 if (!S.getLangOpts().CPlusPlus14) 7012 return false; 7013 // In C++1y, we need to perform overload resolution. 7014 Ctor = false; 7015 break; 7016 7017 case Sema::CXXDestructor: 7018 return ClassDecl->defaultedDestructorIsConstexpr(); 7019 7020 case Sema::CXXInvalid: 7021 return false; 7022 } 7023 7024 // -- if the class is a non-empty union, or for each non-empty anonymous 7025 // union member of a non-union class, exactly one non-static data member 7026 // shall be initialized; [DR1359] 7027 // 7028 // If we squint, this is guaranteed, since exactly one non-static data member 7029 // will be initialized (if the constructor isn't deleted), we just don't know 7030 // which one. 7031 if (Ctor && ClassDecl->isUnion()) 7032 return CSM == Sema::CXXDefaultConstructor 7033 ? ClassDecl->hasInClassInitializer() || 7034 !ClassDecl->hasVariantMembers() 7035 : true; 7036 7037 // -- the class shall not have any virtual base classes; 7038 if (Ctor && ClassDecl->getNumVBases()) 7039 return false; 7040 7041 // C++1y [class.copy]p26: 7042 // -- [the class] is a literal type, and 7043 if (!Ctor && !ClassDecl->isLiteral()) 7044 return false; 7045 7046 // -- every constructor involved in initializing [...] base class 7047 // sub-objects shall be a constexpr constructor; 7048 // -- the assignment operator selected to copy/move each direct base 7049 // class is a constexpr function, and 7050 for (const auto &B : ClassDecl->bases()) { 7051 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7052 if (!BaseType) continue; 7053 7054 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7055 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7056 InheritedCtor, Inherited)) 7057 return false; 7058 } 7059 7060 // -- every constructor involved in initializing non-static data members 7061 // [...] shall be a constexpr constructor; 7062 // -- every non-static data member and base class sub-object shall be 7063 // initialized 7064 // -- for each non-static data member of X that is of class type (or array 7065 // thereof), the assignment operator selected to copy/move that member is 7066 // a constexpr function 7067 for (const auto *F : ClassDecl->fields()) { 7068 if (F->isInvalidDecl()) 7069 continue; 7070 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7071 continue; 7072 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7073 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7074 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7075 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7076 BaseType.getCVRQualifiers(), 7077 ConstArg && !F->isMutable())) 7078 return false; 7079 } else if (CSM == Sema::CXXDefaultConstructor) { 7080 return false; 7081 } 7082 } 7083 7084 // All OK, it's constexpr! 7085 return true; 7086 } 7087 7088 namespace { 7089 /// RAII object to register a defaulted function as having its exception 7090 /// specification computed. 7091 struct ComputingExceptionSpec { 7092 Sema &S; 7093 7094 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7095 : S(S) { 7096 Sema::CodeSynthesisContext Ctx; 7097 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7098 Ctx.PointOfInstantiation = Loc; 7099 Ctx.Entity = FD; 7100 S.pushCodeSynthesisContext(Ctx); 7101 } 7102 ~ComputingExceptionSpec() { 7103 S.popCodeSynthesisContext(); 7104 } 7105 }; 7106 } 7107 7108 static Sema::ImplicitExceptionSpecification 7109 ComputeDefaultedSpecialMemberExceptionSpec( 7110 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7111 Sema::InheritedConstructorInfo *ICI); 7112 7113 static Sema::ImplicitExceptionSpecification 7114 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7115 FunctionDecl *FD, 7116 Sema::DefaultedComparisonKind DCK); 7117 7118 static Sema::ImplicitExceptionSpecification 7119 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7120 auto DFK = S.getDefaultedFunctionKind(FD); 7121 if (DFK.isSpecialMember()) 7122 return ComputeDefaultedSpecialMemberExceptionSpec( 7123 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7124 if (DFK.isComparison()) 7125 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7126 DFK.asComparison()); 7127 7128 auto *CD = cast<CXXConstructorDecl>(FD); 7129 assert(CD->getInheritedConstructor() && 7130 "only defaulted functions and inherited constructors have implicit " 7131 "exception specs"); 7132 Sema::InheritedConstructorInfo ICI( 7133 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7134 return ComputeDefaultedSpecialMemberExceptionSpec( 7135 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7136 } 7137 7138 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7139 CXXMethodDecl *MD) { 7140 FunctionProtoType::ExtProtoInfo EPI; 7141 7142 // Build an exception specification pointing back at this member. 7143 EPI.ExceptionSpec.Type = EST_Unevaluated; 7144 EPI.ExceptionSpec.SourceDecl = MD; 7145 7146 // Set the calling convention to the default for C++ instance methods. 7147 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7148 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7149 /*IsCXXMethod=*/true)); 7150 return EPI; 7151 } 7152 7153 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7154 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7155 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7156 return; 7157 7158 // Evaluate the exception specification. 7159 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7160 auto ESI = IES.getExceptionSpec(); 7161 7162 // Update the type of the special member to use it. 7163 UpdateExceptionSpec(FD, ESI); 7164 } 7165 7166 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7167 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7168 7169 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7170 if (!DefKind) { 7171 assert(FD->getDeclContext()->isDependentContext()); 7172 return; 7173 } 7174 7175 if (DefKind.isSpecialMember() 7176 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7177 DefKind.asSpecialMember()) 7178 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7179 FD->setInvalidDecl(); 7180 } 7181 7182 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7183 CXXSpecialMember CSM) { 7184 CXXRecordDecl *RD = MD->getParent(); 7185 7186 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7187 "not an explicitly-defaulted special member"); 7188 7189 // Defer all checking for special members of a dependent type. 7190 if (RD->isDependentType()) 7191 return false; 7192 7193 // Whether this was the first-declared instance of the constructor. 7194 // This affects whether we implicitly add an exception spec and constexpr. 7195 bool First = MD == MD->getCanonicalDecl(); 7196 7197 bool HadError = false; 7198 7199 // C++11 [dcl.fct.def.default]p1: 7200 // A function that is explicitly defaulted shall 7201 // -- be a special member function [...] (checked elsewhere), 7202 // -- have the same type (except for ref-qualifiers, and except that a 7203 // copy operation can take a non-const reference) as an implicit 7204 // declaration, and 7205 // -- not have default arguments. 7206 // C++2a changes the second bullet to instead delete the function if it's 7207 // defaulted on its first declaration, unless it's "an assignment operator, 7208 // and its return type differs or its parameter type is not a reference". 7209 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7210 bool ShouldDeleteForTypeMismatch = false; 7211 unsigned ExpectedParams = 1; 7212 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7213 ExpectedParams = 0; 7214 if (MD->getNumParams() != ExpectedParams) { 7215 // This checks for default arguments: a copy or move constructor with a 7216 // default argument is classified as a default constructor, and assignment 7217 // operations and destructors can't have default arguments. 7218 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7219 << CSM << MD->getSourceRange(); 7220 HadError = true; 7221 } else if (MD->isVariadic()) { 7222 if (DeleteOnTypeMismatch) 7223 ShouldDeleteForTypeMismatch = true; 7224 else { 7225 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7226 << CSM << MD->getSourceRange(); 7227 HadError = true; 7228 } 7229 } 7230 7231 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7232 7233 bool CanHaveConstParam = false; 7234 if (CSM == CXXCopyConstructor) 7235 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7236 else if (CSM == CXXCopyAssignment) 7237 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7238 7239 QualType ReturnType = Context.VoidTy; 7240 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7241 // Check for return type matching. 7242 ReturnType = Type->getReturnType(); 7243 7244 QualType DeclType = Context.getTypeDeclType(RD); 7245 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7246 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7247 7248 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7249 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7250 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7251 HadError = true; 7252 } 7253 7254 // A defaulted special member cannot have cv-qualifiers. 7255 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7256 if (DeleteOnTypeMismatch) 7257 ShouldDeleteForTypeMismatch = true; 7258 else { 7259 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7260 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7261 HadError = true; 7262 } 7263 } 7264 } 7265 7266 // Check for parameter type matching. 7267 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7268 bool HasConstParam = false; 7269 if (ExpectedParams && ArgType->isReferenceType()) { 7270 // Argument must be reference to possibly-const T. 7271 QualType ReferentType = ArgType->getPointeeType(); 7272 HasConstParam = ReferentType.isConstQualified(); 7273 7274 if (ReferentType.isVolatileQualified()) { 7275 if (DeleteOnTypeMismatch) 7276 ShouldDeleteForTypeMismatch = true; 7277 else { 7278 Diag(MD->getLocation(), 7279 diag::err_defaulted_special_member_volatile_param) << CSM; 7280 HadError = true; 7281 } 7282 } 7283 7284 if (HasConstParam && !CanHaveConstParam) { 7285 if (DeleteOnTypeMismatch) 7286 ShouldDeleteForTypeMismatch = true; 7287 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7288 Diag(MD->getLocation(), 7289 diag::err_defaulted_special_member_copy_const_param) 7290 << (CSM == CXXCopyAssignment); 7291 // FIXME: Explain why this special member can't be const. 7292 HadError = true; 7293 } else { 7294 Diag(MD->getLocation(), 7295 diag::err_defaulted_special_member_move_const_param) 7296 << (CSM == CXXMoveAssignment); 7297 HadError = true; 7298 } 7299 } 7300 } else if (ExpectedParams) { 7301 // A copy assignment operator can take its argument by value, but a 7302 // defaulted one cannot. 7303 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7304 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7305 HadError = true; 7306 } 7307 7308 // C++11 [dcl.fct.def.default]p2: 7309 // An explicitly-defaulted function may be declared constexpr only if it 7310 // would have been implicitly declared as constexpr, 7311 // Do not apply this rule to members of class templates, since core issue 1358 7312 // makes such functions always instantiate to constexpr functions. For 7313 // functions which cannot be constexpr (for non-constructors in C++11 and for 7314 // destructors in C++14 and C++17), this is checked elsewhere. 7315 // 7316 // FIXME: This should not apply if the member is deleted. 7317 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7318 HasConstParam); 7319 if ((getLangOpts().CPlusPlus20 || 7320 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7321 : isa<CXXConstructorDecl>(MD))) && 7322 MD->isConstexpr() && !Constexpr && 7323 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7324 Diag(MD->getBeginLoc(), MD->isConsteval() 7325 ? diag::err_incorrect_defaulted_consteval 7326 : diag::err_incorrect_defaulted_constexpr) 7327 << CSM; 7328 // FIXME: Explain why the special member can't be constexpr. 7329 HadError = true; 7330 } 7331 7332 if (First) { 7333 // C++2a [dcl.fct.def.default]p3: 7334 // If a function is explicitly defaulted on its first declaration, it is 7335 // implicitly considered to be constexpr if the implicit declaration 7336 // would be. 7337 MD->setConstexprKind( 7338 Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr) 7339 : CSK_unspecified); 7340 7341 if (!Type->hasExceptionSpec()) { 7342 // C++2a [except.spec]p3: 7343 // If a declaration of a function does not have a noexcept-specifier 7344 // [and] is defaulted on its first declaration, [...] the exception 7345 // specification is as specified below 7346 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7347 EPI.ExceptionSpec.Type = EST_Unevaluated; 7348 EPI.ExceptionSpec.SourceDecl = MD; 7349 MD->setType(Context.getFunctionType(ReturnType, 7350 llvm::makeArrayRef(&ArgType, 7351 ExpectedParams), 7352 EPI)); 7353 } 7354 } 7355 7356 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7357 if (First) { 7358 SetDeclDeleted(MD, MD->getLocation()); 7359 if (!inTemplateInstantiation() && !HadError) { 7360 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7361 if (ShouldDeleteForTypeMismatch) { 7362 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7363 } else { 7364 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7365 } 7366 } 7367 if (ShouldDeleteForTypeMismatch && !HadError) { 7368 Diag(MD->getLocation(), 7369 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7370 } 7371 } else { 7372 // C++11 [dcl.fct.def.default]p4: 7373 // [For a] user-provided explicitly-defaulted function [...] if such a 7374 // function is implicitly defined as deleted, the program is ill-formed. 7375 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7376 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7377 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7378 HadError = true; 7379 } 7380 } 7381 7382 return HadError; 7383 } 7384 7385 namespace { 7386 /// Helper class for building and checking a defaulted comparison. 7387 /// 7388 /// Defaulted functions are built in two phases: 7389 /// 7390 /// * First, the set of operations that the function will perform are 7391 /// identified, and some of them are checked. If any of the checked 7392 /// operations is invalid in certain ways, the comparison function is 7393 /// defined as deleted and no body is built. 7394 /// * Then, if the function is not defined as deleted, the body is built. 7395 /// 7396 /// This is accomplished by performing two visitation steps over the eventual 7397 /// body of the function. 7398 template<typename Derived, typename ResultList, typename Result, 7399 typename Subobject> 7400 class DefaultedComparisonVisitor { 7401 public: 7402 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7403 7404 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7405 DefaultedComparisonKind DCK) 7406 : S(S), RD(RD), FD(FD), DCK(DCK) { 7407 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7408 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7409 // UnresolvedSet to avoid this copy. 7410 Fns.assign(Info->getUnqualifiedLookups().begin(), 7411 Info->getUnqualifiedLookups().end()); 7412 } 7413 } 7414 7415 ResultList visit() { 7416 // The type of an lvalue naming a parameter of this function. 7417 QualType ParamLvalType = 7418 FD->getParamDecl(0)->getType().getNonReferenceType(); 7419 7420 ResultList Results; 7421 7422 switch (DCK) { 7423 case DefaultedComparisonKind::None: 7424 llvm_unreachable("not a defaulted comparison"); 7425 7426 case DefaultedComparisonKind::Equal: 7427 case DefaultedComparisonKind::ThreeWay: 7428 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7429 return Results; 7430 7431 case DefaultedComparisonKind::NotEqual: 7432 case DefaultedComparisonKind::Relational: 7433 Results.add(getDerived().visitExpandedSubobject( 7434 ParamLvalType, getDerived().getCompleteObject())); 7435 return Results; 7436 } 7437 llvm_unreachable(""); 7438 } 7439 7440 protected: 7441 Derived &getDerived() { return static_cast<Derived&>(*this); } 7442 7443 /// Visit the expanded list of subobjects of the given type, as specified in 7444 /// C++2a [class.compare.default]. 7445 /// 7446 /// \return \c true if the ResultList object said we're done, \c false if not. 7447 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7448 Qualifiers Quals) { 7449 // C++2a [class.compare.default]p4: 7450 // The direct base class subobjects of C 7451 for (CXXBaseSpecifier &Base : Record->bases()) 7452 if (Results.add(getDerived().visitSubobject( 7453 S.Context.getQualifiedType(Base.getType(), Quals), 7454 getDerived().getBase(&Base)))) 7455 return true; 7456 7457 // followed by the non-static data members of C 7458 for (FieldDecl *Field : Record->fields()) { 7459 // Recursively expand anonymous structs. 7460 if (Field->isAnonymousStructOrUnion()) { 7461 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7462 Quals)) 7463 return true; 7464 continue; 7465 } 7466 7467 // Figure out the type of an lvalue denoting this field. 7468 Qualifiers FieldQuals = Quals; 7469 if (Field->isMutable()) 7470 FieldQuals.removeConst(); 7471 QualType FieldType = 7472 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7473 7474 if (Results.add(getDerived().visitSubobject( 7475 FieldType, getDerived().getField(Field)))) 7476 return true; 7477 } 7478 7479 // form a list of subobjects. 7480 return false; 7481 } 7482 7483 Result visitSubobject(QualType Type, Subobject Subobj) { 7484 // In that list, any subobject of array type is recursively expanded 7485 const ArrayType *AT = S.Context.getAsArrayType(Type); 7486 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7487 return getDerived().visitSubobjectArray(CAT->getElementType(), 7488 CAT->getSize(), Subobj); 7489 return getDerived().visitExpandedSubobject(Type, Subobj); 7490 } 7491 7492 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7493 Subobject Subobj) { 7494 return getDerived().visitSubobject(Type, Subobj); 7495 } 7496 7497 protected: 7498 Sema &S; 7499 CXXRecordDecl *RD; 7500 FunctionDecl *FD; 7501 DefaultedComparisonKind DCK; 7502 UnresolvedSet<16> Fns; 7503 }; 7504 7505 /// Information about a defaulted comparison, as determined by 7506 /// DefaultedComparisonAnalyzer. 7507 struct DefaultedComparisonInfo { 7508 bool Deleted = false; 7509 bool Constexpr = true; 7510 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7511 7512 static DefaultedComparisonInfo deleted() { 7513 DefaultedComparisonInfo Deleted; 7514 Deleted.Deleted = true; 7515 return Deleted; 7516 } 7517 7518 bool add(const DefaultedComparisonInfo &R) { 7519 Deleted |= R.Deleted; 7520 Constexpr &= R.Constexpr; 7521 Category = commonComparisonType(Category, R.Category); 7522 return Deleted; 7523 } 7524 }; 7525 7526 /// An element in the expanded list of subobjects of a defaulted comparison, as 7527 /// specified in C++2a [class.compare.default]p4. 7528 struct DefaultedComparisonSubobject { 7529 enum { CompleteObject, Member, Base } Kind; 7530 NamedDecl *Decl; 7531 SourceLocation Loc; 7532 }; 7533 7534 /// A visitor over the notional body of a defaulted comparison that determines 7535 /// whether that body would be deleted or constexpr. 7536 class DefaultedComparisonAnalyzer 7537 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7538 DefaultedComparisonInfo, 7539 DefaultedComparisonInfo, 7540 DefaultedComparisonSubobject> { 7541 public: 7542 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7543 7544 private: 7545 DiagnosticKind Diagnose; 7546 7547 public: 7548 using Base = DefaultedComparisonVisitor; 7549 using Result = DefaultedComparisonInfo; 7550 using Subobject = DefaultedComparisonSubobject; 7551 7552 friend Base; 7553 7554 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7555 DefaultedComparisonKind DCK, 7556 DiagnosticKind Diagnose = NoDiagnostics) 7557 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7558 7559 Result visit() { 7560 if ((DCK == DefaultedComparisonKind::Equal || 7561 DCK == DefaultedComparisonKind::ThreeWay) && 7562 RD->hasVariantMembers()) { 7563 // C++2a [class.compare.default]p2 [P2002R0]: 7564 // A defaulted comparison operator function for class C is defined as 7565 // deleted if [...] C has variant members. 7566 if (Diagnose == ExplainDeleted) { 7567 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7568 << FD << RD->isUnion() << RD; 7569 } 7570 return Result::deleted(); 7571 } 7572 7573 return Base::visit(); 7574 } 7575 7576 private: 7577 Subobject getCompleteObject() { 7578 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7579 } 7580 7581 Subobject getBase(CXXBaseSpecifier *Base) { 7582 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7583 Base->getBaseTypeLoc()}; 7584 } 7585 7586 Subobject getField(FieldDecl *Field) { 7587 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7588 } 7589 7590 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7591 // C++2a [class.compare.default]p2 [P2002R0]: 7592 // A defaulted <=> or == operator function for class C is defined as 7593 // deleted if any non-static data member of C is of reference type 7594 if (Type->isReferenceType()) { 7595 if (Diagnose == ExplainDeleted) { 7596 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7597 << FD << RD; 7598 } 7599 return Result::deleted(); 7600 } 7601 7602 // [...] Let xi be an lvalue denoting the ith element [...] 7603 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7604 Expr *Args[] = {&Xi, &Xi}; 7605 7606 // All operators start by trying to apply that same operator recursively. 7607 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7608 assert(OO != OO_None && "not an overloaded operator!"); 7609 return visitBinaryOperator(OO, Args, Subobj); 7610 } 7611 7612 Result 7613 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7614 Subobject Subobj, 7615 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7616 // Note that there is no need to consider rewritten candidates here if 7617 // we've already found there is no viable 'operator<=>' candidate (and are 7618 // considering synthesizing a '<=>' from '==' and '<'). 7619 OverloadCandidateSet CandidateSet( 7620 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7621 OverloadCandidateSet::OperatorRewriteInfo( 7622 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7623 7624 /// C++2a [class.compare.default]p1 [P2002R0]: 7625 /// [...] the defaulted function itself is never a candidate for overload 7626 /// resolution [...] 7627 CandidateSet.exclude(FD); 7628 7629 if (Args[0]->getType()->isOverloadableType()) 7630 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7631 else { 7632 // FIXME: We determine whether this is a valid expression by checking to 7633 // see if there's a viable builtin operator candidate for it. That isn't 7634 // really what the rules ask us to do, but should give the right results. 7635 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7636 } 7637 7638 Result R; 7639 7640 OverloadCandidateSet::iterator Best; 7641 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7642 case OR_Success: { 7643 // C++2a [class.compare.secondary]p2 [P2002R0]: 7644 // The operator function [...] is defined as deleted if [...] the 7645 // candidate selected by overload resolution is not a rewritten 7646 // candidate. 7647 if ((DCK == DefaultedComparisonKind::NotEqual || 7648 DCK == DefaultedComparisonKind::Relational) && 7649 !Best->RewriteKind) { 7650 if (Diagnose == ExplainDeleted) { 7651 S.Diag(Best->Function->getLocation(), 7652 diag::note_defaulted_comparison_not_rewritten_callee) 7653 << FD; 7654 } 7655 return Result::deleted(); 7656 } 7657 7658 // Throughout C++2a [class.compare]: if overload resolution does not 7659 // result in a usable function, the candidate function is defined as 7660 // deleted. This requires that we selected an accessible function. 7661 // 7662 // Note that this only considers the access of the function when named 7663 // within the type of the subobject, and not the access path for any 7664 // derived-to-base conversion. 7665 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7666 if (ArgClass && Best->FoundDecl.getDecl() && 7667 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7668 QualType ObjectType = Subobj.Kind == Subobject::Member 7669 ? Args[0]->getType() 7670 : S.Context.getRecordType(RD); 7671 if (!S.isMemberAccessibleForDeletion( 7672 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7673 Diagnose == ExplainDeleted 7674 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7675 << FD << Subobj.Kind << Subobj.Decl 7676 : S.PDiag())) 7677 return Result::deleted(); 7678 } 7679 7680 // C++2a [class.compare.default]p3 [P2002R0]: 7681 // A defaulted comparison function is constexpr-compatible if [...] 7682 // no overlod resolution performed [...] results in a non-constexpr 7683 // function. 7684 if (FunctionDecl *BestFD = Best->Function) { 7685 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7686 // If it's not constexpr, explain why not. 7687 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7688 if (Subobj.Kind != Subobject::CompleteObject) 7689 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7690 << Subobj.Kind << Subobj.Decl; 7691 S.Diag(BestFD->getLocation(), 7692 diag::note_defaulted_comparison_not_constexpr_here); 7693 // Bail out after explaining; we don't want any more notes. 7694 return Result::deleted(); 7695 } 7696 R.Constexpr &= BestFD->isConstexpr(); 7697 } 7698 7699 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7700 if (auto *BestFD = Best->Function) { 7701 // If any callee has an undeduced return type, deduce it now. 7702 // FIXME: It's not clear how a failure here should be handled. For 7703 // now, we produce an eager diagnostic, because that is forward 7704 // compatible with most (all?) other reasonable options. 7705 if (BestFD->getReturnType()->isUndeducedType() && 7706 S.DeduceReturnType(BestFD, FD->getLocation(), 7707 /*Diagnose=*/false)) { 7708 // Don't produce a duplicate error when asked to explain why the 7709 // comparison is deleted: we diagnosed that when initially checking 7710 // the defaulted operator. 7711 if (Diagnose == NoDiagnostics) { 7712 S.Diag( 7713 FD->getLocation(), 7714 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7715 << Subobj.Kind << Subobj.Decl; 7716 S.Diag( 7717 Subobj.Loc, 7718 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7719 << Subobj.Kind << Subobj.Decl; 7720 S.Diag(BestFD->getLocation(), 7721 diag::note_defaulted_comparison_cannot_deduce_callee) 7722 << Subobj.Kind << Subobj.Decl; 7723 } 7724 return Result::deleted(); 7725 } 7726 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7727 BestFD->getCallResultType())) { 7728 R.Category = Info->Kind; 7729 } else { 7730 if (Diagnose == ExplainDeleted) { 7731 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7732 << Subobj.Kind << Subobj.Decl 7733 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7734 S.Diag(BestFD->getLocation(), 7735 diag::note_defaulted_comparison_cannot_deduce_callee) 7736 << Subobj.Kind << Subobj.Decl; 7737 } 7738 return Result::deleted(); 7739 } 7740 } else { 7741 Optional<ComparisonCategoryType> Cat = 7742 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7743 assert(Cat && "no category for builtin comparison?"); 7744 R.Category = *Cat; 7745 } 7746 } 7747 7748 // Note that we might be rewriting to a different operator. That call is 7749 // not considered until we come to actually build the comparison function. 7750 break; 7751 } 7752 7753 case OR_Ambiguous: 7754 if (Diagnose == ExplainDeleted) { 7755 unsigned Kind = 0; 7756 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7757 Kind = OO == OO_EqualEqual ? 1 : 2; 7758 CandidateSet.NoteCandidates( 7759 PartialDiagnosticAt( 7760 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7761 << FD << Kind << Subobj.Kind << Subobj.Decl), 7762 S, OCD_AmbiguousCandidates, Args); 7763 } 7764 R = Result::deleted(); 7765 break; 7766 7767 case OR_Deleted: 7768 if (Diagnose == ExplainDeleted) { 7769 if ((DCK == DefaultedComparisonKind::NotEqual || 7770 DCK == DefaultedComparisonKind::Relational) && 7771 !Best->RewriteKind) { 7772 S.Diag(Best->Function->getLocation(), 7773 diag::note_defaulted_comparison_not_rewritten_callee) 7774 << FD; 7775 } else { 7776 S.Diag(Subobj.Loc, 7777 diag::note_defaulted_comparison_calls_deleted) 7778 << FD << Subobj.Kind << Subobj.Decl; 7779 S.NoteDeletedFunction(Best->Function); 7780 } 7781 } 7782 R = Result::deleted(); 7783 break; 7784 7785 case OR_No_Viable_Function: 7786 // If there's no usable candidate, we're done unless we can rewrite a 7787 // '<=>' in terms of '==' and '<'. 7788 if (OO == OO_Spaceship && 7789 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7790 // For any kind of comparison category return type, we need a usable 7791 // '==' and a usable '<'. 7792 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7793 &CandidateSet))) 7794 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7795 break; 7796 } 7797 7798 if (Diagnose == ExplainDeleted) { 7799 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7800 << FD << Subobj.Kind << Subobj.Decl; 7801 7802 // For a three-way comparison, list both the candidates for the 7803 // original operator and the candidates for the synthesized operator. 7804 if (SpaceshipCandidates) { 7805 SpaceshipCandidates->NoteCandidates( 7806 S, Args, 7807 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7808 Args, FD->getLocation())); 7809 S.Diag(Subobj.Loc, 7810 diag::note_defaulted_comparison_no_viable_function_synthesized) 7811 << (OO == OO_EqualEqual ? 0 : 1); 7812 } 7813 7814 CandidateSet.NoteCandidates( 7815 S, Args, 7816 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7817 FD->getLocation())); 7818 } 7819 R = Result::deleted(); 7820 break; 7821 } 7822 7823 return R; 7824 } 7825 }; 7826 7827 /// A list of statements. 7828 struct StmtListResult { 7829 bool IsInvalid = false; 7830 llvm::SmallVector<Stmt*, 16> Stmts; 7831 7832 bool add(const StmtResult &S) { 7833 IsInvalid |= S.isInvalid(); 7834 if (IsInvalid) 7835 return true; 7836 Stmts.push_back(S.get()); 7837 return false; 7838 } 7839 }; 7840 7841 /// A visitor over the notional body of a defaulted comparison that synthesizes 7842 /// the actual body. 7843 class DefaultedComparisonSynthesizer 7844 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7845 StmtListResult, StmtResult, 7846 std::pair<ExprResult, ExprResult>> { 7847 SourceLocation Loc; 7848 unsigned ArrayDepth = 0; 7849 7850 public: 7851 using Base = DefaultedComparisonVisitor; 7852 using ExprPair = std::pair<ExprResult, ExprResult>; 7853 7854 friend Base; 7855 7856 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7857 DefaultedComparisonKind DCK, 7858 SourceLocation BodyLoc) 7859 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7860 7861 /// Build a suitable function body for this defaulted comparison operator. 7862 StmtResult build() { 7863 Sema::CompoundScopeRAII CompoundScope(S); 7864 7865 StmtListResult Stmts = visit(); 7866 if (Stmts.IsInvalid) 7867 return StmtError(); 7868 7869 ExprResult RetVal; 7870 switch (DCK) { 7871 case DefaultedComparisonKind::None: 7872 llvm_unreachable("not a defaulted comparison"); 7873 7874 case DefaultedComparisonKind::Equal: { 7875 // C++2a [class.eq]p3: 7876 // [...] compar[e] the corresponding elements [...] until the first 7877 // index i where xi == yi yields [...] false. If no such index exists, 7878 // V is true. Otherwise, V is false. 7879 // 7880 // Join the comparisons with '&&'s and return the result. Use a right 7881 // fold (traversing the conditions right-to-left), because that 7882 // short-circuits more naturally. 7883 auto OldStmts = std::move(Stmts.Stmts); 7884 Stmts.Stmts.clear(); 7885 ExprResult CmpSoFar; 7886 // Finish a particular comparison chain. 7887 auto FinishCmp = [&] { 7888 if (Expr *Prior = CmpSoFar.get()) { 7889 // Convert the last expression to 'return ...;' 7890 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7891 RetVal = CmpSoFar; 7892 // Convert any prior comparison to 'if (!(...)) return false;' 7893 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7894 return true; 7895 CmpSoFar = ExprResult(); 7896 } 7897 return false; 7898 }; 7899 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7900 Expr *E = dyn_cast<Expr>(EAsStmt); 7901 if (!E) { 7902 // Found an array comparison. 7903 if (FinishCmp() || Stmts.add(EAsStmt)) 7904 return StmtError(); 7905 continue; 7906 } 7907 7908 if (CmpSoFar.isUnset()) { 7909 CmpSoFar = E; 7910 continue; 7911 } 7912 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7913 if (CmpSoFar.isInvalid()) 7914 return StmtError(); 7915 } 7916 if (FinishCmp()) 7917 return StmtError(); 7918 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7919 // If no such index exists, V is true. 7920 if (RetVal.isUnset()) 7921 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7922 break; 7923 } 7924 7925 case DefaultedComparisonKind::ThreeWay: { 7926 // Per C++2a [class.spaceship]p3, as a fallback add: 7927 // return static_cast<R>(std::strong_ordering::equal); 7928 QualType StrongOrdering = S.CheckComparisonCategoryType( 7929 ComparisonCategoryType::StrongOrdering, Loc, 7930 Sema::ComparisonCategoryUsage::DefaultedOperator); 7931 if (StrongOrdering.isNull()) 7932 return StmtError(); 7933 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7934 .getValueInfo(ComparisonCategoryResult::Equal) 7935 ->VD; 7936 RetVal = getDecl(EqualVD); 7937 if (RetVal.isInvalid()) 7938 return StmtError(); 7939 RetVal = buildStaticCastToR(RetVal.get()); 7940 break; 7941 } 7942 7943 case DefaultedComparisonKind::NotEqual: 7944 case DefaultedComparisonKind::Relational: 7945 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 7946 break; 7947 } 7948 7949 // Build the final return statement. 7950 if (RetVal.isInvalid()) 7951 return StmtError(); 7952 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 7953 if (ReturnStmt.isInvalid()) 7954 return StmtError(); 7955 Stmts.Stmts.push_back(ReturnStmt.get()); 7956 7957 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 7958 } 7959 7960 private: 7961 ExprResult getDecl(ValueDecl *VD) { 7962 return S.BuildDeclarationNameExpr( 7963 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 7964 } 7965 7966 ExprResult getParam(unsigned I) { 7967 ParmVarDecl *PD = FD->getParamDecl(I); 7968 return getDecl(PD); 7969 } 7970 7971 ExprPair getCompleteObject() { 7972 unsigned Param = 0; 7973 ExprResult LHS; 7974 if (isa<CXXMethodDecl>(FD)) { 7975 // LHS is '*this'. 7976 LHS = S.ActOnCXXThis(Loc); 7977 if (!LHS.isInvalid()) 7978 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 7979 } else { 7980 LHS = getParam(Param++); 7981 } 7982 ExprResult RHS = getParam(Param++); 7983 assert(Param == FD->getNumParams()); 7984 return {LHS, RHS}; 7985 } 7986 7987 ExprPair getBase(CXXBaseSpecifier *Base) { 7988 ExprPair Obj = getCompleteObject(); 7989 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7990 return {ExprError(), ExprError()}; 7991 CXXCastPath Path = {Base}; 7992 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 7993 CK_DerivedToBase, VK_LValue, &Path), 7994 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 7995 CK_DerivedToBase, VK_LValue, &Path)}; 7996 } 7997 7998 ExprPair getField(FieldDecl *Field) { 7999 ExprPair Obj = getCompleteObject(); 8000 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8001 return {ExprError(), ExprError()}; 8002 8003 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8004 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8005 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8006 CXXScopeSpec(), Field, Found, NameInfo), 8007 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8008 CXXScopeSpec(), Field, Found, NameInfo)}; 8009 } 8010 8011 // FIXME: When expanding a subobject, register a note in the code synthesis 8012 // stack to say which subobject we're comparing. 8013 8014 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8015 if (Cond.isInvalid()) 8016 return StmtError(); 8017 8018 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8019 if (NotCond.isInvalid()) 8020 return StmtError(); 8021 8022 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8023 assert(!False.isInvalid() && "should never fail"); 8024 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8025 if (ReturnFalse.isInvalid()) 8026 return StmtError(); 8027 8028 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8029 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8030 Sema::ConditionKind::Boolean), 8031 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8032 } 8033 8034 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8035 ExprPair Subobj) { 8036 QualType SizeType = S.Context.getSizeType(); 8037 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8038 8039 // Build 'size_t i$n = 0'. 8040 IdentifierInfo *IterationVarName = nullptr; 8041 { 8042 SmallString<8> Str; 8043 llvm::raw_svector_ostream OS(Str); 8044 OS << "i" << ArrayDepth; 8045 IterationVarName = &S.Context.Idents.get(OS.str()); 8046 } 8047 VarDecl *IterationVar = VarDecl::Create( 8048 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8049 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8050 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8051 IterationVar->setInit( 8052 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8053 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8054 8055 auto IterRef = [&] { 8056 ExprResult Ref = S.BuildDeclarationNameExpr( 8057 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8058 IterationVar); 8059 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8060 return Ref.get(); 8061 }; 8062 8063 // Build 'i$n != Size'. 8064 ExprResult Cond = S.CreateBuiltinBinOp( 8065 Loc, BO_NE, IterRef(), 8066 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8067 assert(!Cond.isInvalid() && "should never fail"); 8068 8069 // Build '++i$n'. 8070 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8071 assert(!Inc.isInvalid() && "should never fail"); 8072 8073 // Build 'a[i$n]' and 'b[i$n]'. 8074 auto Index = [&](ExprResult E) { 8075 if (E.isInvalid()) 8076 return ExprError(); 8077 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8078 }; 8079 Subobj.first = Index(Subobj.first); 8080 Subobj.second = Index(Subobj.second); 8081 8082 // Compare the array elements. 8083 ++ArrayDepth; 8084 StmtResult Substmt = visitSubobject(Type, Subobj); 8085 --ArrayDepth; 8086 8087 if (Substmt.isInvalid()) 8088 return StmtError(); 8089 8090 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8091 // For outer levels or for an 'operator<=>' we already have a suitable 8092 // statement that returns as necessary. 8093 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8094 assert(DCK == DefaultedComparisonKind::Equal && 8095 "should have non-expression statement"); 8096 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8097 if (Substmt.isInvalid()) 8098 return StmtError(); 8099 } 8100 8101 // Build 'for (...) ...' 8102 return S.ActOnForStmt(Loc, Loc, Init, 8103 S.ActOnCondition(nullptr, Loc, Cond.get(), 8104 Sema::ConditionKind::Boolean), 8105 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8106 Substmt.get()); 8107 } 8108 8109 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8110 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8111 return StmtError(); 8112 8113 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8114 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8115 ExprResult Op; 8116 if (Type->isOverloadableType()) 8117 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8118 Obj.second.get(), /*PerformADL=*/true, 8119 /*AllowRewrittenCandidates=*/true, FD); 8120 else 8121 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8122 if (Op.isInvalid()) 8123 return StmtError(); 8124 8125 switch (DCK) { 8126 case DefaultedComparisonKind::None: 8127 llvm_unreachable("not a defaulted comparison"); 8128 8129 case DefaultedComparisonKind::Equal: 8130 // Per C++2a [class.eq]p2, each comparison is individually contextually 8131 // converted to bool. 8132 Op = S.PerformContextuallyConvertToBool(Op.get()); 8133 if (Op.isInvalid()) 8134 return StmtError(); 8135 return Op.get(); 8136 8137 case DefaultedComparisonKind::ThreeWay: { 8138 // Per C++2a [class.spaceship]p3, form: 8139 // if (R cmp = static_cast<R>(op); cmp != 0) 8140 // return cmp; 8141 QualType R = FD->getReturnType(); 8142 Op = buildStaticCastToR(Op.get()); 8143 if (Op.isInvalid()) 8144 return StmtError(); 8145 8146 // R cmp = ...; 8147 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8148 VarDecl *VD = 8149 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8150 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8151 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8152 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8153 8154 // cmp != 0 8155 ExprResult VDRef = getDecl(VD); 8156 if (VDRef.isInvalid()) 8157 return StmtError(); 8158 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8159 Expr *Zero = 8160 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8161 ExprResult Comp; 8162 if (VDRef.get()->getType()->isOverloadableType()) 8163 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8164 true, FD); 8165 else 8166 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8167 if (Comp.isInvalid()) 8168 return StmtError(); 8169 Sema::ConditionResult Cond = S.ActOnCondition( 8170 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8171 if (Cond.isInvalid()) 8172 return StmtError(); 8173 8174 // return cmp; 8175 VDRef = getDecl(VD); 8176 if (VDRef.isInvalid()) 8177 return StmtError(); 8178 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8179 if (ReturnStmt.isInvalid()) 8180 return StmtError(); 8181 8182 // if (...) 8183 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8184 ReturnStmt.get(), 8185 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8186 } 8187 8188 case DefaultedComparisonKind::NotEqual: 8189 case DefaultedComparisonKind::Relational: 8190 // C++2a [class.compare.secondary]p2: 8191 // Otherwise, the operator function yields x @ y. 8192 return Op.get(); 8193 } 8194 llvm_unreachable(""); 8195 } 8196 8197 /// Build "static_cast<R>(E)". 8198 ExprResult buildStaticCastToR(Expr *E) { 8199 QualType R = FD->getReturnType(); 8200 assert(!R->isUndeducedType() && "type should have been deduced already"); 8201 8202 // Don't bother forming a no-op cast in the common case. 8203 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8204 return E; 8205 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8206 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8207 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8208 } 8209 }; 8210 } 8211 8212 /// Perform the unqualified lookups that might be needed to form a defaulted 8213 /// comparison function for the given operator. 8214 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8215 UnresolvedSetImpl &Operators, 8216 OverloadedOperatorKind Op) { 8217 auto Lookup = [&](OverloadedOperatorKind OO) { 8218 Self.LookupOverloadedOperatorName(OO, S, Operators); 8219 }; 8220 8221 // Every defaulted operator looks up itself. 8222 Lookup(Op); 8223 // ... and the rewritten form of itself, if any. 8224 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8225 Lookup(ExtraOp); 8226 8227 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8228 // synthesize a three-way comparison from '<' and '=='. In a dependent 8229 // context, we also need to look up '==' in case we implicitly declare a 8230 // defaulted 'operator=='. 8231 if (Op == OO_Spaceship) { 8232 Lookup(OO_ExclaimEqual); 8233 Lookup(OO_Less); 8234 Lookup(OO_EqualEqual); 8235 } 8236 } 8237 8238 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8239 DefaultedComparisonKind DCK) { 8240 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8241 8242 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8243 assert(RD && "defaulted comparison is not defaulted in a class"); 8244 8245 // Perform any unqualified lookups we're going to need to default this 8246 // function. 8247 if (S) { 8248 UnresolvedSet<32> Operators; 8249 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8250 FD->getOverloadedOperator()); 8251 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8252 Context, Operators.pairs())); 8253 } 8254 8255 // C++2a [class.compare.default]p1: 8256 // A defaulted comparison operator function for some class C shall be a 8257 // non-template function declared in the member-specification of C that is 8258 // -- a non-static const member of C having one parameter of type 8259 // const C&, or 8260 // -- a friend of C having two parameters of type const C& or two 8261 // parameters of type C. 8262 QualType ExpectedParmType1 = Context.getRecordType(RD); 8263 QualType ExpectedParmType2 = 8264 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8265 if (isa<CXXMethodDecl>(FD)) 8266 ExpectedParmType1 = ExpectedParmType2; 8267 for (const ParmVarDecl *Param : FD->parameters()) { 8268 if (!Param->getType()->isDependentType() && 8269 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8270 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8271 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8272 // corresponding defaulted 'operator<=>' already. 8273 if (!FD->isImplicit()) { 8274 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8275 << (int)DCK << Param->getType() << ExpectedParmType1 8276 << !isa<CXXMethodDecl>(FD) 8277 << ExpectedParmType2 << Param->getSourceRange(); 8278 } 8279 return true; 8280 } 8281 } 8282 if (FD->getNumParams() == 2 && 8283 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8284 FD->getParamDecl(1)->getType())) { 8285 if (!FD->isImplicit()) { 8286 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8287 << (int)DCK 8288 << FD->getParamDecl(0)->getType() 8289 << FD->getParamDecl(0)->getSourceRange() 8290 << FD->getParamDecl(1)->getType() 8291 << FD->getParamDecl(1)->getSourceRange(); 8292 } 8293 return true; 8294 } 8295 8296 // ... non-static const member ... 8297 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8298 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8299 if (!MD->isConst()) { 8300 SourceLocation InsertLoc; 8301 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8302 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8303 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8304 // corresponding defaulted 'operator<=>' already. 8305 if (!MD->isImplicit()) { 8306 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8307 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8308 } 8309 8310 // Add the 'const' to the type to recover. 8311 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8312 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8313 EPI.TypeQuals.addConst(); 8314 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8315 FPT->getParamTypes(), EPI)); 8316 } 8317 } else { 8318 // A non-member function declared in a class must be a friend. 8319 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8320 } 8321 8322 // C++2a [class.eq]p1, [class.rel]p1: 8323 // A [defaulted comparison other than <=>] shall have a declared return 8324 // type bool. 8325 if (DCK != DefaultedComparisonKind::ThreeWay && 8326 !FD->getDeclaredReturnType()->isDependentType() && 8327 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8328 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8329 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8330 << FD->getReturnTypeSourceRange(); 8331 return true; 8332 } 8333 // C++2a [class.spaceship]p2 [P2002R0]: 8334 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8335 // R shall not contain a placeholder type. 8336 if (DCK == DefaultedComparisonKind::ThreeWay && 8337 FD->getDeclaredReturnType()->getContainedDeducedType() && 8338 !Context.hasSameType(FD->getDeclaredReturnType(), 8339 Context.getAutoDeductType())) { 8340 Diag(FD->getLocation(), 8341 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8342 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8343 << FD->getReturnTypeSourceRange(); 8344 return true; 8345 } 8346 8347 // For a defaulted function in a dependent class, defer all remaining checks 8348 // until instantiation. 8349 if (RD->isDependentType()) 8350 return false; 8351 8352 // Determine whether the function should be defined as deleted. 8353 DefaultedComparisonInfo Info = 8354 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8355 8356 bool First = FD == FD->getCanonicalDecl(); 8357 8358 // If we want to delete the function, then do so; there's nothing else to 8359 // check in that case. 8360 if (Info.Deleted) { 8361 if (!First) { 8362 // C++11 [dcl.fct.def.default]p4: 8363 // [For a] user-provided explicitly-defaulted function [...] if such a 8364 // function is implicitly defined as deleted, the program is ill-formed. 8365 // 8366 // This is really just a consequence of the general rule that you can 8367 // only delete a function on its first declaration. 8368 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8369 << FD->isImplicit() << (int)DCK; 8370 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8371 DefaultedComparisonAnalyzer::ExplainDeleted) 8372 .visit(); 8373 return true; 8374 } 8375 8376 SetDeclDeleted(FD, FD->getLocation()); 8377 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8378 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8379 << (int)DCK; 8380 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8381 DefaultedComparisonAnalyzer::ExplainDeleted) 8382 .visit(); 8383 } 8384 return false; 8385 } 8386 8387 // C++2a [class.spaceship]p2: 8388 // The return type is deduced as the common comparison type of R0, R1, ... 8389 if (DCK == DefaultedComparisonKind::ThreeWay && 8390 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8391 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8392 if (RetLoc.isInvalid()) 8393 RetLoc = FD->getBeginLoc(); 8394 // FIXME: Should we really care whether we have the complete type and the 8395 // 'enumerator' constants here? A forward declaration seems sufficient. 8396 QualType Cat = CheckComparisonCategoryType( 8397 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8398 if (Cat.isNull()) 8399 return true; 8400 Context.adjustDeducedFunctionResultType( 8401 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8402 } 8403 8404 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8405 // An explicitly-defaulted function that is not defined as deleted may be 8406 // declared constexpr or consteval only if it is constexpr-compatible. 8407 // C++2a [class.compare.default]p3 [P2002R0]: 8408 // A defaulted comparison function is constexpr-compatible if it satisfies 8409 // the requirements for a constexpr function [...] 8410 // The only relevant requirements are that the parameter and return types are 8411 // literal types. The remaining conditions are checked by the analyzer. 8412 if (FD->isConstexpr()) { 8413 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8414 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8415 !Info.Constexpr) { 8416 Diag(FD->getBeginLoc(), 8417 diag::err_incorrect_defaulted_comparison_constexpr) 8418 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8419 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8420 DefaultedComparisonAnalyzer::ExplainConstexpr) 8421 .visit(); 8422 } 8423 } 8424 8425 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8426 // If a constexpr-compatible function is explicitly defaulted on its first 8427 // declaration, it is implicitly considered to be constexpr. 8428 // FIXME: Only applying this to the first declaration seems problematic, as 8429 // simple reorderings can affect the meaning of the program. 8430 if (First && !FD->isConstexpr() && Info.Constexpr) 8431 FD->setConstexprKind(CSK_constexpr); 8432 8433 // C++2a [except.spec]p3: 8434 // If a declaration of a function does not have a noexcept-specifier 8435 // [and] is defaulted on its first declaration, [...] the exception 8436 // specification is as specified below 8437 if (FD->getExceptionSpecType() == EST_None) { 8438 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8439 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8440 EPI.ExceptionSpec.Type = EST_Unevaluated; 8441 EPI.ExceptionSpec.SourceDecl = FD; 8442 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8443 FPT->getParamTypes(), EPI)); 8444 } 8445 8446 return false; 8447 } 8448 8449 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8450 FunctionDecl *Spaceship) { 8451 Sema::CodeSynthesisContext Ctx; 8452 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8453 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8454 Ctx.Entity = Spaceship; 8455 pushCodeSynthesisContext(Ctx); 8456 8457 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8458 EqualEqual->setImplicit(); 8459 8460 popCodeSynthesisContext(); 8461 } 8462 8463 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8464 DefaultedComparisonKind DCK) { 8465 assert(FD->isDefaulted() && !FD->isDeleted() && 8466 !FD->doesThisDeclarationHaveABody()); 8467 if (FD->willHaveBody() || FD->isInvalidDecl()) 8468 return; 8469 8470 SynthesizedFunctionScope Scope(*this, FD); 8471 8472 // Add a context note for diagnostics produced after this point. 8473 Scope.addContextNote(UseLoc); 8474 8475 { 8476 // Build and set up the function body. 8477 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8478 SourceLocation BodyLoc = 8479 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8480 StmtResult Body = 8481 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8482 if (Body.isInvalid()) { 8483 FD->setInvalidDecl(); 8484 return; 8485 } 8486 FD->setBody(Body.get()); 8487 FD->markUsed(Context); 8488 } 8489 8490 // The exception specification is needed because we are defining the 8491 // function. Note that this will reuse the body we just built. 8492 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8493 8494 if (ASTMutationListener *L = getASTMutationListener()) 8495 L->CompletedImplicitDefinition(FD); 8496 } 8497 8498 static Sema::ImplicitExceptionSpecification 8499 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8500 FunctionDecl *FD, 8501 Sema::DefaultedComparisonKind DCK) { 8502 ComputingExceptionSpec CES(S, FD, Loc); 8503 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8504 8505 if (FD->isInvalidDecl()) 8506 return ExceptSpec; 8507 8508 // The common case is that we just defined the comparison function. In that 8509 // case, just look at whether the body can throw. 8510 if (FD->hasBody()) { 8511 ExceptSpec.CalledStmt(FD->getBody()); 8512 } else { 8513 // Otherwise, build a body so we can check it. This should ideally only 8514 // happen when we're not actually marking the function referenced. (This is 8515 // only really important for efficiency: we don't want to build and throw 8516 // away bodies for comparison functions more than we strictly need to.) 8517 8518 // Pretend to synthesize the function body in an unevaluated context. 8519 // Note that we can't actually just go ahead and define the function here: 8520 // we are not permitted to mark its callees as referenced. 8521 Sema::SynthesizedFunctionScope Scope(S, FD); 8522 EnterExpressionEvaluationContext Context( 8523 S, Sema::ExpressionEvaluationContext::Unevaluated); 8524 8525 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8526 SourceLocation BodyLoc = 8527 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8528 StmtResult Body = 8529 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8530 if (!Body.isInvalid()) 8531 ExceptSpec.CalledStmt(Body.get()); 8532 8533 // FIXME: Can we hold onto this body and just transform it to potentially 8534 // evaluated when we're asked to define the function rather than rebuilding 8535 // it? Either that, or we should only build the bits of the body that we 8536 // need (the expressions, not the statements). 8537 } 8538 8539 return ExceptSpec; 8540 } 8541 8542 void Sema::CheckDelayedMemberExceptionSpecs() { 8543 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8544 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8545 8546 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8547 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8548 8549 // Perform any deferred checking of exception specifications for virtual 8550 // destructors. 8551 for (auto &Check : Overriding) 8552 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8553 8554 // Perform any deferred checking of exception specifications for befriended 8555 // special members. 8556 for (auto &Check : Equivalent) 8557 CheckEquivalentExceptionSpec(Check.second, Check.first); 8558 } 8559 8560 namespace { 8561 /// CRTP base class for visiting operations performed by a special member 8562 /// function (or inherited constructor). 8563 template<typename Derived> 8564 struct SpecialMemberVisitor { 8565 Sema &S; 8566 CXXMethodDecl *MD; 8567 Sema::CXXSpecialMember CSM; 8568 Sema::InheritedConstructorInfo *ICI; 8569 8570 // Properties of the special member, computed for convenience. 8571 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8572 8573 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8574 Sema::InheritedConstructorInfo *ICI) 8575 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8576 switch (CSM) { 8577 case Sema::CXXDefaultConstructor: 8578 case Sema::CXXCopyConstructor: 8579 case Sema::CXXMoveConstructor: 8580 IsConstructor = true; 8581 break; 8582 case Sema::CXXCopyAssignment: 8583 case Sema::CXXMoveAssignment: 8584 IsAssignment = true; 8585 break; 8586 case Sema::CXXDestructor: 8587 break; 8588 case Sema::CXXInvalid: 8589 llvm_unreachable("invalid special member kind"); 8590 } 8591 8592 if (MD->getNumParams()) { 8593 if (const ReferenceType *RT = 8594 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8595 ConstArg = RT->getPointeeType().isConstQualified(); 8596 } 8597 } 8598 8599 Derived &getDerived() { return static_cast<Derived&>(*this); } 8600 8601 /// Is this a "move" special member? 8602 bool isMove() const { 8603 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8604 } 8605 8606 /// Look up the corresponding special member in the given class. 8607 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8608 unsigned Quals, bool IsMutable) { 8609 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8610 ConstArg && !IsMutable); 8611 } 8612 8613 /// Look up the constructor for the specified base class to see if it's 8614 /// overridden due to this being an inherited constructor. 8615 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8616 if (!ICI) 8617 return {}; 8618 assert(CSM == Sema::CXXDefaultConstructor); 8619 auto *BaseCtor = 8620 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8621 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8622 return MD; 8623 return {}; 8624 } 8625 8626 /// A base or member subobject. 8627 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8628 8629 /// Get the location to use for a subobject in diagnostics. 8630 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8631 // FIXME: For an indirect virtual base, the direct base leading to 8632 // the indirect virtual base would be a more useful choice. 8633 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8634 return B->getBaseTypeLoc(); 8635 else 8636 return Subobj.get<FieldDecl*>()->getLocation(); 8637 } 8638 8639 enum BasesToVisit { 8640 /// Visit all non-virtual (direct) bases. 8641 VisitNonVirtualBases, 8642 /// Visit all direct bases, virtual or not. 8643 VisitDirectBases, 8644 /// Visit all non-virtual bases, and all virtual bases if the class 8645 /// is not abstract. 8646 VisitPotentiallyConstructedBases, 8647 /// Visit all direct or virtual bases. 8648 VisitAllBases 8649 }; 8650 8651 // Visit the bases and members of the class. 8652 bool visit(BasesToVisit Bases) { 8653 CXXRecordDecl *RD = MD->getParent(); 8654 8655 if (Bases == VisitPotentiallyConstructedBases) 8656 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8657 8658 for (auto &B : RD->bases()) 8659 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8660 getDerived().visitBase(&B)) 8661 return true; 8662 8663 if (Bases == VisitAllBases) 8664 for (auto &B : RD->vbases()) 8665 if (getDerived().visitBase(&B)) 8666 return true; 8667 8668 for (auto *F : RD->fields()) 8669 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8670 getDerived().visitField(F)) 8671 return true; 8672 8673 return false; 8674 } 8675 }; 8676 } 8677 8678 namespace { 8679 struct SpecialMemberDeletionInfo 8680 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8681 bool Diagnose; 8682 8683 SourceLocation Loc; 8684 8685 bool AllFieldsAreConst; 8686 8687 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8688 Sema::CXXSpecialMember CSM, 8689 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8690 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8691 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8692 8693 bool inUnion() const { return MD->getParent()->isUnion(); } 8694 8695 Sema::CXXSpecialMember getEffectiveCSM() { 8696 return ICI ? Sema::CXXInvalid : CSM; 8697 } 8698 8699 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8700 8701 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8702 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8703 8704 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8705 bool shouldDeleteForField(FieldDecl *FD); 8706 bool shouldDeleteForAllConstMembers(); 8707 8708 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8709 unsigned Quals); 8710 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8711 Sema::SpecialMemberOverloadResult SMOR, 8712 bool IsDtorCallInCtor); 8713 8714 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8715 }; 8716 } 8717 8718 /// Is the given special member inaccessible when used on the given 8719 /// sub-object. 8720 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8721 CXXMethodDecl *target) { 8722 /// If we're operating on a base class, the object type is the 8723 /// type of this special member. 8724 QualType objectTy; 8725 AccessSpecifier access = target->getAccess(); 8726 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8727 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8728 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8729 8730 // If we're operating on a field, the object type is the type of the field. 8731 } else { 8732 objectTy = S.Context.getTypeDeclType(target->getParent()); 8733 } 8734 8735 return S.isMemberAccessibleForDeletion( 8736 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8737 } 8738 8739 /// Check whether we should delete a special member due to the implicit 8740 /// definition containing a call to a special member of a subobject. 8741 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8742 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8743 bool IsDtorCallInCtor) { 8744 CXXMethodDecl *Decl = SMOR.getMethod(); 8745 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8746 8747 int DiagKind = -1; 8748 8749 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8750 DiagKind = !Decl ? 0 : 1; 8751 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8752 DiagKind = 2; 8753 else if (!isAccessible(Subobj, Decl)) 8754 DiagKind = 3; 8755 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8756 !Decl->isTrivial()) { 8757 // A member of a union must have a trivial corresponding special member. 8758 // As a weird special case, a destructor call from a union's constructor 8759 // must be accessible and non-deleted, but need not be trivial. Such a 8760 // destructor is never actually called, but is semantically checked as 8761 // if it were. 8762 DiagKind = 4; 8763 } 8764 8765 if (DiagKind == -1) 8766 return false; 8767 8768 if (Diagnose) { 8769 if (Field) { 8770 S.Diag(Field->getLocation(), 8771 diag::note_deleted_special_member_class_subobject) 8772 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8773 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8774 } else { 8775 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8776 S.Diag(Base->getBeginLoc(), 8777 diag::note_deleted_special_member_class_subobject) 8778 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8779 << Base->getType() << DiagKind << IsDtorCallInCtor 8780 << /*IsObjCPtr*/false; 8781 } 8782 8783 if (DiagKind == 1) 8784 S.NoteDeletedFunction(Decl); 8785 // FIXME: Explain inaccessibility if DiagKind == 3. 8786 } 8787 8788 return true; 8789 } 8790 8791 /// Check whether we should delete a special member function due to having a 8792 /// direct or virtual base class or non-static data member of class type M. 8793 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8794 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8795 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8796 bool IsMutable = Field && Field->isMutable(); 8797 8798 // C++11 [class.ctor]p5: 8799 // -- any direct or virtual base class, or non-static data member with no 8800 // brace-or-equal-initializer, has class type M (or array thereof) and 8801 // either M has no default constructor or overload resolution as applied 8802 // to M's default constructor results in an ambiguity or in a function 8803 // that is deleted or inaccessible 8804 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8805 // -- a direct or virtual base class B that cannot be copied/moved because 8806 // overload resolution, as applied to B's corresponding special member, 8807 // results in an ambiguity or a function that is deleted or inaccessible 8808 // from the defaulted special member 8809 // C++11 [class.dtor]p5: 8810 // -- any direct or virtual base class [...] has a type with a destructor 8811 // that is deleted or inaccessible 8812 if (!(CSM == Sema::CXXDefaultConstructor && 8813 Field && Field->hasInClassInitializer()) && 8814 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8815 false)) 8816 return true; 8817 8818 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8819 // -- any direct or virtual base class or non-static data member has a 8820 // type with a destructor that is deleted or inaccessible 8821 if (IsConstructor) { 8822 Sema::SpecialMemberOverloadResult SMOR = 8823 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8824 false, false, false, false, false); 8825 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8826 return true; 8827 } 8828 8829 return false; 8830 } 8831 8832 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8833 FieldDecl *FD, QualType FieldType) { 8834 // The defaulted special functions are defined as deleted if this is a variant 8835 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8836 // type under ARC. 8837 if (!FieldType.hasNonTrivialObjCLifetime()) 8838 return false; 8839 8840 // Don't make the defaulted default constructor defined as deleted if the 8841 // member has an in-class initializer. 8842 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8843 return false; 8844 8845 if (Diagnose) { 8846 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8847 S.Diag(FD->getLocation(), 8848 diag::note_deleted_special_member_class_subobject) 8849 << getEffectiveCSM() << ParentClass << /*IsField*/true 8850 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8851 } 8852 8853 return true; 8854 } 8855 8856 /// Check whether we should delete a special member function due to the class 8857 /// having a particular direct or virtual base class. 8858 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8859 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8860 // If program is correct, BaseClass cannot be null, but if it is, the error 8861 // must be reported elsewhere. 8862 if (!BaseClass) 8863 return false; 8864 // If we have an inheriting constructor, check whether we're calling an 8865 // inherited constructor instead of a default constructor. 8866 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8867 if (auto *BaseCtor = SMOR.getMethod()) { 8868 // Note that we do not check access along this path; other than that, 8869 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8870 // FIXME: Check that the base has a usable destructor! Sink this into 8871 // shouldDeleteForClassSubobject. 8872 if (BaseCtor->isDeleted() && Diagnose) { 8873 S.Diag(Base->getBeginLoc(), 8874 diag::note_deleted_special_member_class_subobject) 8875 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8876 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8877 << /*IsObjCPtr*/false; 8878 S.NoteDeletedFunction(BaseCtor); 8879 } 8880 return BaseCtor->isDeleted(); 8881 } 8882 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8883 } 8884 8885 /// Check whether we should delete a special member function due to the class 8886 /// having a particular non-static data member. 8887 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8888 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8889 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8890 8891 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8892 return true; 8893 8894 if (CSM == Sema::CXXDefaultConstructor) { 8895 // For a default constructor, all references must be initialized in-class 8896 // and, if a union, it must have a non-const member. 8897 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8898 if (Diagnose) 8899 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8900 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8901 return true; 8902 } 8903 // C++11 [class.ctor]p5: any non-variant non-static data member of 8904 // const-qualified type (or array thereof) with no 8905 // brace-or-equal-initializer does not have a user-provided default 8906 // constructor. 8907 if (!inUnion() && FieldType.isConstQualified() && 8908 !FD->hasInClassInitializer() && 8909 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8910 if (Diagnose) 8911 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8912 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8913 return true; 8914 } 8915 8916 if (inUnion() && !FieldType.isConstQualified()) 8917 AllFieldsAreConst = false; 8918 } else if (CSM == Sema::CXXCopyConstructor) { 8919 // For a copy constructor, data members must not be of rvalue reference 8920 // type. 8921 if (FieldType->isRValueReferenceType()) { 8922 if (Diagnose) 8923 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8924 << MD->getParent() << FD << FieldType; 8925 return true; 8926 } 8927 } else if (IsAssignment) { 8928 // For an assignment operator, data members must not be of reference type. 8929 if (FieldType->isReferenceType()) { 8930 if (Diagnose) 8931 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8932 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8933 return true; 8934 } 8935 if (!FieldRecord && FieldType.isConstQualified()) { 8936 // C++11 [class.copy]p23: 8937 // -- a non-static data member of const non-class type (or array thereof) 8938 if (Diagnose) 8939 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8940 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8941 return true; 8942 } 8943 } 8944 8945 if (FieldRecord) { 8946 // Some additional restrictions exist on the variant members. 8947 if (!inUnion() && FieldRecord->isUnion() && 8948 FieldRecord->isAnonymousStructOrUnion()) { 8949 bool AllVariantFieldsAreConst = true; 8950 8951 // FIXME: Handle anonymous unions declared within anonymous unions. 8952 for (auto *UI : FieldRecord->fields()) { 8953 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 8954 8955 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 8956 return true; 8957 8958 if (!UnionFieldType.isConstQualified()) 8959 AllVariantFieldsAreConst = false; 8960 8961 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 8962 if (UnionFieldRecord && 8963 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 8964 UnionFieldType.getCVRQualifiers())) 8965 return true; 8966 } 8967 8968 // At least one member in each anonymous union must be non-const 8969 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 8970 !FieldRecord->field_empty()) { 8971 if (Diagnose) 8972 S.Diag(FieldRecord->getLocation(), 8973 diag::note_deleted_default_ctor_all_const) 8974 << !!ICI << MD->getParent() << /*anonymous union*/1; 8975 return true; 8976 } 8977 8978 // Don't check the implicit member of the anonymous union type. 8979 // This is technically non-conformant, but sanity demands it. 8980 return false; 8981 } 8982 8983 if (shouldDeleteForClassSubobject(FieldRecord, FD, 8984 FieldType.getCVRQualifiers())) 8985 return true; 8986 } 8987 8988 return false; 8989 } 8990 8991 /// C++11 [class.ctor] p5: 8992 /// A defaulted default constructor for a class X is defined as deleted if 8993 /// X is a union and all of its variant members are of const-qualified type. 8994 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 8995 // This is a silly definition, because it gives an empty union a deleted 8996 // default constructor. Don't do that. 8997 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 8998 bool AnyFields = false; 8999 for (auto *F : MD->getParent()->fields()) 9000 if ((AnyFields = !F->isUnnamedBitfield())) 9001 break; 9002 if (!AnyFields) 9003 return false; 9004 if (Diagnose) 9005 S.Diag(MD->getParent()->getLocation(), 9006 diag::note_deleted_default_ctor_all_const) 9007 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9008 return true; 9009 } 9010 return false; 9011 } 9012 9013 /// Determine whether a defaulted special member function should be defined as 9014 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9015 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9016 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9017 InheritedConstructorInfo *ICI, 9018 bool Diagnose) { 9019 if (MD->isInvalidDecl()) 9020 return false; 9021 CXXRecordDecl *RD = MD->getParent(); 9022 assert(!RD->isDependentType() && "do deletion after instantiation"); 9023 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9024 return false; 9025 9026 // C++11 [expr.lambda.prim]p19: 9027 // The closure type associated with a lambda-expression has a 9028 // deleted (8.4.3) default constructor and a deleted copy 9029 // assignment operator. 9030 // C++2a adds back these operators if the lambda has no lambda-capture. 9031 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9032 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9033 if (Diagnose) 9034 Diag(RD->getLocation(), diag::note_lambda_decl); 9035 return true; 9036 } 9037 9038 // For an anonymous struct or union, the copy and assignment special members 9039 // will never be used, so skip the check. For an anonymous union declared at 9040 // namespace scope, the constructor and destructor are used. 9041 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9042 RD->isAnonymousStructOrUnion()) 9043 return false; 9044 9045 // C++11 [class.copy]p7, p18: 9046 // If the class definition declares a move constructor or move assignment 9047 // operator, an implicitly declared copy constructor or copy assignment 9048 // operator is defined as deleted. 9049 if (MD->isImplicit() && 9050 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9051 CXXMethodDecl *UserDeclaredMove = nullptr; 9052 9053 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9054 // deletion of the corresponding copy operation, not both copy operations. 9055 // MSVC 2015 has adopted the standards conforming behavior. 9056 bool DeletesOnlyMatchingCopy = 9057 getLangOpts().MSVCCompat && 9058 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9059 9060 if (RD->hasUserDeclaredMoveConstructor() && 9061 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9062 if (!Diagnose) return true; 9063 9064 // Find any user-declared move constructor. 9065 for (auto *I : RD->ctors()) { 9066 if (I->isMoveConstructor()) { 9067 UserDeclaredMove = I; 9068 break; 9069 } 9070 } 9071 assert(UserDeclaredMove); 9072 } else if (RD->hasUserDeclaredMoveAssignment() && 9073 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9074 if (!Diagnose) return true; 9075 9076 // Find any user-declared move assignment operator. 9077 for (auto *I : RD->methods()) { 9078 if (I->isMoveAssignmentOperator()) { 9079 UserDeclaredMove = I; 9080 break; 9081 } 9082 } 9083 assert(UserDeclaredMove); 9084 } 9085 9086 if (UserDeclaredMove) { 9087 Diag(UserDeclaredMove->getLocation(), 9088 diag::note_deleted_copy_user_declared_move) 9089 << (CSM == CXXCopyAssignment) << RD 9090 << UserDeclaredMove->isMoveAssignmentOperator(); 9091 return true; 9092 } 9093 } 9094 9095 // Do access control from the special member function 9096 ContextRAII MethodContext(*this, MD); 9097 9098 // C++11 [class.dtor]p5: 9099 // -- for a virtual destructor, lookup of the non-array deallocation function 9100 // results in an ambiguity or in a function that is deleted or inaccessible 9101 if (CSM == CXXDestructor && MD->isVirtual()) { 9102 FunctionDecl *OperatorDelete = nullptr; 9103 DeclarationName Name = 9104 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9105 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9106 OperatorDelete, /*Diagnose*/false)) { 9107 if (Diagnose) 9108 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9109 return true; 9110 } 9111 } 9112 9113 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9114 9115 // Per DR1611, do not consider virtual bases of constructors of abstract 9116 // classes, since we are not going to construct them. 9117 // Per DR1658, do not consider virtual bases of destructors of abstract 9118 // classes either. 9119 // Per DR2180, for assignment operators we only assign (and thus only 9120 // consider) direct bases. 9121 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9122 : SMI.VisitPotentiallyConstructedBases)) 9123 return true; 9124 9125 if (SMI.shouldDeleteForAllConstMembers()) 9126 return true; 9127 9128 if (getLangOpts().CUDA) { 9129 // We should delete the special member in CUDA mode if target inference 9130 // failed. 9131 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9132 // is treated as certain special member, which may not reflect what special 9133 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9134 // expects CSM to match MD, therefore recalculate CSM. 9135 assert(ICI || CSM == getSpecialMember(MD)); 9136 auto RealCSM = CSM; 9137 if (ICI) 9138 RealCSM = getSpecialMember(MD); 9139 9140 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9141 SMI.ConstArg, Diagnose); 9142 } 9143 9144 return false; 9145 } 9146 9147 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9148 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9149 assert(DFK && "not a defaultable function"); 9150 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9151 9152 if (DFK.isSpecialMember()) { 9153 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9154 nullptr, /*Diagnose=*/true); 9155 } else { 9156 DefaultedComparisonAnalyzer( 9157 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9158 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9159 .visit(); 9160 } 9161 } 9162 9163 /// Perform lookup for a special member of the specified kind, and determine 9164 /// whether it is trivial. If the triviality can be determined without the 9165 /// lookup, skip it. This is intended for use when determining whether a 9166 /// special member of a containing object is trivial, and thus does not ever 9167 /// perform overload resolution for default constructors. 9168 /// 9169 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9170 /// member that was most likely to be intended to be trivial, if any. 9171 /// 9172 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9173 /// determine whether the special member is trivial. 9174 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9175 Sema::CXXSpecialMember CSM, unsigned Quals, 9176 bool ConstRHS, 9177 Sema::TrivialABIHandling TAH, 9178 CXXMethodDecl **Selected) { 9179 if (Selected) 9180 *Selected = nullptr; 9181 9182 switch (CSM) { 9183 case Sema::CXXInvalid: 9184 llvm_unreachable("not a special member"); 9185 9186 case Sema::CXXDefaultConstructor: 9187 // C++11 [class.ctor]p5: 9188 // A default constructor is trivial if: 9189 // - all the [direct subobjects] have trivial default constructors 9190 // 9191 // Note, no overload resolution is performed in this case. 9192 if (RD->hasTrivialDefaultConstructor()) 9193 return true; 9194 9195 if (Selected) { 9196 // If there's a default constructor which could have been trivial, dig it 9197 // out. Otherwise, if there's any user-provided default constructor, point 9198 // to that as an example of why there's not a trivial one. 9199 CXXConstructorDecl *DefCtor = nullptr; 9200 if (RD->needsImplicitDefaultConstructor()) 9201 S.DeclareImplicitDefaultConstructor(RD); 9202 for (auto *CI : RD->ctors()) { 9203 if (!CI->isDefaultConstructor()) 9204 continue; 9205 DefCtor = CI; 9206 if (!DefCtor->isUserProvided()) 9207 break; 9208 } 9209 9210 *Selected = DefCtor; 9211 } 9212 9213 return false; 9214 9215 case Sema::CXXDestructor: 9216 // C++11 [class.dtor]p5: 9217 // A destructor is trivial if: 9218 // - all the direct [subobjects] have trivial destructors 9219 if (RD->hasTrivialDestructor() || 9220 (TAH == Sema::TAH_ConsiderTrivialABI && 9221 RD->hasTrivialDestructorForCall())) 9222 return true; 9223 9224 if (Selected) { 9225 if (RD->needsImplicitDestructor()) 9226 S.DeclareImplicitDestructor(RD); 9227 *Selected = RD->getDestructor(); 9228 } 9229 9230 return false; 9231 9232 case Sema::CXXCopyConstructor: 9233 // C++11 [class.copy]p12: 9234 // A copy constructor is trivial if: 9235 // - the constructor selected to copy each direct [subobject] is trivial 9236 if (RD->hasTrivialCopyConstructor() || 9237 (TAH == Sema::TAH_ConsiderTrivialABI && 9238 RD->hasTrivialCopyConstructorForCall())) { 9239 if (Quals == Qualifiers::Const) 9240 // We must either select the trivial copy constructor or reach an 9241 // ambiguity; no need to actually perform overload resolution. 9242 return true; 9243 } else if (!Selected) { 9244 return false; 9245 } 9246 // In C++98, we are not supposed to perform overload resolution here, but we 9247 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9248 // cases like B as having a non-trivial copy constructor: 9249 // struct A { template<typename T> A(T&); }; 9250 // struct B { mutable A a; }; 9251 goto NeedOverloadResolution; 9252 9253 case Sema::CXXCopyAssignment: 9254 // C++11 [class.copy]p25: 9255 // A copy assignment operator is trivial if: 9256 // - the assignment operator selected to copy each direct [subobject] is 9257 // trivial 9258 if (RD->hasTrivialCopyAssignment()) { 9259 if (Quals == Qualifiers::Const) 9260 return true; 9261 } else if (!Selected) { 9262 return false; 9263 } 9264 // In C++98, we are not supposed to perform overload resolution here, but we 9265 // treat that as a language defect. 9266 goto NeedOverloadResolution; 9267 9268 case Sema::CXXMoveConstructor: 9269 case Sema::CXXMoveAssignment: 9270 NeedOverloadResolution: 9271 Sema::SpecialMemberOverloadResult SMOR = 9272 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9273 9274 // The standard doesn't describe how to behave if the lookup is ambiguous. 9275 // We treat it as not making the member non-trivial, just like the standard 9276 // mandates for the default constructor. This should rarely matter, because 9277 // the member will also be deleted. 9278 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9279 return true; 9280 9281 if (!SMOR.getMethod()) { 9282 assert(SMOR.getKind() == 9283 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9284 return false; 9285 } 9286 9287 // We deliberately don't check if we found a deleted special member. We're 9288 // not supposed to! 9289 if (Selected) 9290 *Selected = SMOR.getMethod(); 9291 9292 if (TAH == Sema::TAH_ConsiderTrivialABI && 9293 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9294 return SMOR.getMethod()->isTrivialForCall(); 9295 return SMOR.getMethod()->isTrivial(); 9296 } 9297 9298 llvm_unreachable("unknown special method kind"); 9299 } 9300 9301 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9302 for (auto *CI : RD->ctors()) 9303 if (!CI->isImplicit()) 9304 return CI; 9305 9306 // Look for constructor templates. 9307 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9308 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9309 if (CXXConstructorDecl *CD = 9310 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9311 return CD; 9312 } 9313 9314 return nullptr; 9315 } 9316 9317 /// The kind of subobject we are checking for triviality. The values of this 9318 /// enumeration are used in diagnostics. 9319 enum TrivialSubobjectKind { 9320 /// The subobject is a base class. 9321 TSK_BaseClass, 9322 /// The subobject is a non-static data member. 9323 TSK_Field, 9324 /// The object is actually the complete object. 9325 TSK_CompleteObject 9326 }; 9327 9328 /// Check whether the special member selected for a given type would be trivial. 9329 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9330 QualType SubType, bool ConstRHS, 9331 Sema::CXXSpecialMember CSM, 9332 TrivialSubobjectKind Kind, 9333 Sema::TrivialABIHandling TAH, bool Diagnose) { 9334 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9335 if (!SubRD) 9336 return true; 9337 9338 CXXMethodDecl *Selected; 9339 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9340 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9341 return true; 9342 9343 if (Diagnose) { 9344 if (ConstRHS) 9345 SubType.addConst(); 9346 9347 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9348 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9349 << Kind << SubType.getUnqualifiedType(); 9350 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9351 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9352 } else if (!Selected) 9353 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9354 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9355 else if (Selected->isUserProvided()) { 9356 if (Kind == TSK_CompleteObject) 9357 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9358 << Kind << SubType.getUnqualifiedType() << CSM; 9359 else { 9360 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9361 << Kind << SubType.getUnqualifiedType() << CSM; 9362 S.Diag(Selected->getLocation(), diag::note_declared_at); 9363 } 9364 } else { 9365 if (Kind != TSK_CompleteObject) 9366 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9367 << Kind << SubType.getUnqualifiedType() << CSM; 9368 9369 // Explain why the defaulted or deleted special member isn't trivial. 9370 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9371 Diagnose); 9372 } 9373 } 9374 9375 return false; 9376 } 9377 9378 /// Check whether the members of a class type allow a special member to be 9379 /// trivial. 9380 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9381 Sema::CXXSpecialMember CSM, 9382 bool ConstArg, 9383 Sema::TrivialABIHandling TAH, 9384 bool Diagnose) { 9385 for (const auto *FI : RD->fields()) { 9386 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9387 continue; 9388 9389 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9390 9391 // Pretend anonymous struct or union members are members of this class. 9392 if (FI->isAnonymousStructOrUnion()) { 9393 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9394 CSM, ConstArg, TAH, Diagnose)) 9395 return false; 9396 continue; 9397 } 9398 9399 // C++11 [class.ctor]p5: 9400 // A default constructor is trivial if [...] 9401 // -- no non-static data member of its class has a 9402 // brace-or-equal-initializer 9403 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9404 if (Diagnose) 9405 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 9406 return false; 9407 } 9408 9409 // Objective C ARC 4.3.5: 9410 // [...] nontrivally ownership-qualified types are [...] not trivially 9411 // default constructible, copy constructible, move constructible, copy 9412 // assignable, move assignable, or destructible [...] 9413 if (FieldType.hasNonTrivialObjCLifetime()) { 9414 if (Diagnose) 9415 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9416 << RD << FieldType.getObjCLifetime(); 9417 return false; 9418 } 9419 9420 bool ConstRHS = ConstArg && !FI->isMutable(); 9421 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9422 CSM, TSK_Field, TAH, Diagnose)) 9423 return false; 9424 } 9425 9426 return true; 9427 } 9428 9429 /// Diagnose why the specified class does not have a trivial special member of 9430 /// the given kind. 9431 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9432 QualType Ty = Context.getRecordType(RD); 9433 9434 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9435 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9436 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9437 /*Diagnose*/true); 9438 } 9439 9440 /// Determine whether a defaulted or deleted special member function is trivial, 9441 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9442 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9443 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9444 TrivialABIHandling TAH, bool Diagnose) { 9445 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9446 9447 CXXRecordDecl *RD = MD->getParent(); 9448 9449 bool ConstArg = false; 9450 9451 // C++11 [class.copy]p12, p25: [DR1593] 9452 // A [special member] is trivial if [...] its parameter-type-list is 9453 // equivalent to the parameter-type-list of an implicit declaration [...] 9454 switch (CSM) { 9455 case CXXDefaultConstructor: 9456 case CXXDestructor: 9457 // Trivial default constructors and destructors cannot have parameters. 9458 break; 9459 9460 case CXXCopyConstructor: 9461 case CXXCopyAssignment: { 9462 // Trivial copy operations always have const, non-volatile parameter types. 9463 ConstArg = true; 9464 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9465 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9466 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9467 if (Diagnose) 9468 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9469 << Param0->getSourceRange() << Param0->getType() 9470 << Context.getLValueReferenceType( 9471 Context.getRecordType(RD).withConst()); 9472 return false; 9473 } 9474 break; 9475 } 9476 9477 case CXXMoveConstructor: 9478 case CXXMoveAssignment: { 9479 // Trivial move operations always have non-cv-qualified parameters. 9480 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9481 const RValueReferenceType *RT = 9482 Param0->getType()->getAs<RValueReferenceType>(); 9483 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9484 if (Diagnose) 9485 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9486 << Param0->getSourceRange() << Param0->getType() 9487 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9488 return false; 9489 } 9490 break; 9491 } 9492 9493 case CXXInvalid: 9494 llvm_unreachable("not a special member"); 9495 } 9496 9497 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9498 if (Diagnose) 9499 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9500 diag::note_nontrivial_default_arg) 9501 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9502 return false; 9503 } 9504 if (MD->isVariadic()) { 9505 if (Diagnose) 9506 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9507 return false; 9508 } 9509 9510 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9511 // A copy/move [constructor or assignment operator] is trivial if 9512 // -- the [member] selected to copy/move each direct base class subobject 9513 // is trivial 9514 // 9515 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9516 // A [default constructor or destructor] is trivial if 9517 // -- all the direct base classes have trivial [default constructors or 9518 // destructors] 9519 for (const auto &BI : RD->bases()) 9520 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9521 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9522 return false; 9523 9524 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9525 // A copy/move [constructor or assignment operator] for a class X is 9526 // trivial if 9527 // -- for each non-static data member of X that is of class type (or array 9528 // thereof), the constructor selected to copy/move that member is 9529 // trivial 9530 // 9531 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9532 // A [default constructor or destructor] is trivial if 9533 // -- for all of the non-static data members of its class that are of class 9534 // type (or array thereof), each such class has a trivial [default 9535 // constructor or destructor] 9536 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9537 return false; 9538 9539 // C++11 [class.dtor]p5: 9540 // A destructor is trivial if [...] 9541 // -- the destructor is not virtual 9542 if (CSM == CXXDestructor && MD->isVirtual()) { 9543 if (Diagnose) 9544 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9545 return false; 9546 } 9547 9548 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9549 // A [special member] for class X is trivial if [...] 9550 // -- class X has no virtual functions and no virtual base classes 9551 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9552 if (!Diagnose) 9553 return false; 9554 9555 if (RD->getNumVBases()) { 9556 // Check for virtual bases. We already know that the corresponding 9557 // member in all bases is trivial, so vbases must all be direct. 9558 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9559 assert(BS.isVirtual()); 9560 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9561 return false; 9562 } 9563 9564 // Must have a virtual method. 9565 for (const auto *MI : RD->methods()) { 9566 if (MI->isVirtual()) { 9567 SourceLocation MLoc = MI->getBeginLoc(); 9568 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9569 return false; 9570 } 9571 } 9572 9573 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9574 } 9575 9576 // Looks like it's trivial! 9577 return true; 9578 } 9579 9580 namespace { 9581 struct FindHiddenVirtualMethod { 9582 Sema *S; 9583 CXXMethodDecl *Method; 9584 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9585 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9586 9587 private: 9588 /// Check whether any most overridden method from MD in Methods 9589 static bool CheckMostOverridenMethods( 9590 const CXXMethodDecl *MD, 9591 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9592 if (MD->size_overridden_methods() == 0) 9593 return Methods.count(MD->getCanonicalDecl()); 9594 for (const CXXMethodDecl *O : MD->overridden_methods()) 9595 if (CheckMostOverridenMethods(O, Methods)) 9596 return true; 9597 return false; 9598 } 9599 9600 public: 9601 /// Member lookup function that determines whether a given C++ 9602 /// method overloads virtual methods in a base class without overriding any, 9603 /// to be used with CXXRecordDecl::lookupInBases(). 9604 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9605 RecordDecl *BaseRecord = 9606 Specifier->getType()->castAs<RecordType>()->getDecl(); 9607 9608 DeclarationName Name = Method->getDeclName(); 9609 assert(Name.getNameKind() == DeclarationName::Identifier); 9610 9611 bool foundSameNameMethod = false; 9612 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9613 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9614 Path.Decls = Path.Decls.slice(1)) { 9615 NamedDecl *D = Path.Decls.front(); 9616 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9617 MD = MD->getCanonicalDecl(); 9618 foundSameNameMethod = true; 9619 // Interested only in hidden virtual methods. 9620 if (!MD->isVirtual()) 9621 continue; 9622 // If the method we are checking overrides a method from its base 9623 // don't warn about the other overloaded methods. Clang deviates from 9624 // GCC by only diagnosing overloads of inherited virtual functions that 9625 // do not override any other virtual functions in the base. GCC's 9626 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9627 // function from a base class. These cases may be better served by a 9628 // warning (not specific to virtual functions) on call sites when the 9629 // call would select a different function from the base class, were it 9630 // visible. 9631 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9632 if (!S->IsOverload(Method, MD, false)) 9633 return true; 9634 // Collect the overload only if its hidden. 9635 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9636 overloadedMethods.push_back(MD); 9637 } 9638 } 9639 9640 if (foundSameNameMethod) 9641 OverloadedMethods.append(overloadedMethods.begin(), 9642 overloadedMethods.end()); 9643 return foundSameNameMethod; 9644 } 9645 }; 9646 } // end anonymous namespace 9647 9648 /// Add the most overriden methods from MD to Methods 9649 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9650 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9651 if (MD->size_overridden_methods() == 0) 9652 Methods.insert(MD->getCanonicalDecl()); 9653 else 9654 for (const CXXMethodDecl *O : MD->overridden_methods()) 9655 AddMostOverridenMethods(O, Methods); 9656 } 9657 9658 /// Check if a method overloads virtual methods in a base class without 9659 /// overriding any. 9660 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9661 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9662 if (!MD->getDeclName().isIdentifier()) 9663 return; 9664 9665 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9666 /*bool RecordPaths=*/false, 9667 /*bool DetectVirtual=*/false); 9668 FindHiddenVirtualMethod FHVM; 9669 FHVM.Method = MD; 9670 FHVM.S = this; 9671 9672 // Keep the base methods that were overridden or introduced in the subclass 9673 // by 'using' in a set. A base method not in this set is hidden. 9674 CXXRecordDecl *DC = MD->getParent(); 9675 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9676 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9677 NamedDecl *ND = *I; 9678 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9679 ND = shad->getTargetDecl(); 9680 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9681 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9682 } 9683 9684 if (DC->lookupInBases(FHVM, Paths)) 9685 OverloadedMethods = FHVM.OverloadedMethods; 9686 } 9687 9688 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9689 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9690 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9691 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9692 PartialDiagnostic PD = PDiag( 9693 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9694 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9695 Diag(overloadedMD->getLocation(), PD); 9696 } 9697 } 9698 9699 /// Diagnose methods which overload virtual methods in a base class 9700 /// without overriding any. 9701 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9702 if (MD->isInvalidDecl()) 9703 return; 9704 9705 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9706 return; 9707 9708 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9709 FindHiddenVirtualMethods(MD, OverloadedMethods); 9710 if (!OverloadedMethods.empty()) { 9711 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9712 << MD << (OverloadedMethods.size() > 1); 9713 9714 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9715 } 9716 } 9717 9718 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9719 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9720 // No diagnostics if this is a template instantiation. 9721 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9722 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9723 diag::ext_cannot_use_trivial_abi) << &RD; 9724 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9725 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9726 } 9727 RD.dropAttr<TrivialABIAttr>(); 9728 }; 9729 9730 // Ill-formed if the copy and move constructors are deleted. 9731 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9732 // If the type is dependent, then assume it might have 9733 // implicit copy or move ctor because we won't know yet at this point. 9734 if (RD.isDependentType()) 9735 return true; 9736 if (RD.needsImplicitCopyConstructor() && 9737 !RD.defaultedCopyConstructorIsDeleted()) 9738 return true; 9739 if (RD.needsImplicitMoveConstructor() && 9740 !RD.defaultedMoveConstructorIsDeleted()) 9741 return true; 9742 for (const CXXConstructorDecl *CD : RD.ctors()) 9743 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9744 return true; 9745 return false; 9746 }; 9747 9748 if (!HasNonDeletedCopyOrMoveConstructor()) { 9749 PrintDiagAndRemoveAttr(0); 9750 return; 9751 } 9752 9753 // Ill-formed if the struct has virtual functions. 9754 if (RD.isPolymorphic()) { 9755 PrintDiagAndRemoveAttr(1); 9756 return; 9757 } 9758 9759 for (const auto &B : RD.bases()) { 9760 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9761 // virtual base. 9762 if (!B.getType()->isDependentType() && 9763 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9764 PrintDiagAndRemoveAttr(2); 9765 return; 9766 } 9767 9768 if (B.isVirtual()) { 9769 PrintDiagAndRemoveAttr(3); 9770 return; 9771 } 9772 } 9773 9774 for (const auto *FD : RD.fields()) { 9775 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9776 // non-trivial for the purpose of calls. 9777 QualType FT = FD->getType(); 9778 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9779 PrintDiagAndRemoveAttr(4); 9780 return; 9781 } 9782 9783 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9784 if (!RT->isDependentType() && 9785 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9786 PrintDiagAndRemoveAttr(5); 9787 return; 9788 } 9789 } 9790 } 9791 9792 void Sema::ActOnFinishCXXMemberSpecification( 9793 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9794 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9795 if (!TagDecl) 9796 return; 9797 9798 AdjustDeclIfTemplate(TagDecl); 9799 9800 for (const ParsedAttr &AL : AttrList) { 9801 if (AL.getKind() != ParsedAttr::AT_Visibility) 9802 continue; 9803 AL.setInvalid(); 9804 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9805 } 9806 9807 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9808 // strict aliasing violation! 9809 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9810 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9811 9812 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9813 } 9814 9815 /// Find the equality comparison functions that should be implicitly declared 9816 /// in a given class definition, per C++2a [class.compare.default]p3. 9817 static void findImplicitlyDeclaredEqualityComparisons( 9818 ASTContext &Ctx, CXXRecordDecl *RD, 9819 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9820 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9821 if (!RD->lookup(EqEq).empty()) 9822 // Member operator== explicitly declared: no implicit operator==s. 9823 return; 9824 9825 // Traverse friends looking for an '==' or a '<=>'. 9826 for (FriendDecl *Friend : RD->friends()) { 9827 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9828 if (!FD) continue; 9829 9830 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9831 // Friend operator== explicitly declared: no implicit operator==s. 9832 Spaceships.clear(); 9833 return; 9834 } 9835 9836 if (FD->getOverloadedOperator() == OO_Spaceship && 9837 FD->isExplicitlyDefaulted()) 9838 Spaceships.push_back(FD); 9839 } 9840 9841 // Look for members named 'operator<=>'. 9842 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9843 for (NamedDecl *ND : RD->lookup(Cmp)) { 9844 // Note that we could find a non-function here (either a function template 9845 // or a using-declaration). Neither case results in an implicit 9846 // 'operator=='. 9847 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9848 if (FD->isExplicitlyDefaulted()) 9849 Spaceships.push_back(FD); 9850 } 9851 } 9852 9853 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9854 /// special functions, such as the default constructor, copy 9855 /// constructor, or destructor, to the given C++ class (C++ 9856 /// [special]p1). This routine can only be executed just before the 9857 /// definition of the class is complete. 9858 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9859 // Don't add implicit special members to templated classes. 9860 // FIXME: This means unqualified lookups for 'operator=' within a class 9861 // template don't work properly. 9862 if (!ClassDecl->isDependentType()) { 9863 if (ClassDecl->needsImplicitDefaultConstructor()) { 9864 ++getASTContext().NumImplicitDefaultConstructors; 9865 9866 if (ClassDecl->hasInheritedConstructor()) 9867 DeclareImplicitDefaultConstructor(ClassDecl); 9868 } 9869 9870 if (ClassDecl->needsImplicitCopyConstructor()) { 9871 ++getASTContext().NumImplicitCopyConstructors; 9872 9873 // If the properties or semantics of the copy constructor couldn't be 9874 // determined while the class was being declared, force a declaration 9875 // of it now. 9876 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9877 ClassDecl->hasInheritedConstructor()) 9878 DeclareImplicitCopyConstructor(ClassDecl); 9879 // For the MS ABI we need to know whether the copy ctor is deleted. A 9880 // prerequisite for deleting the implicit copy ctor is that the class has 9881 // a move ctor or move assignment that is either user-declared or whose 9882 // semantics are inherited from a subobject. FIXME: We should provide a 9883 // more direct way for CodeGen to ask whether the constructor was deleted. 9884 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9885 (ClassDecl->hasUserDeclaredMoveConstructor() || 9886 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9887 ClassDecl->hasUserDeclaredMoveAssignment() || 9888 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9889 DeclareImplicitCopyConstructor(ClassDecl); 9890 } 9891 9892 if (getLangOpts().CPlusPlus11 && 9893 ClassDecl->needsImplicitMoveConstructor()) { 9894 ++getASTContext().NumImplicitMoveConstructors; 9895 9896 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9897 ClassDecl->hasInheritedConstructor()) 9898 DeclareImplicitMoveConstructor(ClassDecl); 9899 } 9900 9901 if (ClassDecl->needsImplicitCopyAssignment()) { 9902 ++getASTContext().NumImplicitCopyAssignmentOperators; 9903 9904 // If we have a dynamic class, then the copy assignment operator may be 9905 // virtual, so we have to declare it immediately. This ensures that, e.g., 9906 // it shows up in the right place in the vtable and that we diagnose 9907 // problems with the implicit exception specification. 9908 if (ClassDecl->isDynamicClass() || 9909 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9910 ClassDecl->hasInheritedAssignment()) 9911 DeclareImplicitCopyAssignment(ClassDecl); 9912 } 9913 9914 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9915 ++getASTContext().NumImplicitMoveAssignmentOperators; 9916 9917 // Likewise for the move assignment operator. 9918 if (ClassDecl->isDynamicClass() || 9919 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9920 ClassDecl->hasInheritedAssignment()) 9921 DeclareImplicitMoveAssignment(ClassDecl); 9922 } 9923 9924 if (ClassDecl->needsImplicitDestructor()) { 9925 ++getASTContext().NumImplicitDestructors; 9926 9927 // If we have a dynamic class, then the destructor may be virtual, so we 9928 // have to declare the destructor immediately. This ensures that, e.g., it 9929 // shows up in the right place in the vtable and that we diagnose problems 9930 // with the implicit exception specification. 9931 if (ClassDecl->isDynamicClass() || 9932 ClassDecl->needsOverloadResolutionForDestructor()) 9933 DeclareImplicitDestructor(ClassDecl); 9934 } 9935 } 9936 9937 // C++2a [class.compare.default]p3: 9938 // If the member-specification does not explicitly declare any member or 9939 // friend named operator==, an == operator function is declared implicitly 9940 // for each defaulted three-way comparison operator function defined in 9941 // the member-specification 9942 // FIXME: Consider doing this lazily. 9943 // We do this during the initial parse for a class template, not during 9944 // instantiation, so that we can handle unqualified lookups for 'operator==' 9945 // when parsing the template. 9946 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 9947 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 9948 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 9949 DefaultedSpaceships); 9950 for (auto *FD : DefaultedSpaceships) 9951 DeclareImplicitEqualityComparison(ClassDecl, FD); 9952 } 9953 } 9954 9955 unsigned 9956 Sema::ActOnReenterTemplateScope(Decl *D, 9957 llvm::function_ref<Scope *()> EnterScope) { 9958 if (!D) 9959 return 0; 9960 AdjustDeclIfTemplate(D); 9961 9962 // In order to get name lookup right, reenter template scopes in order from 9963 // outermost to innermost. 9964 SmallVector<TemplateParameterList *, 4> ParameterLists; 9965 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 9966 9967 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 9968 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 9969 ParameterLists.push_back(DD->getTemplateParameterList(i)); 9970 9971 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9972 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 9973 ParameterLists.push_back(FTD->getTemplateParameters()); 9974 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 9975 LookupDC = VD->getDeclContext(); 9976 9977 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 9978 ParameterLists.push_back(VTD->getTemplateParameters()); 9979 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 9980 ParameterLists.push_back(PSD->getTemplateParameters()); 9981 } 9982 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9983 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 9984 ParameterLists.push_back(TD->getTemplateParameterList(i)); 9985 9986 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 9987 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 9988 ParameterLists.push_back(CTD->getTemplateParameters()); 9989 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 9990 ParameterLists.push_back(PSD->getTemplateParameters()); 9991 } 9992 } 9993 // FIXME: Alias declarations and concepts. 9994 9995 unsigned Count = 0; 9996 Scope *InnermostTemplateScope = nullptr; 9997 for (TemplateParameterList *Params : ParameterLists) { 9998 // Ignore explicit specializations; they don't contribute to the template 9999 // depth. 10000 if (Params->size() == 0) 10001 continue; 10002 10003 InnermostTemplateScope = EnterScope(); 10004 for (NamedDecl *Param : *Params) { 10005 if (Param->getDeclName()) { 10006 InnermostTemplateScope->AddDecl(Param); 10007 IdResolver.AddDecl(Param); 10008 } 10009 } 10010 ++Count; 10011 } 10012 10013 // Associate the new template scopes with the corresponding entities. 10014 if (InnermostTemplateScope) { 10015 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10016 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10017 } 10018 10019 return Count; 10020 } 10021 10022 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10023 if (!RecordD) return; 10024 AdjustDeclIfTemplate(RecordD); 10025 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10026 PushDeclContext(S, Record); 10027 } 10028 10029 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10030 if (!RecordD) return; 10031 PopDeclContext(); 10032 } 10033 10034 /// This is used to implement the constant expression evaluation part of the 10035 /// attribute enable_if extension. There is nothing in standard C++ which would 10036 /// require reentering parameters. 10037 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10038 if (!Param) 10039 return; 10040 10041 S->AddDecl(Param); 10042 if (Param->getDeclName()) 10043 IdResolver.AddDecl(Param); 10044 } 10045 10046 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10047 /// parsing a top-level (non-nested) C++ class, and we are now 10048 /// parsing those parts of the given Method declaration that could 10049 /// not be parsed earlier (C++ [class.mem]p2), such as default 10050 /// arguments. This action should enter the scope of the given 10051 /// Method declaration as if we had just parsed the qualified method 10052 /// name. However, it should not bring the parameters into scope; 10053 /// that will be performed by ActOnDelayedCXXMethodParameter. 10054 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10055 } 10056 10057 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10058 /// C++ method declaration. We're (re-)introducing the given 10059 /// function parameter into scope for use in parsing later parts of 10060 /// the method declaration. For example, we could see an 10061 /// ActOnParamDefaultArgument event for this parameter. 10062 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10063 if (!ParamD) 10064 return; 10065 10066 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10067 10068 S->AddDecl(Param); 10069 if (Param->getDeclName()) 10070 IdResolver.AddDecl(Param); 10071 } 10072 10073 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10074 /// processing the delayed method declaration for Method. The method 10075 /// declaration is now considered finished. There may be a separate 10076 /// ActOnStartOfFunctionDef action later (not necessarily 10077 /// immediately!) for this method, if it was also defined inside the 10078 /// class body. 10079 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10080 if (!MethodD) 10081 return; 10082 10083 AdjustDeclIfTemplate(MethodD); 10084 10085 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10086 10087 // Now that we have our default arguments, check the constructor 10088 // again. It could produce additional diagnostics or affect whether 10089 // the class has implicitly-declared destructors, among other 10090 // things. 10091 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10092 CheckConstructor(Constructor); 10093 10094 // Check the default arguments, which we may have added. 10095 if (!Method->isInvalidDecl()) 10096 CheckCXXDefaultArguments(Method); 10097 } 10098 10099 // Emit the given diagnostic for each non-address-space qualifier. 10100 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10101 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10102 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10103 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10104 bool DiagOccured = false; 10105 FTI.MethodQualifiers->forEachQualifier( 10106 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10107 SourceLocation SL) { 10108 // This diagnostic should be emitted on any qualifier except an addr 10109 // space qualifier. However, forEachQualifier currently doesn't visit 10110 // addr space qualifiers, so there's no way to write this condition 10111 // right now; we just diagnose on everything. 10112 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10113 DiagOccured = true; 10114 }); 10115 if (DiagOccured) 10116 D.setInvalidType(); 10117 } 10118 } 10119 10120 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10121 /// the well-formedness of the constructor declarator @p D with type @p 10122 /// R. If there are any errors in the declarator, this routine will 10123 /// emit diagnostics and set the invalid bit to true. In any case, the type 10124 /// will be updated to reflect a well-formed type for the constructor and 10125 /// returned. 10126 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10127 StorageClass &SC) { 10128 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10129 10130 // C++ [class.ctor]p3: 10131 // A constructor shall not be virtual (10.3) or static (9.4). A 10132 // constructor can be invoked for a const, volatile or const 10133 // volatile object. A constructor shall not be declared const, 10134 // volatile, or const volatile (9.3.2). 10135 if (isVirtual) { 10136 if (!D.isInvalidType()) 10137 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10138 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10139 << SourceRange(D.getIdentifierLoc()); 10140 D.setInvalidType(); 10141 } 10142 if (SC == SC_Static) { 10143 if (!D.isInvalidType()) 10144 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10145 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10146 << SourceRange(D.getIdentifierLoc()); 10147 D.setInvalidType(); 10148 SC = SC_None; 10149 } 10150 10151 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10152 diagnoseIgnoredQualifiers( 10153 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10154 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10155 D.getDeclSpec().getRestrictSpecLoc(), 10156 D.getDeclSpec().getAtomicSpecLoc()); 10157 D.setInvalidType(); 10158 } 10159 10160 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10161 10162 // C++0x [class.ctor]p4: 10163 // A constructor shall not be declared with a ref-qualifier. 10164 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10165 if (FTI.hasRefQualifier()) { 10166 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10167 << FTI.RefQualifierIsLValueRef 10168 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10169 D.setInvalidType(); 10170 } 10171 10172 // Rebuild the function type "R" without any type qualifiers (in 10173 // case any of the errors above fired) and with "void" as the 10174 // return type, since constructors don't have return types. 10175 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10176 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10177 return R; 10178 10179 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10180 EPI.TypeQuals = Qualifiers(); 10181 EPI.RefQualifier = RQ_None; 10182 10183 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10184 } 10185 10186 /// CheckConstructor - Checks a fully-formed constructor for 10187 /// well-formedness, issuing any diagnostics required. Returns true if 10188 /// the constructor declarator is invalid. 10189 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10190 CXXRecordDecl *ClassDecl 10191 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10192 if (!ClassDecl) 10193 return Constructor->setInvalidDecl(); 10194 10195 // C++ [class.copy]p3: 10196 // A declaration of a constructor for a class X is ill-formed if 10197 // its first parameter is of type (optionally cv-qualified) X and 10198 // either there are no other parameters or else all other 10199 // parameters have default arguments. 10200 if (!Constructor->isInvalidDecl() && 10201 Constructor->hasOneParamOrDefaultArgs() && 10202 Constructor->getTemplateSpecializationKind() != 10203 TSK_ImplicitInstantiation) { 10204 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10205 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10206 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10207 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10208 const char *ConstRef 10209 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10210 : " const &"; 10211 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10212 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10213 10214 // FIXME: Rather that making the constructor invalid, we should endeavor 10215 // to fix the type. 10216 Constructor->setInvalidDecl(); 10217 } 10218 } 10219 } 10220 10221 /// CheckDestructor - Checks a fully-formed destructor definition for 10222 /// well-formedness, issuing any diagnostics required. Returns true 10223 /// on error. 10224 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10225 CXXRecordDecl *RD = Destructor->getParent(); 10226 10227 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10228 SourceLocation Loc; 10229 10230 if (!Destructor->isImplicit()) 10231 Loc = Destructor->getLocation(); 10232 else 10233 Loc = RD->getLocation(); 10234 10235 // If we have a virtual destructor, look up the deallocation function 10236 if (FunctionDecl *OperatorDelete = 10237 FindDeallocationFunctionForDestructor(Loc, RD)) { 10238 Expr *ThisArg = nullptr; 10239 10240 // If the notional 'delete this' expression requires a non-trivial 10241 // conversion from 'this' to the type of a destroying operator delete's 10242 // first parameter, perform that conversion now. 10243 if (OperatorDelete->isDestroyingOperatorDelete()) { 10244 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10245 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10246 // C++ [class.dtor]p13: 10247 // ... as if for the expression 'delete this' appearing in a 10248 // non-virtual destructor of the destructor's class. 10249 ContextRAII SwitchContext(*this, Destructor); 10250 ExprResult This = 10251 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10252 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10253 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10254 if (This.isInvalid()) { 10255 // FIXME: Register this as a context note so that it comes out 10256 // in the right order. 10257 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10258 return true; 10259 } 10260 ThisArg = This.get(); 10261 } 10262 } 10263 10264 DiagnoseUseOfDecl(OperatorDelete, Loc); 10265 MarkFunctionReferenced(Loc, OperatorDelete); 10266 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10267 } 10268 } 10269 10270 return false; 10271 } 10272 10273 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10274 /// the well-formednes of the destructor declarator @p D with type @p 10275 /// R. If there are any errors in the declarator, this routine will 10276 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10277 /// will be updated to reflect a well-formed type for the destructor and 10278 /// returned. 10279 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10280 StorageClass& SC) { 10281 // C++ [class.dtor]p1: 10282 // [...] A typedef-name that names a class is a class-name 10283 // (7.1.3); however, a typedef-name that names a class shall not 10284 // be used as the identifier in the declarator for a destructor 10285 // declaration. 10286 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10287 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10288 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10289 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10290 else if (const TemplateSpecializationType *TST = 10291 DeclaratorType->getAs<TemplateSpecializationType>()) 10292 if (TST->isTypeAlias()) 10293 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10294 << DeclaratorType << 1; 10295 10296 // C++ [class.dtor]p2: 10297 // A destructor is used to destroy objects of its class type. A 10298 // destructor takes no parameters, and no return type can be 10299 // specified for it (not even void). The address of a destructor 10300 // shall not be taken. A destructor shall not be static. A 10301 // destructor can be invoked for a const, volatile or const 10302 // volatile object. A destructor shall not be declared const, 10303 // volatile or const volatile (9.3.2). 10304 if (SC == SC_Static) { 10305 if (!D.isInvalidType()) 10306 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10307 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10308 << SourceRange(D.getIdentifierLoc()) 10309 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10310 10311 SC = SC_None; 10312 } 10313 if (!D.isInvalidType()) { 10314 // Destructors don't have return types, but the parser will 10315 // happily parse something like: 10316 // 10317 // class X { 10318 // float ~X(); 10319 // }; 10320 // 10321 // The return type will be eliminated later. 10322 if (D.getDeclSpec().hasTypeSpecifier()) 10323 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10324 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10325 << SourceRange(D.getIdentifierLoc()); 10326 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10327 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10328 SourceLocation(), 10329 D.getDeclSpec().getConstSpecLoc(), 10330 D.getDeclSpec().getVolatileSpecLoc(), 10331 D.getDeclSpec().getRestrictSpecLoc(), 10332 D.getDeclSpec().getAtomicSpecLoc()); 10333 D.setInvalidType(); 10334 } 10335 } 10336 10337 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10338 10339 // C++0x [class.dtor]p2: 10340 // A destructor shall not be declared with a ref-qualifier. 10341 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10342 if (FTI.hasRefQualifier()) { 10343 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10344 << FTI.RefQualifierIsLValueRef 10345 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10346 D.setInvalidType(); 10347 } 10348 10349 // Make sure we don't have any parameters. 10350 if (FTIHasNonVoidParameters(FTI)) { 10351 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10352 10353 // Delete the parameters. 10354 FTI.freeParams(); 10355 D.setInvalidType(); 10356 } 10357 10358 // Make sure the destructor isn't variadic. 10359 if (FTI.isVariadic) { 10360 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10361 D.setInvalidType(); 10362 } 10363 10364 // Rebuild the function type "R" without any type qualifiers or 10365 // parameters (in case any of the errors above fired) and with 10366 // "void" as the return type, since destructors don't have return 10367 // types. 10368 if (!D.isInvalidType()) 10369 return R; 10370 10371 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10372 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10373 EPI.Variadic = false; 10374 EPI.TypeQuals = Qualifiers(); 10375 EPI.RefQualifier = RQ_None; 10376 return Context.getFunctionType(Context.VoidTy, None, EPI); 10377 } 10378 10379 static void extendLeft(SourceRange &R, SourceRange Before) { 10380 if (Before.isInvalid()) 10381 return; 10382 R.setBegin(Before.getBegin()); 10383 if (R.getEnd().isInvalid()) 10384 R.setEnd(Before.getEnd()); 10385 } 10386 10387 static void extendRight(SourceRange &R, SourceRange After) { 10388 if (After.isInvalid()) 10389 return; 10390 if (R.getBegin().isInvalid()) 10391 R.setBegin(After.getBegin()); 10392 R.setEnd(After.getEnd()); 10393 } 10394 10395 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10396 /// well-formednes of the conversion function declarator @p D with 10397 /// type @p R. If there are any errors in the declarator, this routine 10398 /// will emit diagnostics and return true. Otherwise, it will return 10399 /// false. Either way, the type @p R will be updated to reflect a 10400 /// well-formed type for the conversion operator. 10401 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10402 StorageClass& SC) { 10403 // C++ [class.conv.fct]p1: 10404 // Neither parameter types nor return type can be specified. The 10405 // type of a conversion function (8.3.5) is "function taking no 10406 // parameter returning conversion-type-id." 10407 if (SC == SC_Static) { 10408 if (!D.isInvalidType()) 10409 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10410 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10411 << D.getName().getSourceRange(); 10412 D.setInvalidType(); 10413 SC = SC_None; 10414 } 10415 10416 TypeSourceInfo *ConvTSI = nullptr; 10417 QualType ConvType = 10418 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10419 10420 const DeclSpec &DS = D.getDeclSpec(); 10421 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10422 // Conversion functions don't have return types, but the parser will 10423 // happily parse something like: 10424 // 10425 // class X { 10426 // float operator bool(); 10427 // }; 10428 // 10429 // The return type will be changed later anyway. 10430 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10431 << SourceRange(DS.getTypeSpecTypeLoc()) 10432 << SourceRange(D.getIdentifierLoc()); 10433 D.setInvalidType(); 10434 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10435 // It's also plausible that the user writes type qualifiers in the wrong 10436 // place, such as: 10437 // struct S { const operator int(); }; 10438 // FIXME: we could provide a fixit to move the qualifiers onto the 10439 // conversion type. 10440 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10441 << SourceRange(D.getIdentifierLoc()) << 0; 10442 D.setInvalidType(); 10443 } 10444 10445 const auto *Proto = R->castAs<FunctionProtoType>(); 10446 10447 // Make sure we don't have any parameters. 10448 if (Proto->getNumParams() > 0) { 10449 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10450 10451 // Delete the parameters. 10452 D.getFunctionTypeInfo().freeParams(); 10453 D.setInvalidType(); 10454 } else if (Proto->isVariadic()) { 10455 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10456 D.setInvalidType(); 10457 } 10458 10459 // Diagnose "&operator bool()" and other such nonsense. This 10460 // is actually a gcc extension which we don't support. 10461 if (Proto->getReturnType() != ConvType) { 10462 bool NeedsTypedef = false; 10463 SourceRange Before, After; 10464 10465 // Walk the chunks and extract information on them for our diagnostic. 10466 bool PastFunctionChunk = false; 10467 for (auto &Chunk : D.type_objects()) { 10468 switch (Chunk.Kind) { 10469 case DeclaratorChunk::Function: 10470 if (!PastFunctionChunk) { 10471 if (Chunk.Fun.HasTrailingReturnType) { 10472 TypeSourceInfo *TRT = nullptr; 10473 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10474 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10475 } 10476 PastFunctionChunk = true; 10477 break; 10478 } 10479 LLVM_FALLTHROUGH; 10480 case DeclaratorChunk::Array: 10481 NeedsTypedef = true; 10482 extendRight(After, Chunk.getSourceRange()); 10483 break; 10484 10485 case DeclaratorChunk::Pointer: 10486 case DeclaratorChunk::BlockPointer: 10487 case DeclaratorChunk::Reference: 10488 case DeclaratorChunk::MemberPointer: 10489 case DeclaratorChunk::Pipe: 10490 extendLeft(Before, Chunk.getSourceRange()); 10491 break; 10492 10493 case DeclaratorChunk::Paren: 10494 extendLeft(Before, Chunk.Loc); 10495 extendRight(After, Chunk.EndLoc); 10496 break; 10497 } 10498 } 10499 10500 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10501 After.isValid() ? After.getBegin() : 10502 D.getIdentifierLoc(); 10503 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10504 DB << Before << After; 10505 10506 if (!NeedsTypedef) { 10507 DB << /*don't need a typedef*/0; 10508 10509 // If we can provide a correct fix-it hint, do so. 10510 if (After.isInvalid() && ConvTSI) { 10511 SourceLocation InsertLoc = 10512 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10513 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10514 << FixItHint::CreateInsertionFromRange( 10515 InsertLoc, CharSourceRange::getTokenRange(Before)) 10516 << FixItHint::CreateRemoval(Before); 10517 } 10518 } else if (!Proto->getReturnType()->isDependentType()) { 10519 DB << /*typedef*/1 << Proto->getReturnType(); 10520 } else if (getLangOpts().CPlusPlus11) { 10521 DB << /*alias template*/2 << Proto->getReturnType(); 10522 } else { 10523 DB << /*might not be fixable*/3; 10524 } 10525 10526 // Recover by incorporating the other type chunks into the result type. 10527 // Note, this does *not* change the name of the function. This is compatible 10528 // with the GCC extension: 10529 // struct S { &operator int(); } s; 10530 // int &r = s.operator int(); // ok in GCC 10531 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10532 ConvType = Proto->getReturnType(); 10533 } 10534 10535 // C++ [class.conv.fct]p4: 10536 // The conversion-type-id shall not represent a function type nor 10537 // an array type. 10538 if (ConvType->isArrayType()) { 10539 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10540 ConvType = Context.getPointerType(ConvType); 10541 D.setInvalidType(); 10542 } else if (ConvType->isFunctionType()) { 10543 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10544 ConvType = Context.getPointerType(ConvType); 10545 D.setInvalidType(); 10546 } 10547 10548 // Rebuild the function type "R" without any parameters (in case any 10549 // of the errors above fired) and with the conversion type as the 10550 // return type. 10551 if (D.isInvalidType()) 10552 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10553 10554 // C++0x explicit conversion operators. 10555 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10556 Diag(DS.getExplicitSpecLoc(), 10557 getLangOpts().CPlusPlus11 10558 ? diag::warn_cxx98_compat_explicit_conversion_functions 10559 : diag::ext_explicit_conversion_functions) 10560 << SourceRange(DS.getExplicitSpecRange()); 10561 } 10562 10563 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10564 /// the declaration of the given C++ conversion function. This routine 10565 /// is responsible for recording the conversion function in the C++ 10566 /// class, if possible. 10567 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10568 assert(Conversion && "Expected to receive a conversion function declaration"); 10569 10570 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10571 10572 // Make sure we aren't redeclaring the conversion function. 10573 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10574 // C++ [class.conv.fct]p1: 10575 // [...] A conversion function is never used to convert a 10576 // (possibly cv-qualified) object to the (possibly cv-qualified) 10577 // same object type (or a reference to it), to a (possibly 10578 // cv-qualified) base class of that type (or a reference to it), 10579 // or to (possibly cv-qualified) void. 10580 QualType ClassType 10581 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10582 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10583 ConvType = ConvTypeRef->getPointeeType(); 10584 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10585 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10586 /* Suppress diagnostics for instantiations. */; 10587 else if (Conversion->size_overridden_methods() != 0) 10588 /* Suppress diagnostics for overriding virtual function in a base class. */; 10589 else if (ConvType->isRecordType()) { 10590 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10591 if (ConvType == ClassType) 10592 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10593 << ClassType; 10594 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10595 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10596 << ClassType << ConvType; 10597 } else if (ConvType->isVoidType()) { 10598 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10599 << ClassType << ConvType; 10600 } 10601 10602 if (FunctionTemplateDecl *ConversionTemplate 10603 = Conversion->getDescribedFunctionTemplate()) 10604 return ConversionTemplate; 10605 10606 return Conversion; 10607 } 10608 10609 namespace { 10610 /// Utility class to accumulate and print a diagnostic listing the invalid 10611 /// specifier(s) on a declaration. 10612 struct BadSpecifierDiagnoser { 10613 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10614 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10615 ~BadSpecifierDiagnoser() { 10616 Diagnostic << Specifiers; 10617 } 10618 10619 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10620 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10621 } 10622 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10623 return check(SpecLoc, 10624 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10625 } 10626 void check(SourceLocation SpecLoc, const char *Spec) { 10627 if (SpecLoc.isInvalid()) return; 10628 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10629 if (!Specifiers.empty()) Specifiers += " "; 10630 Specifiers += Spec; 10631 } 10632 10633 Sema &S; 10634 Sema::SemaDiagnosticBuilder Diagnostic; 10635 std::string Specifiers; 10636 }; 10637 } 10638 10639 /// Check the validity of a declarator that we parsed for a deduction-guide. 10640 /// These aren't actually declarators in the grammar, so we need to check that 10641 /// the user didn't specify any pieces that are not part of the deduction-guide 10642 /// grammar. 10643 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10644 StorageClass &SC) { 10645 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10646 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10647 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10648 10649 // C++ [temp.deduct.guide]p3: 10650 // A deduction-gide shall be declared in the same scope as the 10651 // corresponding class template. 10652 if (!CurContext->getRedeclContext()->Equals( 10653 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10654 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10655 << GuidedTemplateDecl; 10656 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10657 } 10658 10659 auto &DS = D.getMutableDeclSpec(); 10660 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10661 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10662 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10663 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10664 BadSpecifierDiagnoser Diagnoser( 10665 *this, D.getIdentifierLoc(), 10666 diag::err_deduction_guide_invalid_specifier); 10667 10668 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10669 DS.ClearStorageClassSpecs(); 10670 SC = SC_None; 10671 10672 // 'explicit' is permitted. 10673 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10674 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10675 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10676 DS.ClearConstexprSpec(); 10677 10678 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10679 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10680 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10681 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10682 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10683 DS.ClearTypeQualifiers(); 10684 10685 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10686 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10687 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10688 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10689 DS.ClearTypeSpecType(); 10690 } 10691 10692 if (D.isInvalidType()) 10693 return; 10694 10695 // Check the declarator is simple enough. 10696 bool FoundFunction = false; 10697 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10698 if (Chunk.Kind == DeclaratorChunk::Paren) 10699 continue; 10700 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10701 Diag(D.getDeclSpec().getBeginLoc(), 10702 diag::err_deduction_guide_with_complex_decl) 10703 << D.getSourceRange(); 10704 break; 10705 } 10706 if (!Chunk.Fun.hasTrailingReturnType()) { 10707 Diag(D.getName().getBeginLoc(), 10708 diag::err_deduction_guide_no_trailing_return_type); 10709 break; 10710 } 10711 10712 // Check that the return type is written as a specialization of 10713 // the template specified as the deduction-guide's name. 10714 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10715 TypeSourceInfo *TSI = nullptr; 10716 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10717 assert(TSI && "deduction guide has valid type but invalid return type?"); 10718 bool AcceptableReturnType = false; 10719 bool MightInstantiateToSpecialization = false; 10720 if (auto RetTST = 10721 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10722 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10723 bool TemplateMatches = 10724 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10725 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10726 AcceptableReturnType = true; 10727 else { 10728 // This could still instantiate to the right type, unless we know it 10729 // names the wrong class template. 10730 auto *TD = SpecifiedName.getAsTemplateDecl(); 10731 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10732 !TemplateMatches); 10733 } 10734 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10735 MightInstantiateToSpecialization = true; 10736 } 10737 10738 if (!AcceptableReturnType) { 10739 Diag(TSI->getTypeLoc().getBeginLoc(), 10740 diag::err_deduction_guide_bad_trailing_return_type) 10741 << GuidedTemplate << TSI->getType() 10742 << MightInstantiateToSpecialization 10743 << TSI->getTypeLoc().getSourceRange(); 10744 } 10745 10746 // Keep going to check that we don't have any inner declarator pieces (we 10747 // could still have a function returning a pointer to a function). 10748 FoundFunction = true; 10749 } 10750 10751 if (D.isFunctionDefinition()) 10752 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10753 } 10754 10755 //===----------------------------------------------------------------------===// 10756 // Namespace Handling 10757 //===----------------------------------------------------------------------===// 10758 10759 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10760 /// reopened. 10761 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10762 SourceLocation Loc, 10763 IdentifierInfo *II, bool *IsInline, 10764 NamespaceDecl *PrevNS) { 10765 assert(*IsInline != PrevNS->isInline()); 10766 10767 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10768 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10769 // inline namespaces, with the intention of bringing names into namespace std. 10770 // 10771 // We support this just well enough to get that case working; this is not 10772 // sufficient to support reopening namespaces as inline in general. 10773 if (*IsInline && II && II->getName().startswith("__atomic") && 10774 S.getSourceManager().isInSystemHeader(Loc)) { 10775 // Mark all prior declarations of the namespace as inline. 10776 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10777 NS = NS->getPreviousDecl()) 10778 NS->setInline(*IsInline); 10779 // Patch up the lookup table for the containing namespace. This isn't really 10780 // correct, but it's good enough for this particular case. 10781 for (auto *I : PrevNS->decls()) 10782 if (auto *ND = dyn_cast<NamedDecl>(I)) 10783 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10784 return; 10785 } 10786 10787 if (PrevNS->isInline()) 10788 // The user probably just forgot the 'inline', so suggest that it 10789 // be added back. 10790 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10791 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10792 else 10793 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10794 10795 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10796 *IsInline = PrevNS->isInline(); 10797 } 10798 10799 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10800 /// definition. 10801 Decl *Sema::ActOnStartNamespaceDef( 10802 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10803 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10804 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10805 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10806 // For anonymous namespace, take the location of the left brace. 10807 SourceLocation Loc = II ? IdentLoc : LBrace; 10808 bool IsInline = InlineLoc.isValid(); 10809 bool IsInvalid = false; 10810 bool IsStd = false; 10811 bool AddToKnown = false; 10812 Scope *DeclRegionScope = NamespcScope->getParent(); 10813 10814 NamespaceDecl *PrevNS = nullptr; 10815 if (II) { 10816 // C++ [namespace.def]p2: 10817 // The identifier in an original-namespace-definition shall not 10818 // have been previously defined in the declarative region in 10819 // which the original-namespace-definition appears. The 10820 // identifier in an original-namespace-definition is the name of 10821 // the namespace. Subsequently in that declarative region, it is 10822 // treated as an original-namespace-name. 10823 // 10824 // Since namespace names are unique in their scope, and we don't 10825 // look through using directives, just look for any ordinary names 10826 // as if by qualified name lookup. 10827 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10828 ForExternalRedeclaration); 10829 LookupQualifiedName(R, CurContext->getRedeclContext()); 10830 NamedDecl *PrevDecl = 10831 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10832 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10833 10834 if (PrevNS) { 10835 // This is an extended namespace definition. 10836 if (IsInline != PrevNS->isInline()) 10837 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10838 &IsInline, PrevNS); 10839 } else if (PrevDecl) { 10840 // This is an invalid name redefinition. 10841 Diag(Loc, diag::err_redefinition_different_kind) 10842 << II; 10843 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10844 IsInvalid = true; 10845 // Continue on to push Namespc as current DeclContext and return it. 10846 } else if (II->isStr("std") && 10847 CurContext->getRedeclContext()->isTranslationUnit()) { 10848 // This is the first "real" definition of the namespace "std", so update 10849 // our cache of the "std" namespace to point at this definition. 10850 PrevNS = getStdNamespace(); 10851 IsStd = true; 10852 AddToKnown = !IsInline; 10853 } else { 10854 // We've seen this namespace for the first time. 10855 AddToKnown = !IsInline; 10856 } 10857 } else { 10858 // Anonymous namespaces. 10859 10860 // Determine whether the parent already has an anonymous namespace. 10861 DeclContext *Parent = CurContext->getRedeclContext(); 10862 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10863 PrevNS = TU->getAnonymousNamespace(); 10864 } else { 10865 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10866 PrevNS = ND->getAnonymousNamespace(); 10867 } 10868 10869 if (PrevNS && IsInline != PrevNS->isInline()) 10870 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10871 &IsInline, PrevNS); 10872 } 10873 10874 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10875 StartLoc, Loc, II, PrevNS); 10876 if (IsInvalid) 10877 Namespc->setInvalidDecl(); 10878 10879 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10880 AddPragmaAttributes(DeclRegionScope, Namespc); 10881 10882 // FIXME: Should we be merging attributes? 10883 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10884 PushNamespaceVisibilityAttr(Attr, Loc); 10885 10886 if (IsStd) 10887 StdNamespace = Namespc; 10888 if (AddToKnown) 10889 KnownNamespaces[Namespc] = false; 10890 10891 if (II) { 10892 PushOnScopeChains(Namespc, DeclRegionScope); 10893 } else { 10894 // Link the anonymous namespace into its parent. 10895 DeclContext *Parent = CurContext->getRedeclContext(); 10896 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10897 TU->setAnonymousNamespace(Namespc); 10898 } else { 10899 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10900 } 10901 10902 CurContext->addDecl(Namespc); 10903 10904 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10905 // behaves as if it were replaced by 10906 // namespace unique { /* empty body */ } 10907 // using namespace unique; 10908 // namespace unique { namespace-body } 10909 // where all occurrences of 'unique' in a translation unit are 10910 // replaced by the same identifier and this identifier differs 10911 // from all other identifiers in the entire program. 10912 10913 // We just create the namespace with an empty name and then add an 10914 // implicit using declaration, just like the standard suggests. 10915 // 10916 // CodeGen enforces the "universally unique" aspect by giving all 10917 // declarations semantically contained within an anonymous 10918 // namespace internal linkage. 10919 10920 if (!PrevNS) { 10921 UD = UsingDirectiveDecl::Create(Context, Parent, 10922 /* 'using' */ LBrace, 10923 /* 'namespace' */ SourceLocation(), 10924 /* qualifier */ NestedNameSpecifierLoc(), 10925 /* identifier */ SourceLocation(), 10926 Namespc, 10927 /* Ancestor */ Parent); 10928 UD->setImplicit(); 10929 Parent->addDecl(UD); 10930 } 10931 } 10932 10933 ActOnDocumentableDecl(Namespc); 10934 10935 // Although we could have an invalid decl (i.e. the namespace name is a 10936 // redefinition), push it as current DeclContext and try to continue parsing. 10937 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10938 // for the namespace has the declarations that showed up in that particular 10939 // namespace definition. 10940 PushDeclContext(NamespcScope, Namespc); 10941 return Namespc; 10942 } 10943 10944 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 10945 /// is a namespace alias, returns the namespace it points to. 10946 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 10947 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 10948 return AD->getNamespace(); 10949 return dyn_cast_or_null<NamespaceDecl>(D); 10950 } 10951 10952 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 10953 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 10954 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 10955 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 10956 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 10957 Namespc->setRBraceLoc(RBrace); 10958 PopDeclContext(); 10959 if (Namespc->hasAttr<VisibilityAttr>()) 10960 PopPragmaVisibility(true, RBrace); 10961 // If this namespace contains an export-declaration, export it now. 10962 if (DeferredExportedNamespaces.erase(Namespc)) 10963 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 10964 } 10965 10966 CXXRecordDecl *Sema::getStdBadAlloc() const { 10967 return cast_or_null<CXXRecordDecl>( 10968 StdBadAlloc.get(Context.getExternalSource())); 10969 } 10970 10971 EnumDecl *Sema::getStdAlignValT() const { 10972 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 10973 } 10974 10975 NamespaceDecl *Sema::getStdNamespace() const { 10976 return cast_or_null<NamespaceDecl>( 10977 StdNamespace.get(Context.getExternalSource())); 10978 } 10979 10980 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 10981 if (!StdExperimentalNamespaceCache) { 10982 if (auto Std = getStdNamespace()) { 10983 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 10984 SourceLocation(), LookupNamespaceName); 10985 if (!LookupQualifiedName(Result, Std) || 10986 !(StdExperimentalNamespaceCache = 10987 Result.getAsSingle<NamespaceDecl>())) 10988 Result.suppressDiagnostics(); 10989 } 10990 } 10991 return StdExperimentalNamespaceCache; 10992 } 10993 10994 namespace { 10995 10996 enum UnsupportedSTLSelect { 10997 USS_InvalidMember, 10998 USS_MissingMember, 10999 USS_NonTrivial, 11000 USS_Other 11001 }; 11002 11003 struct InvalidSTLDiagnoser { 11004 Sema &S; 11005 SourceLocation Loc; 11006 QualType TyForDiags; 11007 11008 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11009 const VarDecl *VD = nullptr) { 11010 { 11011 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11012 << TyForDiags << ((int)Sel); 11013 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11014 assert(!Name.empty()); 11015 D << Name; 11016 } 11017 } 11018 if (Sel == USS_InvalidMember) { 11019 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11020 << VD << VD->getSourceRange(); 11021 } 11022 return QualType(); 11023 } 11024 }; 11025 } // namespace 11026 11027 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11028 SourceLocation Loc, 11029 ComparisonCategoryUsage Usage) { 11030 assert(getLangOpts().CPlusPlus && 11031 "Looking for comparison category type outside of C++."); 11032 11033 // Use an elaborated type for diagnostics which has a name containing the 11034 // prepended 'std' namespace but not any inline namespace names. 11035 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11036 auto *NNS = 11037 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11038 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11039 }; 11040 11041 // Check if we've already successfully checked the comparison category type 11042 // before. If so, skip checking it again. 11043 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11044 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11045 // The only thing we need to check is that the type has a reachable 11046 // definition in the current context. 11047 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11048 return QualType(); 11049 11050 return Info->getType(); 11051 } 11052 11053 // If lookup failed 11054 if (!Info) { 11055 std::string NameForDiags = "std::"; 11056 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11057 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11058 << NameForDiags << (int)Usage; 11059 return QualType(); 11060 } 11061 11062 assert(Info->Kind == Kind); 11063 assert(Info->Record); 11064 11065 // Update the Record decl in case we encountered a forward declaration on our 11066 // first pass. FIXME: This is a bit of a hack. 11067 if (Info->Record->hasDefinition()) 11068 Info->Record = Info->Record->getDefinition(); 11069 11070 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11071 return QualType(); 11072 11073 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11074 11075 if (!Info->Record->isTriviallyCopyable()) 11076 return UnsupportedSTLError(USS_NonTrivial); 11077 11078 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11079 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11080 // Tolerate empty base classes. 11081 if (Base->isEmpty()) 11082 continue; 11083 // Reject STL implementations which have at least one non-empty base. 11084 return UnsupportedSTLError(); 11085 } 11086 11087 // Check that the STL has implemented the types using a single integer field. 11088 // This expectation allows better codegen for builtin operators. We require: 11089 // (1) The class has exactly one field. 11090 // (2) The field is an integral or enumeration type. 11091 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11092 if (std::distance(FIt, FEnd) != 1 || 11093 !FIt->getType()->isIntegralOrEnumerationType()) { 11094 return UnsupportedSTLError(); 11095 } 11096 11097 // Build each of the require values and store them in Info. 11098 for (ComparisonCategoryResult CCR : 11099 ComparisonCategories::getPossibleResultsForType(Kind)) { 11100 StringRef MemName = ComparisonCategories::getResultString(CCR); 11101 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11102 11103 if (!ValInfo) 11104 return UnsupportedSTLError(USS_MissingMember, MemName); 11105 11106 VarDecl *VD = ValInfo->VD; 11107 assert(VD && "should not be null!"); 11108 11109 // Attempt to diagnose reasons why the STL definition of this type 11110 // might be foobar, including it failing to be a constant expression. 11111 // TODO Handle more ways the lookup or result can be invalid. 11112 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 11113 !VD->checkInitIsICE()) 11114 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11115 11116 // Attempt to evaluate the var decl as a constant expression and extract 11117 // the value of its first field as a ICE. If this fails, the STL 11118 // implementation is not supported. 11119 if (!ValInfo->hasValidIntValue()) 11120 return UnsupportedSTLError(); 11121 11122 MarkVariableReferenced(Loc, VD); 11123 } 11124 11125 // We've successfully built the required types and expressions. Update 11126 // the cache and return the newly cached value. 11127 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11128 return Info->getType(); 11129 } 11130 11131 /// Retrieve the special "std" namespace, which may require us to 11132 /// implicitly define the namespace. 11133 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11134 if (!StdNamespace) { 11135 // The "std" namespace has not yet been defined, so build one implicitly. 11136 StdNamespace = NamespaceDecl::Create(Context, 11137 Context.getTranslationUnitDecl(), 11138 /*Inline=*/false, 11139 SourceLocation(), SourceLocation(), 11140 &PP.getIdentifierTable().get("std"), 11141 /*PrevDecl=*/nullptr); 11142 getStdNamespace()->setImplicit(true); 11143 } 11144 11145 return getStdNamespace(); 11146 } 11147 11148 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11149 assert(getLangOpts().CPlusPlus && 11150 "Looking for std::initializer_list outside of C++."); 11151 11152 // We're looking for implicit instantiations of 11153 // template <typename E> class std::initializer_list. 11154 11155 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11156 return false; 11157 11158 ClassTemplateDecl *Template = nullptr; 11159 const TemplateArgument *Arguments = nullptr; 11160 11161 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11162 11163 ClassTemplateSpecializationDecl *Specialization = 11164 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11165 if (!Specialization) 11166 return false; 11167 11168 Template = Specialization->getSpecializedTemplate(); 11169 Arguments = Specialization->getTemplateArgs().data(); 11170 } else if (const TemplateSpecializationType *TST = 11171 Ty->getAs<TemplateSpecializationType>()) { 11172 Template = dyn_cast_or_null<ClassTemplateDecl>( 11173 TST->getTemplateName().getAsTemplateDecl()); 11174 Arguments = TST->getArgs(); 11175 } 11176 if (!Template) 11177 return false; 11178 11179 if (!StdInitializerList) { 11180 // Haven't recognized std::initializer_list yet, maybe this is it. 11181 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11182 if (TemplateClass->getIdentifier() != 11183 &PP.getIdentifierTable().get("initializer_list") || 11184 !getStdNamespace()->InEnclosingNamespaceSetOf( 11185 TemplateClass->getDeclContext())) 11186 return false; 11187 // This is a template called std::initializer_list, but is it the right 11188 // template? 11189 TemplateParameterList *Params = Template->getTemplateParameters(); 11190 if (Params->getMinRequiredArguments() != 1) 11191 return false; 11192 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11193 return false; 11194 11195 // It's the right template. 11196 StdInitializerList = Template; 11197 } 11198 11199 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11200 return false; 11201 11202 // This is an instance of std::initializer_list. Find the argument type. 11203 if (Element) 11204 *Element = Arguments[0].getAsType(); 11205 return true; 11206 } 11207 11208 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11209 NamespaceDecl *Std = S.getStdNamespace(); 11210 if (!Std) { 11211 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11212 return nullptr; 11213 } 11214 11215 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11216 Loc, Sema::LookupOrdinaryName); 11217 if (!S.LookupQualifiedName(Result, Std)) { 11218 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11219 return nullptr; 11220 } 11221 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11222 if (!Template) { 11223 Result.suppressDiagnostics(); 11224 // We found something weird. Complain about the first thing we found. 11225 NamedDecl *Found = *Result.begin(); 11226 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11227 return nullptr; 11228 } 11229 11230 // We found some template called std::initializer_list. Now verify that it's 11231 // correct. 11232 TemplateParameterList *Params = Template->getTemplateParameters(); 11233 if (Params->getMinRequiredArguments() != 1 || 11234 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11235 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11236 return nullptr; 11237 } 11238 11239 return Template; 11240 } 11241 11242 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11243 if (!StdInitializerList) { 11244 StdInitializerList = LookupStdInitializerList(*this, Loc); 11245 if (!StdInitializerList) 11246 return QualType(); 11247 } 11248 11249 TemplateArgumentListInfo Args(Loc, Loc); 11250 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11251 Context.getTrivialTypeSourceInfo(Element, 11252 Loc))); 11253 return Context.getCanonicalType( 11254 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11255 } 11256 11257 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11258 // C++ [dcl.init.list]p2: 11259 // A constructor is an initializer-list constructor if its first parameter 11260 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11261 // std::initializer_list<E> for some type E, and either there are no other 11262 // parameters or else all other parameters have default arguments. 11263 if (!Ctor->hasOneParamOrDefaultArgs()) 11264 return false; 11265 11266 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11267 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11268 ArgType = RT->getPointeeType().getUnqualifiedType(); 11269 11270 return isStdInitializerList(ArgType, nullptr); 11271 } 11272 11273 /// Determine whether a using statement is in a context where it will be 11274 /// apply in all contexts. 11275 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11276 switch (CurContext->getDeclKind()) { 11277 case Decl::TranslationUnit: 11278 return true; 11279 case Decl::LinkageSpec: 11280 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11281 default: 11282 return false; 11283 } 11284 } 11285 11286 namespace { 11287 11288 // Callback to only accept typo corrections that are namespaces. 11289 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11290 public: 11291 bool ValidateCandidate(const TypoCorrection &candidate) override { 11292 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11293 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11294 return false; 11295 } 11296 11297 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11298 return std::make_unique<NamespaceValidatorCCC>(*this); 11299 } 11300 }; 11301 11302 } 11303 11304 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11305 CXXScopeSpec &SS, 11306 SourceLocation IdentLoc, 11307 IdentifierInfo *Ident) { 11308 R.clear(); 11309 NamespaceValidatorCCC CCC{}; 11310 if (TypoCorrection Corrected = 11311 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11312 Sema::CTK_ErrorRecovery)) { 11313 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11314 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11315 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11316 Ident->getName().equals(CorrectedStr); 11317 S.diagnoseTypo(Corrected, 11318 S.PDiag(diag::err_using_directive_member_suggest) 11319 << Ident << DC << DroppedSpecifier << SS.getRange(), 11320 S.PDiag(diag::note_namespace_defined_here)); 11321 } else { 11322 S.diagnoseTypo(Corrected, 11323 S.PDiag(diag::err_using_directive_suggest) << Ident, 11324 S.PDiag(diag::note_namespace_defined_here)); 11325 } 11326 R.addDecl(Corrected.getFoundDecl()); 11327 return true; 11328 } 11329 return false; 11330 } 11331 11332 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11333 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11334 SourceLocation IdentLoc, 11335 IdentifierInfo *NamespcName, 11336 const ParsedAttributesView &AttrList) { 11337 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11338 assert(NamespcName && "Invalid NamespcName."); 11339 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11340 11341 // This can only happen along a recovery path. 11342 while (S->isTemplateParamScope()) 11343 S = S->getParent(); 11344 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11345 11346 UsingDirectiveDecl *UDir = nullptr; 11347 NestedNameSpecifier *Qualifier = nullptr; 11348 if (SS.isSet()) 11349 Qualifier = SS.getScopeRep(); 11350 11351 // Lookup namespace name. 11352 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11353 LookupParsedName(R, S, &SS); 11354 if (R.isAmbiguous()) 11355 return nullptr; 11356 11357 if (R.empty()) { 11358 R.clear(); 11359 // Allow "using namespace std;" or "using namespace ::std;" even if 11360 // "std" hasn't been defined yet, for GCC compatibility. 11361 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11362 NamespcName->isStr("std")) { 11363 Diag(IdentLoc, diag::ext_using_undefined_std); 11364 R.addDecl(getOrCreateStdNamespace()); 11365 R.resolveKind(); 11366 } 11367 // Otherwise, attempt typo correction. 11368 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11369 } 11370 11371 if (!R.empty()) { 11372 NamedDecl *Named = R.getRepresentativeDecl(); 11373 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11374 assert(NS && "expected namespace decl"); 11375 11376 // The use of a nested name specifier may trigger deprecation warnings. 11377 DiagnoseUseOfDecl(Named, IdentLoc); 11378 11379 // C++ [namespace.udir]p1: 11380 // A using-directive specifies that the names in the nominated 11381 // namespace can be used in the scope in which the 11382 // using-directive appears after the using-directive. During 11383 // unqualified name lookup (3.4.1), the names appear as if they 11384 // were declared in the nearest enclosing namespace which 11385 // contains both the using-directive and the nominated 11386 // namespace. [Note: in this context, "contains" means "contains 11387 // directly or indirectly". ] 11388 11389 // Find enclosing context containing both using-directive and 11390 // nominated namespace. 11391 DeclContext *CommonAncestor = NS; 11392 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11393 CommonAncestor = CommonAncestor->getParent(); 11394 11395 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11396 SS.getWithLocInContext(Context), 11397 IdentLoc, Named, CommonAncestor); 11398 11399 if (IsUsingDirectiveInToplevelContext(CurContext) && 11400 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11401 Diag(IdentLoc, diag::warn_using_directive_in_header); 11402 } 11403 11404 PushUsingDirective(S, UDir); 11405 } else { 11406 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11407 } 11408 11409 if (UDir) 11410 ProcessDeclAttributeList(S, UDir, AttrList); 11411 11412 return UDir; 11413 } 11414 11415 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11416 // If the scope has an associated entity and the using directive is at 11417 // namespace or translation unit scope, add the UsingDirectiveDecl into 11418 // its lookup structure so qualified name lookup can find it. 11419 DeclContext *Ctx = S->getEntity(); 11420 if (Ctx && !Ctx->isFunctionOrMethod()) 11421 Ctx->addDecl(UDir); 11422 else 11423 // Otherwise, it is at block scope. The using-directives will affect lookup 11424 // only to the end of the scope. 11425 S->PushUsingDirective(UDir); 11426 } 11427 11428 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11429 SourceLocation UsingLoc, 11430 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11431 UnqualifiedId &Name, 11432 SourceLocation EllipsisLoc, 11433 const ParsedAttributesView &AttrList) { 11434 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11435 11436 if (SS.isEmpty()) { 11437 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11438 return nullptr; 11439 } 11440 11441 switch (Name.getKind()) { 11442 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11443 case UnqualifiedIdKind::IK_Identifier: 11444 case UnqualifiedIdKind::IK_OperatorFunctionId: 11445 case UnqualifiedIdKind::IK_LiteralOperatorId: 11446 case UnqualifiedIdKind::IK_ConversionFunctionId: 11447 break; 11448 11449 case UnqualifiedIdKind::IK_ConstructorName: 11450 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11451 // C++11 inheriting constructors. 11452 Diag(Name.getBeginLoc(), 11453 getLangOpts().CPlusPlus11 11454 ? diag::warn_cxx98_compat_using_decl_constructor 11455 : diag::err_using_decl_constructor) 11456 << SS.getRange(); 11457 11458 if (getLangOpts().CPlusPlus11) break; 11459 11460 return nullptr; 11461 11462 case UnqualifiedIdKind::IK_DestructorName: 11463 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11464 return nullptr; 11465 11466 case UnqualifiedIdKind::IK_TemplateId: 11467 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11468 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11469 return nullptr; 11470 11471 case UnqualifiedIdKind::IK_DeductionGuideName: 11472 llvm_unreachable("cannot parse qualified deduction guide name"); 11473 } 11474 11475 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11476 DeclarationName TargetName = TargetNameInfo.getName(); 11477 if (!TargetName) 11478 return nullptr; 11479 11480 // Warn about access declarations. 11481 if (UsingLoc.isInvalid()) { 11482 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11483 ? diag::err_access_decl 11484 : diag::warn_access_decl_deprecated) 11485 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11486 } 11487 11488 if (EllipsisLoc.isInvalid()) { 11489 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11490 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11491 return nullptr; 11492 } else { 11493 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11494 !TargetNameInfo.containsUnexpandedParameterPack()) { 11495 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11496 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11497 EllipsisLoc = SourceLocation(); 11498 } 11499 } 11500 11501 NamedDecl *UD = 11502 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11503 SS, TargetNameInfo, EllipsisLoc, AttrList, 11504 /*IsInstantiation*/false); 11505 if (UD) 11506 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11507 11508 return UD; 11509 } 11510 11511 /// Determine whether a using declaration considers the given 11512 /// declarations as "equivalent", e.g., if they are redeclarations of 11513 /// the same entity or are both typedefs of the same type. 11514 static bool 11515 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11516 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11517 return true; 11518 11519 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11520 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11521 return Context.hasSameType(TD1->getUnderlyingType(), 11522 TD2->getUnderlyingType()); 11523 11524 return false; 11525 } 11526 11527 11528 /// Determines whether to create a using shadow decl for a particular 11529 /// decl, given the set of decls existing prior to this using lookup. 11530 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11531 const LookupResult &Previous, 11532 UsingShadowDecl *&PrevShadow) { 11533 // Diagnose finding a decl which is not from a base class of the 11534 // current class. We do this now because there are cases where this 11535 // function will silently decide not to build a shadow decl, which 11536 // will pre-empt further diagnostics. 11537 // 11538 // We don't need to do this in C++11 because we do the check once on 11539 // the qualifier. 11540 // 11541 // FIXME: diagnose the following if we care enough: 11542 // struct A { int foo; }; 11543 // struct B : A { using A::foo; }; 11544 // template <class T> struct C : A {}; 11545 // template <class T> struct D : C<T> { using B::foo; } // <--- 11546 // This is invalid (during instantiation) in C++03 because B::foo 11547 // resolves to the using decl in B, which is not a base class of D<T>. 11548 // We can't diagnose it immediately because C<T> is an unknown 11549 // specialization. The UsingShadowDecl in D<T> then points directly 11550 // to A::foo, which will look well-formed when we instantiate. 11551 // The right solution is to not collapse the shadow-decl chain. 11552 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11553 DeclContext *OrigDC = Orig->getDeclContext(); 11554 11555 // Handle enums and anonymous structs. 11556 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11557 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11558 while (OrigRec->isAnonymousStructOrUnion()) 11559 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11560 11561 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11562 if (OrigDC == CurContext) { 11563 Diag(Using->getLocation(), 11564 diag::err_using_decl_nested_name_specifier_is_current_class) 11565 << Using->getQualifierLoc().getSourceRange(); 11566 Diag(Orig->getLocation(), diag::note_using_decl_target); 11567 Using->setInvalidDecl(); 11568 return true; 11569 } 11570 11571 Diag(Using->getQualifierLoc().getBeginLoc(), 11572 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11573 << Using->getQualifier() 11574 << cast<CXXRecordDecl>(CurContext) 11575 << Using->getQualifierLoc().getSourceRange(); 11576 Diag(Orig->getLocation(), diag::note_using_decl_target); 11577 Using->setInvalidDecl(); 11578 return true; 11579 } 11580 } 11581 11582 if (Previous.empty()) return false; 11583 11584 NamedDecl *Target = Orig; 11585 if (isa<UsingShadowDecl>(Target)) 11586 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11587 11588 // If the target happens to be one of the previous declarations, we 11589 // don't have a conflict. 11590 // 11591 // FIXME: but we might be increasing its access, in which case we 11592 // should redeclare it. 11593 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11594 bool FoundEquivalentDecl = false; 11595 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11596 I != E; ++I) { 11597 NamedDecl *D = (*I)->getUnderlyingDecl(); 11598 // We can have UsingDecls in our Previous results because we use the same 11599 // LookupResult for checking whether the UsingDecl itself is a valid 11600 // redeclaration. 11601 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11602 continue; 11603 11604 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11605 // C++ [class.mem]p19: 11606 // If T is the name of a class, then [every named member other than 11607 // a non-static data member] shall have a name different from T 11608 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11609 !isa<IndirectFieldDecl>(Target) && 11610 !isa<UnresolvedUsingValueDecl>(Target) && 11611 DiagnoseClassNameShadow( 11612 CurContext, 11613 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11614 return true; 11615 } 11616 11617 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11618 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11619 PrevShadow = Shadow; 11620 FoundEquivalentDecl = true; 11621 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11622 // We don't conflict with an existing using shadow decl of an equivalent 11623 // declaration, but we're not a redeclaration of it. 11624 FoundEquivalentDecl = true; 11625 } 11626 11627 if (isVisible(D)) 11628 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11629 } 11630 11631 if (FoundEquivalentDecl) 11632 return false; 11633 11634 if (FunctionDecl *FD = Target->getAsFunction()) { 11635 NamedDecl *OldDecl = nullptr; 11636 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11637 /*IsForUsingDecl*/ true)) { 11638 case Ovl_Overload: 11639 return false; 11640 11641 case Ovl_NonFunction: 11642 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11643 break; 11644 11645 // We found a decl with the exact signature. 11646 case Ovl_Match: 11647 // If we're in a record, we want to hide the target, so we 11648 // return true (without a diagnostic) to tell the caller not to 11649 // build a shadow decl. 11650 if (CurContext->isRecord()) 11651 return true; 11652 11653 // If we're not in a record, this is an error. 11654 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11655 break; 11656 } 11657 11658 Diag(Target->getLocation(), diag::note_using_decl_target); 11659 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11660 Using->setInvalidDecl(); 11661 return true; 11662 } 11663 11664 // Target is not a function. 11665 11666 if (isa<TagDecl>(Target)) { 11667 // No conflict between a tag and a non-tag. 11668 if (!Tag) return false; 11669 11670 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11671 Diag(Target->getLocation(), diag::note_using_decl_target); 11672 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11673 Using->setInvalidDecl(); 11674 return true; 11675 } 11676 11677 // No conflict between a tag and a non-tag. 11678 if (!NonTag) return false; 11679 11680 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11681 Diag(Target->getLocation(), diag::note_using_decl_target); 11682 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11683 Using->setInvalidDecl(); 11684 return true; 11685 } 11686 11687 /// Determine whether a direct base class is a virtual base class. 11688 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11689 if (!Derived->getNumVBases()) 11690 return false; 11691 for (auto &B : Derived->bases()) 11692 if (B.getType()->getAsCXXRecordDecl() == Base) 11693 return B.isVirtual(); 11694 llvm_unreachable("not a direct base class"); 11695 } 11696 11697 /// Builds a shadow declaration corresponding to a 'using' declaration. 11698 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11699 UsingDecl *UD, 11700 NamedDecl *Orig, 11701 UsingShadowDecl *PrevDecl) { 11702 // If we resolved to another shadow declaration, just coalesce them. 11703 NamedDecl *Target = Orig; 11704 if (isa<UsingShadowDecl>(Target)) { 11705 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11706 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11707 } 11708 11709 NamedDecl *NonTemplateTarget = Target; 11710 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11711 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11712 11713 UsingShadowDecl *Shadow; 11714 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11715 bool IsVirtualBase = 11716 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11717 UD->getQualifier()->getAsRecordDecl()); 11718 Shadow = ConstructorUsingShadowDecl::Create( 11719 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11720 } else { 11721 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11722 Target); 11723 } 11724 UD->addShadowDecl(Shadow); 11725 11726 Shadow->setAccess(UD->getAccess()); 11727 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11728 Shadow->setInvalidDecl(); 11729 11730 Shadow->setPreviousDecl(PrevDecl); 11731 11732 if (S) 11733 PushOnScopeChains(Shadow, S); 11734 else 11735 CurContext->addDecl(Shadow); 11736 11737 11738 return Shadow; 11739 } 11740 11741 /// Hides a using shadow declaration. This is required by the current 11742 /// using-decl implementation when a resolvable using declaration in a 11743 /// class is followed by a declaration which would hide or override 11744 /// one or more of the using decl's targets; for example: 11745 /// 11746 /// struct Base { void foo(int); }; 11747 /// struct Derived : Base { 11748 /// using Base::foo; 11749 /// void foo(int); 11750 /// }; 11751 /// 11752 /// The governing language is C++03 [namespace.udecl]p12: 11753 /// 11754 /// When a using-declaration brings names from a base class into a 11755 /// derived class scope, member functions in the derived class 11756 /// override and/or hide member functions with the same name and 11757 /// parameter types in a base class (rather than conflicting). 11758 /// 11759 /// There are two ways to implement this: 11760 /// (1) optimistically create shadow decls when they're not hidden 11761 /// by existing declarations, or 11762 /// (2) don't create any shadow decls (or at least don't make them 11763 /// visible) until we've fully parsed/instantiated the class. 11764 /// The problem with (1) is that we might have to retroactively remove 11765 /// a shadow decl, which requires several O(n) operations because the 11766 /// decl structures are (very reasonably) not designed for removal. 11767 /// (2) avoids this but is very fiddly and phase-dependent. 11768 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11769 if (Shadow->getDeclName().getNameKind() == 11770 DeclarationName::CXXConversionFunctionName) 11771 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11772 11773 // Remove it from the DeclContext... 11774 Shadow->getDeclContext()->removeDecl(Shadow); 11775 11776 // ...and the scope, if applicable... 11777 if (S) { 11778 S->RemoveDecl(Shadow); 11779 IdResolver.RemoveDecl(Shadow); 11780 } 11781 11782 // ...and the using decl. 11783 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11784 11785 // TODO: complain somehow if Shadow was used. It shouldn't 11786 // be possible for this to happen, because...? 11787 } 11788 11789 /// Find the base specifier for a base class with the given type. 11790 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11791 QualType DesiredBase, 11792 bool &AnyDependentBases) { 11793 // Check whether the named type is a direct base class. 11794 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11795 .getUnqualifiedType(); 11796 for (auto &Base : Derived->bases()) { 11797 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11798 if (CanonicalDesiredBase == BaseType) 11799 return &Base; 11800 if (BaseType->isDependentType()) 11801 AnyDependentBases = true; 11802 } 11803 return nullptr; 11804 } 11805 11806 namespace { 11807 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11808 public: 11809 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11810 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11811 : HasTypenameKeyword(HasTypenameKeyword), 11812 IsInstantiation(IsInstantiation), OldNNS(NNS), 11813 RequireMemberOf(RequireMemberOf) {} 11814 11815 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11816 NamedDecl *ND = Candidate.getCorrectionDecl(); 11817 11818 // Keywords are not valid here. 11819 if (!ND || isa<NamespaceDecl>(ND)) 11820 return false; 11821 11822 // Completely unqualified names are invalid for a 'using' declaration. 11823 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11824 return false; 11825 11826 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11827 // reject. 11828 11829 if (RequireMemberOf) { 11830 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11831 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11832 // No-one ever wants a using-declaration to name an injected-class-name 11833 // of a base class, unless they're declaring an inheriting constructor. 11834 ASTContext &Ctx = ND->getASTContext(); 11835 if (!Ctx.getLangOpts().CPlusPlus11) 11836 return false; 11837 QualType FoundType = Ctx.getRecordType(FoundRecord); 11838 11839 // Check that the injected-class-name is named as a member of its own 11840 // type; we don't want to suggest 'using Derived::Base;', since that 11841 // means something else. 11842 NestedNameSpecifier *Specifier = 11843 Candidate.WillReplaceSpecifier() 11844 ? Candidate.getCorrectionSpecifier() 11845 : OldNNS; 11846 if (!Specifier->getAsType() || 11847 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11848 return false; 11849 11850 // Check that this inheriting constructor declaration actually names a 11851 // direct base class of the current class. 11852 bool AnyDependentBases = false; 11853 if (!findDirectBaseWithType(RequireMemberOf, 11854 Ctx.getRecordType(FoundRecord), 11855 AnyDependentBases) && 11856 !AnyDependentBases) 11857 return false; 11858 } else { 11859 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11860 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11861 return false; 11862 11863 // FIXME: Check that the base class member is accessible? 11864 } 11865 } else { 11866 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11867 if (FoundRecord && FoundRecord->isInjectedClassName()) 11868 return false; 11869 } 11870 11871 if (isa<TypeDecl>(ND)) 11872 return HasTypenameKeyword || !IsInstantiation; 11873 11874 return !HasTypenameKeyword; 11875 } 11876 11877 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11878 return std::make_unique<UsingValidatorCCC>(*this); 11879 } 11880 11881 private: 11882 bool HasTypenameKeyword; 11883 bool IsInstantiation; 11884 NestedNameSpecifier *OldNNS; 11885 CXXRecordDecl *RequireMemberOf; 11886 }; 11887 } // end anonymous namespace 11888 11889 /// Builds a using declaration. 11890 /// 11891 /// \param IsInstantiation - Whether this call arises from an 11892 /// instantiation of an unresolved using declaration. We treat 11893 /// the lookup differently for these declarations. 11894 NamedDecl *Sema::BuildUsingDeclaration( 11895 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11896 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11897 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11898 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11899 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11900 SourceLocation IdentLoc = NameInfo.getLoc(); 11901 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11902 11903 // FIXME: We ignore attributes for now. 11904 11905 // For an inheriting constructor declaration, the name of the using 11906 // declaration is the name of a constructor in this class, not in the 11907 // base class. 11908 DeclarationNameInfo UsingName = NameInfo; 11909 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11910 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11911 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11912 Context.getCanonicalType(Context.getRecordType(RD)))); 11913 11914 // Do the redeclaration lookup in the current scope. 11915 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11916 ForVisibleRedeclaration); 11917 Previous.setHideTags(false); 11918 if (S) { 11919 LookupName(Previous, S); 11920 11921 // It is really dumb that we have to do this. 11922 LookupResult::Filter F = Previous.makeFilter(); 11923 while (F.hasNext()) { 11924 NamedDecl *D = F.next(); 11925 if (!isDeclInScope(D, CurContext, S)) 11926 F.erase(); 11927 // If we found a local extern declaration that's not ordinarily visible, 11928 // and this declaration is being added to a non-block scope, ignore it. 11929 // We're only checking for scope conflicts here, not also for violations 11930 // of the linkage rules. 11931 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11932 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11933 F.erase(); 11934 } 11935 F.done(); 11936 } else { 11937 assert(IsInstantiation && "no scope in non-instantiation"); 11938 if (CurContext->isRecord()) 11939 LookupQualifiedName(Previous, CurContext); 11940 else { 11941 // No redeclaration check is needed here; in non-member contexts we 11942 // diagnosed all possible conflicts with other using-declarations when 11943 // building the template: 11944 // 11945 // For a dependent non-type using declaration, the only valid case is 11946 // if we instantiate to a single enumerator. We check for conflicts 11947 // between shadow declarations we introduce, and we check in the template 11948 // definition for conflicts between a non-type using declaration and any 11949 // other declaration, which together covers all cases. 11950 // 11951 // A dependent typename using declaration will never successfully 11952 // instantiate, since it will always name a class member, so we reject 11953 // that in the template definition. 11954 } 11955 } 11956 11957 // Check for invalid redeclarations. 11958 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 11959 SS, IdentLoc, Previous)) 11960 return nullptr; 11961 11962 // Check for bad qualifiers. 11963 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 11964 IdentLoc)) 11965 return nullptr; 11966 11967 DeclContext *LookupContext = computeDeclContext(SS); 11968 NamedDecl *D; 11969 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11970 if (!LookupContext || EllipsisLoc.isValid()) { 11971 if (HasTypenameKeyword) { 11972 // FIXME: not all declaration name kinds are legal here 11973 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 11974 UsingLoc, TypenameLoc, 11975 QualifierLoc, 11976 IdentLoc, NameInfo.getName(), 11977 EllipsisLoc); 11978 } else { 11979 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 11980 QualifierLoc, NameInfo, EllipsisLoc); 11981 } 11982 D->setAccess(AS); 11983 CurContext->addDecl(D); 11984 return D; 11985 } 11986 11987 auto Build = [&](bool Invalid) { 11988 UsingDecl *UD = 11989 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 11990 UsingName, HasTypenameKeyword); 11991 UD->setAccess(AS); 11992 CurContext->addDecl(UD); 11993 UD->setInvalidDecl(Invalid); 11994 return UD; 11995 }; 11996 auto BuildInvalid = [&]{ return Build(true); }; 11997 auto BuildValid = [&]{ return Build(false); }; 11998 11999 if (RequireCompleteDeclContext(SS, LookupContext)) 12000 return BuildInvalid(); 12001 12002 // Look up the target name. 12003 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12004 12005 // Unlike most lookups, we don't always want to hide tag 12006 // declarations: tag names are visible through the using declaration 12007 // even if hidden by ordinary names, *except* in a dependent context 12008 // where it's important for the sanity of two-phase lookup. 12009 if (!IsInstantiation) 12010 R.setHideTags(false); 12011 12012 // For the purposes of this lookup, we have a base object type 12013 // equal to that of the current context. 12014 if (CurContext->isRecord()) { 12015 R.setBaseObjectType( 12016 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12017 } 12018 12019 LookupQualifiedName(R, LookupContext); 12020 12021 // Try to correct typos if possible. If constructor name lookup finds no 12022 // results, that means the named class has no explicit constructors, and we 12023 // suppressed declaring implicit ones (probably because it's dependent or 12024 // invalid). 12025 if (R.empty() && 12026 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12027 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 12028 // it will believe that glibc provides a ::gets in cases where it does not, 12029 // and will try to pull it into namespace std with a using-declaration. 12030 // Just ignore the using-declaration in that case. 12031 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12032 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12033 CurContext->isStdNamespace() && 12034 isa<TranslationUnitDecl>(LookupContext) && 12035 getSourceManager().isInSystemHeader(UsingLoc)) 12036 return nullptr; 12037 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12038 dyn_cast<CXXRecordDecl>(CurContext)); 12039 if (TypoCorrection Corrected = 12040 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12041 CTK_ErrorRecovery)) { 12042 // We reject candidates where DroppedSpecifier == true, hence the 12043 // literal '0' below. 12044 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12045 << NameInfo.getName() << LookupContext << 0 12046 << SS.getRange()); 12047 12048 // If we picked a correction with no attached Decl we can't do anything 12049 // useful with it, bail out. 12050 NamedDecl *ND = Corrected.getCorrectionDecl(); 12051 if (!ND) 12052 return BuildInvalid(); 12053 12054 // If we corrected to an inheriting constructor, handle it as one. 12055 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12056 if (RD && RD->isInjectedClassName()) { 12057 // The parent of the injected class name is the class itself. 12058 RD = cast<CXXRecordDecl>(RD->getParent()); 12059 12060 // Fix up the information we'll use to build the using declaration. 12061 if (Corrected.WillReplaceSpecifier()) { 12062 NestedNameSpecifierLocBuilder Builder; 12063 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12064 QualifierLoc.getSourceRange()); 12065 QualifierLoc = Builder.getWithLocInContext(Context); 12066 } 12067 12068 // In this case, the name we introduce is the name of a derived class 12069 // constructor. 12070 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12071 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12072 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12073 UsingName.setNamedTypeInfo(nullptr); 12074 for (auto *Ctor : LookupConstructors(RD)) 12075 R.addDecl(Ctor); 12076 R.resolveKind(); 12077 } else { 12078 // FIXME: Pick up all the declarations if we found an overloaded 12079 // function. 12080 UsingName.setName(ND->getDeclName()); 12081 R.addDecl(ND); 12082 } 12083 } else { 12084 Diag(IdentLoc, diag::err_no_member) 12085 << NameInfo.getName() << LookupContext << SS.getRange(); 12086 return BuildInvalid(); 12087 } 12088 } 12089 12090 if (R.isAmbiguous()) 12091 return BuildInvalid(); 12092 12093 if (HasTypenameKeyword) { 12094 // If we asked for a typename and got a non-type decl, error out. 12095 if (!R.getAsSingle<TypeDecl>()) { 12096 Diag(IdentLoc, diag::err_using_typename_non_type); 12097 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12098 Diag((*I)->getUnderlyingDecl()->getLocation(), 12099 diag::note_using_decl_target); 12100 return BuildInvalid(); 12101 } 12102 } else { 12103 // If we asked for a non-typename and we got a type, error out, 12104 // but only if this is an instantiation of an unresolved using 12105 // decl. Otherwise just silently find the type name. 12106 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12107 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12108 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12109 return BuildInvalid(); 12110 } 12111 } 12112 12113 // C++14 [namespace.udecl]p6: 12114 // A using-declaration shall not name a namespace. 12115 if (R.getAsSingle<NamespaceDecl>()) { 12116 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12117 << SS.getRange(); 12118 return BuildInvalid(); 12119 } 12120 12121 // C++14 [namespace.udecl]p7: 12122 // A using-declaration shall not name a scoped enumerator. 12123 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12124 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12125 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12126 << SS.getRange(); 12127 return BuildInvalid(); 12128 } 12129 } 12130 12131 UsingDecl *UD = BuildValid(); 12132 12133 // Some additional rules apply to inheriting constructors. 12134 if (UsingName.getName().getNameKind() == 12135 DeclarationName::CXXConstructorName) { 12136 // Suppress access diagnostics; the access check is instead performed at the 12137 // point of use for an inheriting constructor. 12138 R.suppressDiagnostics(); 12139 if (CheckInheritingConstructorUsingDecl(UD)) 12140 return UD; 12141 } 12142 12143 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12144 UsingShadowDecl *PrevDecl = nullptr; 12145 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12146 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12147 } 12148 12149 return UD; 12150 } 12151 12152 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12153 ArrayRef<NamedDecl *> Expansions) { 12154 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12155 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12156 isa<UsingPackDecl>(InstantiatedFrom)); 12157 12158 auto *UPD = 12159 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12160 UPD->setAccess(InstantiatedFrom->getAccess()); 12161 CurContext->addDecl(UPD); 12162 return UPD; 12163 } 12164 12165 /// Additional checks for a using declaration referring to a constructor name. 12166 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12167 assert(!UD->hasTypename() && "expecting a constructor name"); 12168 12169 const Type *SourceType = UD->getQualifier()->getAsType(); 12170 assert(SourceType && 12171 "Using decl naming constructor doesn't have type in scope spec."); 12172 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12173 12174 // Check whether the named type is a direct base class. 12175 bool AnyDependentBases = false; 12176 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12177 AnyDependentBases); 12178 if (!Base && !AnyDependentBases) { 12179 Diag(UD->getUsingLoc(), 12180 diag::err_using_decl_constructor_not_in_direct_base) 12181 << UD->getNameInfo().getSourceRange() 12182 << QualType(SourceType, 0) << TargetClass; 12183 UD->setInvalidDecl(); 12184 return true; 12185 } 12186 12187 if (Base) 12188 Base->setInheritConstructors(); 12189 12190 return false; 12191 } 12192 12193 /// Checks that the given using declaration is not an invalid 12194 /// redeclaration. Note that this is checking only for the using decl 12195 /// itself, not for any ill-formedness among the UsingShadowDecls. 12196 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12197 bool HasTypenameKeyword, 12198 const CXXScopeSpec &SS, 12199 SourceLocation NameLoc, 12200 const LookupResult &Prev) { 12201 NestedNameSpecifier *Qual = SS.getScopeRep(); 12202 12203 // C++03 [namespace.udecl]p8: 12204 // C++0x [namespace.udecl]p10: 12205 // A using-declaration is a declaration and can therefore be used 12206 // repeatedly where (and only where) multiple declarations are 12207 // allowed. 12208 // 12209 // That's in non-member contexts. 12210 if (!CurContext->getRedeclContext()->isRecord()) { 12211 // A dependent qualifier outside a class can only ever resolve to an 12212 // enumeration type. Therefore it conflicts with any other non-type 12213 // declaration in the same scope. 12214 // FIXME: How should we check for dependent type-type conflicts at block 12215 // scope? 12216 if (Qual->isDependent() && !HasTypenameKeyword) { 12217 for (auto *D : Prev) { 12218 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12219 bool OldCouldBeEnumerator = 12220 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12221 Diag(NameLoc, 12222 OldCouldBeEnumerator ? diag::err_redefinition 12223 : diag::err_redefinition_different_kind) 12224 << Prev.getLookupName(); 12225 Diag(D->getLocation(), diag::note_previous_definition); 12226 return true; 12227 } 12228 } 12229 } 12230 return false; 12231 } 12232 12233 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12234 NamedDecl *D = *I; 12235 12236 bool DTypename; 12237 NestedNameSpecifier *DQual; 12238 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12239 DTypename = UD->hasTypename(); 12240 DQual = UD->getQualifier(); 12241 } else if (UnresolvedUsingValueDecl *UD 12242 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12243 DTypename = false; 12244 DQual = UD->getQualifier(); 12245 } else if (UnresolvedUsingTypenameDecl *UD 12246 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12247 DTypename = true; 12248 DQual = UD->getQualifier(); 12249 } else continue; 12250 12251 // using decls differ if one says 'typename' and the other doesn't. 12252 // FIXME: non-dependent using decls? 12253 if (HasTypenameKeyword != DTypename) continue; 12254 12255 // using decls differ if they name different scopes (but note that 12256 // template instantiation can cause this check to trigger when it 12257 // didn't before instantiation). 12258 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12259 Context.getCanonicalNestedNameSpecifier(DQual)) 12260 continue; 12261 12262 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12263 Diag(D->getLocation(), diag::note_using_decl) << 1; 12264 return true; 12265 } 12266 12267 return false; 12268 } 12269 12270 12271 /// Checks that the given nested-name qualifier used in a using decl 12272 /// in the current context is appropriately related to the current 12273 /// scope. If an error is found, diagnoses it and returns true. 12274 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12275 bool HasTypename, 12276 const CXXScopeSpec &SS, 12277 const DeclarationNameInfo &NameInfo, 12278 SourceLocation NameLoc) { 12279 DeclContext *NamedContext = computeDeclContext(SS); 12280 12281 if (!CurContext->isRecord()) { 12282 // C++03 [namespace.udecl]p3: 12283 // C++0x [namespace.udecl]p8: 12284 // A using-declaration for a class member shall be a member-declaration. 12285 12286 // If we weren't able to compute a valid scope, it might validly be a 12287 // dependent class scope or a dependent enumeration unscoped scope. If 12288 // we have a 'typename' keyword, the scope must resolve to a class type. 12289 if ((HasTypename && !NamedContext) || 12290 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12291 auto *RD = NamedContext 12292 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12293 : nullptr; 12294 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12295 RD = nullptr; 12296 12297 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12298 << SS.getRange(); 12299 12300 // If we have a complete, non-dependent source type, try to suggest a 12301 // way to get the same effect. 12302 if (!RD) 12303 return true; 12304 12305 // Find what this using-declaration was referring to. 12306 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12307 R.setHideTags(false); 12308 R.suppressDiagnostics(); 12309 LookupQualifiedName(R, RD); 12310 12311 if (R.getAsSingle<TypeDecl>()) { 12312 if (getLangOpts().CPlusPlus11) { 12313 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12314 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12315 << 0 // alias declaration 12316 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12317 NameInfo.getName().getAsString() + 12318 " = "); 12319 } else { 12320 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12321 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12322 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12323 << 1 // typedef declaration 12324 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12325 << FixItHint::CreateInsertion( 12326 InsertLoc, " " + NameInfo.getName().getAsString()); 12327 } 12328 } else if (R.getAsSingle<VarDecl>()) { 12329 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12330 // repeating the type of the static data member here. 12331 FixItHint FixIt; 12332 if (getLangOpts().CPlusPlus11) { 12333 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12334 FixIt = FixItHint::CreateReplacement( 12335 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12336 } 12337 12338 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12339 << 2 // reference declaration 12340 << FixIt; 12341 } else if (R.getAsSingle<EnumConstantDecl>()) { 12342 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12343 // repeating the type of the enumeration here, and we can't do so if 12344 // the type is anonymous. 12345 FixItHint FixIt; 12346 if (getLangOpts().CPlusPlus11) { 12347 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12348 FixIt = FixItHint::CreateReplacement( 12349 UsingLoc, 12350 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12351 } 12352 12353 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12354 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12355 << FixIt; 12356 } 12357 return true; 12358 } 12359 12360 // Otherwise, this might be valid. 12361 return false; 12362 } 12363 12364 // The current scope is a record. 12365 12366 // If the named context is dependent, we can't decide much. 12367 if (!NamedContext) { 12368 // FIXME: in C++0x, we can diagnose if we can prove that the 12369 // nested-name-specifier does not refer to a base class, which is 12370 // still possible in some cases. 12371 12372 // Otherwise we have to conservatively report that things might be 12373 // okay. 12374 return false; 12375 } 12376 12377 if (!NamedContext->isRecord()) { 12378 // Ideally this would point at the last name in the specifier, 12379 // but we don't have that level of source info. 12380 Diag(SS.getRange().getBegin(), 12381 diag::err_using_decl_nested_name_specifier_is_not_class) 12382 << SS.getScopeRep() << SS.getRange(); 12383 return true; 12384 } 12385 12386 if (!NamedContext->isDependentContext() && 12387 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12388 return true; 12389 12390 if (getLangOpts().CPlusPlus11) { 12391 // C++11 [namespace.udecl]p3: 12392 // In a using-declaration used as a member-declaration, the 12393 // nested-name-specifier shall name a base class of the class 12394 // being defined. 12395 12396 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12397 cast<CXXRecordDecl>(NamedContext))) { 12398 if (CurContext == NamedContext) { 12399 Diag(NameLoc, 12400 diag::err_using_decl_nested_name_specifier_is_current_class) 12401 << SS.getRange(); 12402 return true; 12403 } 12404 12405 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12406 Diag(SS.getRange().getBegin(), 12407 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12408 << SS.getScopeRep() 12409 << cast<CXXRecordDecl>(CurContext) 12410 << SS.getRange(); 12411 } 12412 return true; 12413 } 12414 12415 return false; 12416 } 12417 12418 // C++03 [namespace.udecl]p4: 12419 // A using-declaration used as a member-declaration shall refer 12420 // to a member of a base class of the class being defined [etc.]. 12421 12422 // Salient point: SS doesn't have to name a base class as long as 12423 // lookup only finds members from base classes. Therefore we can 12424 // diagnose here only if we can prove that that can't happen, 12425 // i.e. if the class hierarchies provably don't intersect. 12426 12427 // TODO: it would be nice if "definitely valid" results were cached 12428 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12429 // need to be repeated. 12430 12431 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12432 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12433 Bases.insert(Base); 12434 return true; 12435 }; 12436 12437 // Collect all bases. Return false if we find a dependent base. 12438 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12439 return false; 12440 12441 // Returns true if the base is dependent or is one of the accumulated base 12442 // classes. 12443 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12444 return !Bases.count(Base); 12445 }; 12446 12447 // Return false if the class has a dependent base or if it or one 12448 // of its bases is present in the base set of the current context. 12449 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12450 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12451 return false; 12452 12453 Diag(SS.getRange().getBegin(), 12454 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12455 << SS.getScopeRep() 12456 << cast<CXXRecordDecl>(CurContext) 12457 << SS.getRange(); 12458 12459 return true; 12460 } 12461 12462 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12463 MultiTemplateParamsArg TemplateParamLists, 12464 SourceLocation UsingLoc, UnqualifiedId &Name, 12465 const ParsedAttributesView &AttrList, 12466 TypeResult Type, Decl *DeclFromDeclSpec) { 12467 // Skip up to the relevant declaration scope. 12468 while (S->isTemplateParamScope()) 12469 S = S->getParent(); 12470 assert((S->getFlags() & Scope::DeclScope) && 12471 "got alias-declaration outside of declaration scope"); 12472 12473 if (Type.isInvalid()) 12474 return nullptr; 12475 12476 bool Invalid = false; 12477 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12478 TypeSourceInfo *TInfo = nullptr; 12479 GetTypeFromParser(Type.get(), &TInfo); 12480 12481 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12482 return nullptr; 12483 12484 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12485 UPPC_DeclarationType)) { 12486 Invalid = true; 12487 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12488 TInfo->getTypeLoc().getBeginLoc()); 12489 } 12490 12491 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12492 TemplateParamLists.size() 12493 ? forRedeclarationInCurContext() 12494 : ForVisibleRedeclaration); 12495 LookupName(Previous, S); 12496 12497 // Warn about shadowing the name of a template parameter. 12498 if (Previous.isSingleResult() && 12499 Previous.getFoundDecl()->isTemplateParameter()) { 12500 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12501 Previous.clear(); 12502 } 12503 12504 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12505 "name in alias declaration must be an identifier"); 12506 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12507 Name.StartLocation, 12508 Name.Identifier, TInfo); 12509 12510 NewTD->setAccess(AS); 12511 12512 if (Invalid) 12513 NewTD->setInvalidDecl(); 12514 12515 ProcessDeclAttributeList(S, NewTD, AttrList); 12516 AddPragmaAttributes(S, NewTD); 12517 12518 CheckTypedefForVariablyModifiedType(S, NewTD); 12519 Invalid |= NewTD->isInvalidDecl(); 12520 12521 bool Redeclaration = false; 12522 12523 NamedDecl *NewND; 12524 if (TemplateParamLists.size()) { 12525 TypeAliasTemplateDecl *OldDecl = nullptr; 12526 TemplateParameterList *OldTemplateParams = nullptr; 12527 12528 if (TemplateParamLists.size() != 1) { 12529 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12530 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12531 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12532 } 12533 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12534 12535 // Check that we can declare a template here. 12536 if (CheckTemplateDeclScope(S, TemplateParams)) 12537 return nullptr; 12538 12539 // Only consider previous declarations in the same scope. 12540 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12541 /*ExplicitInstantiationOrSpecialization*/false); 12542 if (!Previous.empty()) { 12543 Redeclaration = true; 12544 12545 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12546 if (!OldDecl && !Invalid) { 12547 Diag(UsingLoc, diag::err_redefinition_different_kind) 12548 << Name.Identifier; 12549 12550 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12551 if (OldD->getLocation().isValid()) 12552 Diag(OldD->getLocation(), diag::note_previous_definition); 12553 12554 Invalid = true; 12555 } 12556 12557 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12558 if (TemplateParameterListsAreEqual(TemplateParams, 12559 OldDecl->getTemplateParameters(), 12560 /*Complain=*/true, 12561 TPL_TemplateMatch)) 12562 OldTemplateParams = 12563 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12564 else 12565 Invalid = true; 12566 12567 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12568 if (!Invalid && 12569 !Context.hasSameType(OldTD->getUnderlyingType(), 12570 NewTD->getUnderlyingType())) { 12571 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12572 // but we can't reasonably accept it. 12573 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12574 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12575 if (OldTD->getLocation().isValid()) 12576 Diag(OldTD->getLocation(), diag::note_previous_definition); 12577 Invalid = true; 12578 } 12579 } 12580 } 12581 12582 // Merge any previous default template arguments into our parameters, 12583 // and check the parameter list. 12584 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12585 TPC_TypeAliasTemplate)) 12586 return nullptr; 12587 12588 TypeAliasTemplateDecl *NewDecl = 12589 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12590 Name.Identifier, TemplateParams, 12591 NewTD); 12592 NewTD->setDescribedAliasTemplate(NewDecl); 12593 12594 NewDecl->setAccess(AS); 12595 12596 if (Invalid) 12597 NewDecl->setInvalidDecl(); 12598 else if (OldDecl) { 12599 NewDecl->setPreviousDecl(OldDecl); 12600 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12601 } 12602 12603 NewND = NewDecl; 12604 } else { 12605 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12606 setTagNameForLinkagePurposes(TD, NewTD); 12607 handleTagNumbering(TD, S); 12608 } 12609 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12610 NewND = NewTD; 12611 } 12612 12613 PushOnScopeChains(NewND, S); 12614 ActOnDocumentableDecl(NewND); 12615 return NewND; 12616 } 12617 12618 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12619 SourceLocation AliasLoc, 12620 IdentifierInfo *Alias, CXXScopeSpec &SS, 12621 SourceLocation IdentLoc, 12622 IdentifierInfo *Ident) { 12623 12624 // Lookup the namespace name. 12625 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12626 LookupParsedName(R, S, &SS); 12627 12628 if (R.isAmbiguous()) 12629 return nullptr; 12630 12631 if (R.empty()) { 12632 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12633 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12634 return nullptr; 12635 } 12636 } 12637 assert(!R.isAmbiguous() && !R.empty()); 12638 NamedDecl *ND = R.getRepresentativeDecl(); 12639 12640 // Check if we have a previous declaration with the same name. 12641 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12642 ForVisibleRedeclaration); 12643 LookupName(PrevR, S); 12644 12645 // Check we're not shadowing a template parameter. 12646 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12647 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12648 PrevR.clear(); 12649 } 12650 12651 // Filter out any other lookup result from an enclosing scope. 12652 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12653 /*AllowInlineNamespace*/false); 12654 12655 // Find the previous declaration and check that we can redeclare it. 12656 NamespaceAliasDecl *Prev = nullptr; 12657 if (PrevR.isSingleResult()) { 12658 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12659 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12660 // We already have an alias with the same name that points to the same 12661 // namespace; check that it matches. 12662 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12663 Prev = AD; 12664 } else if (isVisible(PrevDecl)) { 12665 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12666 << Alias; 12667 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12668 << AD->getNamespace(); 12669 return nullptr; 12670 } 12671 } else if (isVisible(PrevDecl)) { 12672 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12673 ? diag::err_redefinition 12674 : diag::err_redefinition_different_kind; 12675 Diag(AliasLoc, DiagID) << Alias; 12676 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12677 return nullptr; 12678 } 12679 } 12680 12681 // The use of a nested name specifier may trigger deprecation warnings. 12682 DiagnoseUseOfDecl(ND, IdentLoc); 12683 12684 NamespaceAliasDecl *AliasDecl = 12685 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12686 Alias, SS.getWithLocInContext(Context), 12687 IdentLoc, ND); 12688 if (Prev) 12689 AliasDecl->setPreviousDecl(Prev); 12690 12691 PushOnScopeChains(AliasDecl, S); 12692 return AliasDecl; 12693 } 12694 12695 namespace { 12696 struct SpecialMemberExceptionSpecInfo 12697 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12698 SourceLocation Loc; 12699 Sema::ImplicitExceptionSpecification ExceptSpec; 12700 12701 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12702 Sema::CXXSpecialMember CSM, 12703 Sema::InheritedConstructorInfo *ICI, 12704 SourceLocation Loc) 12705 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12706 12707 bool visitBase(CXXBaseSpecifier *Base); 12708 bool visitField(FieldDecl *FD); 12709 12710 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12711 unsigned Quals); 12712 12713 void visitSubobjectCall(Subobject Subobj, 12714 Sema::SpecialMemberOverloadResult SMOR); 12715 }; 12716 } 12717 12718 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12719 auto *RT = Base->getType()->getAs<RecordType>(); 12720 if (!RT) 12721 return false; 12722 12723 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12724 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12725 if (auto *BaseCtor = SMOR.getMethod()) { 12726 visitSubobjectCall(Base, BaseCtor); 12727 return false; 12728 } 12729 12730 visitClassSubobject(BaseClass, Base, 0); 12731 return false; 12732 } 12733 12734 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12735 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12736 Expr *E = FD->getInClassInitializer(); 12737 if (!E) 12738 // FIXME: It's a little wasteful to build and throw away a 12739 // CXXDefaultInitExpr here. 12740 // FIXME: We should have a single context note pointing at Loc, and 12741 // this location should be MD->getLocation() instead, since that's 12742 // the location where we actually use the default init expression. 12743 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12744 if (E) 12745 ExceptSpec.CalledExpr(E); 12746 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12747 ->getAs<RecordType>()) { 12748 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12749 FD->getType().getCVRQualifiers()); 12750 } 12751 return false; 12752 } 12753 12754 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12755 Subobject Subobj, 12756 unsigned Quals) { 12757 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12758 bool IsMutable = Field && Field->isMutable(); 12759 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12760 } 12761 12762 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12763 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12764 // Note, if lookup fails, it doesn't matter what exception specification we 12765 // choose because the special member will be deleted. 12766 if (CXXMethodDecl *MD = SMOR.getMethod()) 12767 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12768 } 12769 12770 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12771 llvm::APSInt Result; 12772 ExprResult Converted = CheckConvertedConstantExpression( 12773 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12774 ExplicitSpec.setExpr(Converted.get()); 12775 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12776 ExplicitSpec.setKind(Result.getBoolValue() 12777 ? ExplicitSpecKind::ResolvedTrue 12778 : ExplicitSpecKind::ResolvedFalse); 12779 return true; 12780 } 12781 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12782 return false; 12783 } 12784 12785 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12786 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12787 if (!ExplicitExpr->isTypeDependent()) 12788 tryResolveExplicitSpecifier(ES); 12789 return ES; 12790 } 12791 12792 static Sema::ImplicitExceptionSpecification 12793 ComputeDefaultedSpecialMemberExceptionSpec( 12794 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12795 Sema::InheritedConstructorInfo *ICI) { 12796 ComputingExceptionSpec CES(S, MD, Loc); 12797 12798 CXXRecordDecl *ClassDecl = MD->getParent(); 12799 12800 // C++ [except.spec]p14: 12801 // An implicitly declared special member function (Clause 12) shall have an 12802 // exception-specification. [...] 12803 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12804 if (ClassDecl->isInvalidDecl()) 12805 return Info.ExceptSpec; 12806 12807 // FIXME: If this diagnostic fires, we're probably missing a check for 12808 // attempting to resolve an exception specification before it's known 12809 // at a higher level. 12810 if (S.RequireCompleteType(MD->getLocation(), 12811 S.Context.getRecordType(ClassDecl), 12812 diag::err_exception_spec_incomplete_type)) 12813 return Info.ExceptSpec; 12814 12815 // C++1z [except.spec]p7: 12816 // [Look for exceptions thrown by] a constructor selected [...] to 12817 // initialize a potentially constructed subobject, 12818 // C++1z [except.spec]p8: 12819 // The exception specification for an implicitly-declared destructor, or a 12820 // destructor without a noexcept-specifier, is potentially-throwing if and 12821 // only if any of the destructors for any of its potentially constructed 12822 // subojects is potentially throwing. 12823 // FIXME: We respect the first rule but ignore the "potentially constructed" 12824 // in the second rule to resolve a core issue (no number yet) that would have 12825 // us reject: 12826 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12827 // struct B : A {}; 12828 // struct C : B { void f(); }; 12829 // ... due to giving B::~B() a non-throwing exception specification. 12830 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12831 : Info.VisitAllBases); 12832 12833 return Info.ExceptSpec; 12834 } 12835 12836 namespace { 12837 /// RAII object to register a special member as being currently declared. 12838 struct DeclaringSpecialMember { 12839 Sema &S; 12840 Sema::SpecialMemberDecl D; 12841 Sema::ContextRAII SavedContext; 12842 bool WasAlreadyBeingDeclared; 12843 12844 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12845 : S(S), D(RD, CSM), SavedContext(S, RD) { 12846 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12847 if (WasAlreadyBeingDeclared) 12848 // This almost never happens, but if it does, ensure that our cache 12849 // doesn't contain a stale result. 12850 S.SpecialMemberCache.clear(); 12851 else { 12852 // Register a note to be produced if we encounter an error while 12853 // declaring the special member. 12854 Sema::CodeSynthesisContext Ctx; 12855 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12856 // FIXME: We don't have a location to use here. Using the class's 12857 // location maintains the fiction that we declare all special members 12858 // with the class, but (1) it's not clear that lying about that helps our 12859 // users understand what's going on, and (2) there may be outer contexts 12860 // on the stack (some of which are relevant) and printing them exposes 12861 // our lies. 12862 Ctx.PointOfInstantiation = RD->getLocation(); 12863 Ctx.Entity = RD; 12864 Ctx.SpecialMember = CSM; 12865 S.pushCodeSynthesisContext(Ctx); 12866 } 12867 } 12868 ~DeclaringSpecialMember() { 12869 if (!WasAlreadyBeingDeclared) { 12870 S.SpecialMembersBeingDeclared.erase(D); 12871 S.popCodeSynthesisContext(); 12872 } 12873 } 12874 12875 /// Are we already trying to declare this special member? 12876 bool isAlreadyBeingDeclared() const { 12877 return WasAlreadyBeingDeclared; 12878 } 12879 }; 12880 } 12881 12882 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12883 // Look up any existing declarations, but don't trigger declaration of all 12884 // implicit special members with this name. 12885 DeclarationName Name = FD->getDeclName(); 12886 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12887 ForExternalRedeclaration); 12888 for (auto *D : FD->getParent()->lookup(Name)) 12889 if (auto *Acceptable = R.getAcceptableDecl(D)) 12890 R.addDecl(Acceptable); 12891 R.resolveKind(); 12892 R.suppressDiagnostics(); 12893 12894 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12895 } 12896 12897 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12898 QualType ResultTy, 12899 ArrayRef<QualType> Args) { 12900 // Build an exception specification pointing back at this constructor. 12901 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12902 12903 LangAS AS = getDefaultCXXMethodAddrSpace(); 12904 if (AS != LangAS::Default) { 12905 EPI.TypeQuals.addAddressSpace(AS); 12906 } 12907 12908 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12909 SpecialMem->setType(QT); 12910 } 12911 12912 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12913 CXXRecordDecl *ClassDecl) { 12914 // C++ [class.ctor]p5: 12915 // A default constructor for a class X is a constructor of class X 12916 // that can be called without an argument. If there is no 12917 // user-declared constructor for class X, a default constructor is 12918 // implicitly declared. An implicitly-declared default constructor 12919 // is an inline public member of its class. 12920 assert(ClassDecl->needsImplicitDefaultConstructor() && 12921 "Should not build implicit default constructor!"); 12922 12923 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12924 if (DSM.isAlreadyBeingDeclared()) 12925 return nullptr; 12926 12927 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12928 CXXDefaultConstructor, 12929 false); 12930 12931 // Create the actual constructor declaration. 12932 CanQualType ClassType 12933 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12934 SourceLocation ClassLoc = ClassDecl->getLocation(); 12935 DeclarationName Name 12936 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12937 DeclarationNameInfo NameInfo(Name, ClassLoc); 12938 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12939 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12940 /*TInfo=*/nullptr, ExplicitSpecifier(), 12941 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12942 Constexpr ? CSK_constexpr : CSK_unspecified); 12943 DefaultCon->setAccess(AS_public); 12944 DefaultCon->setDefaulted(); 12945 12946 if (getLangOpts().CUDA) { 12947 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 12948 DefaultCon, 12949 /* ConstRHS */ false, 12950 /* Diagnose */ false); 12951 } 12952 12953 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 12954 12955 // We don't need to use SpecialMemberIsTrivial here; triviality for default 12956 // constructors is easy to compute. 12957 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 12958 12959 // Note that we have declared this constructor. 12960 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 12961 12962 Scope *S = getScopeForContext(ClassDecl); 12963 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 12964 12965 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 12966 SetDeclDeleted(DefaultCon, ClassLoc); 12967 12968 if (S) 12969 PushOnScopeChains(DefaultCon, S, false); 12970 ClassDecl->addDecl(DefaultCon); 12971 12972 return DefaultCon; 12973 } 12974 12975 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 12976 CXXConstructorDecl *Constructor) { 12977 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 12978 !Constructor->doesThisDeclarationHaveABody() && 12979 !Constructor->isDeleted()) && 12980 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 12981 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12982 return; 12983 12984 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12985 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 12986 12987 SynthesizedFunctionScope Scope(*this, Constructor); 12988 12989 // The exception specification is needed because we are defining the 12990 // function. 12991 ResolveExceptionSpec(CurrentLocation, 12992 Constructor->getType()->castAs<FunctionProtoType>()); 12993 MarkVTableUsed(CurrentLocation, ClassDecl); 12994 12995 // Add a context note for diagnostics produced after this point. 12996 Scope.addContextNote(CurrentLocation); 12997 12998 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 12999 Constructor->setInvalidDecl(); 13000 return; 13001 } 13002 13003 SourceLocation Loc = Constructor->getEndLoc().isValid() 13004 ? Constructor->getEndLoc() 13005 : Constructor->getLocation(); 13006 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13007 Constructor->markUsed(Context); 13008 13009 if (ASTMutationListener *L = getASTMutationListener()) { 13010 L->CompletedImplicitDefinition(Constructor); 13011 } 13012 13013 DiagnoseUninitializedFields(*this, Constructor); 13014 } 13015 13016 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13017 // Perform any delayed checks on exception specifications. 13018 CheckDelayedMemberExceptionSpecs(); 13019 } 13020 13021 /// Find or create the fake constructor we synthesize to model constructing an 13022 /// object of a derived class via a constructor of a base class. 13023 CXXConstructorDecl * 13024 Sema::findInheritingConstructor(SourceLocation Loc, 13025 CXXConstructorDecl *BaseCtor, 13026 ConstructorUsingShadowDecl *Shadow) { 13027 CXXRecordDecl *Derived = Shadow->getParent(); 13028 SourceLocation UsingLoc = Shadow->getLocation(); 13029 13030 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13031 // For now we use the name of the base class constructor as a member of the 13032 // derived class to indicate a (fake) inherited constructor name. 13033 DeclarationName Name = BaseCtor->getDeclName(); 13034 13035 // Check to see if we already have a fake constructor for this inherited 13036 // constructor call. 13037 for (NamedDecl *Ctor : Derived->lookup(Name)) 13038 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13039 ->getInheritedConstructor() 13040 .getConstructor(), 13041 BaseCtor)) 13042 return cast<CXXConstructorDecl>(Ctor); 13043 13044 DeclarationNameInfo NameInfo(Name, UsingLoc); 13045 TypeSourceInfo *TInfo = 13046 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13047 FunctionProtoTypeLoc ProtoLoc = 13048 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13049 13050 // Check the inherited constructor is valid and find the list of base classes 13051 // from which it was inherited. 13052 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13053 13054 bool Constexpr = 13055 BaseCtor->isConstexpr() && 13056 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13057 false, BaseCtor, &ICI); 13058 13059 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13060 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13061 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13062 /*isImplicitlyDeclared=*/true, 13063 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 13064 InheritedConstructor(Shadow, BaseCtor), 13065 BaseCtor->getTrailingRequiresClause()); 13066 if (Shadow->isInvalidDecl()) 13067 DerivedCtor->setInvalidDecl(); 13068 13069 // Build an unevaluated exception specification for this fake constructor. 13070 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13071 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13072 EPI.ExceptionSpec.Type = EST_Unevaluated; 13073 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13074 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13075 FPT->getParamTypes(), EPI)); 13076 13077 // Build the parameter declarations. 13078 SmallVector<ParmVarDecl *, 16> ParamDecls; 13079 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13080 TypeSourceInfo *TInfo = 13081 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13082 ParmVarDecl *PD = ParmVarDecl::Create( 13083 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13084 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13085 PD->setScopeInfo(0, I); 13086 PD->setImplicit(); 13087 // Ensure attributes are propagated onto parameters (this matters for 13088 // format, pass_object_size, ...). 13089 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13090 ParamDecls.push_back(PD); 13091 ProtoLoc.setParam(I, PD); 13092 } 13093 13094 // Set up the new constructor. 13095 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13096 DerivedCtor->setAccess(BaseCtor->getAccess()); 13097 DerivedCtor->setParams(ParamDecls); 13098 Derived->addDecl(DerivedCtor); 13099 13100 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13101 SetDeclDeleted(DerivedCtor, UsingLoc); 13102 13103 return DerivedCtor; 13104 } 13105 13106 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13107 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13108 Ctor->getInheritedConstructor().getShadowDecl()); 13109 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13110 /*Diagnose*/true); 13111 } 13112 13113 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13114 CXXConstructorDecl *Constructor) { 13115 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13116 assert(Constructor->getInheritedConstructor() && 13117 !Constructor->doesThisDeclarationHaveABody() && 13118 !Constructor->isDeleted()); 13119 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13120 return; 13121 13122 // Initializations are performed "as if by a defaulted default constructor", 13123 // so enter the appropriate scope. 13124 SynthesizedFunctionScope Scope(*this, Constructor); 13125 13126 // The exception specification is needed because we are defining the 13127 // function. 13128 ResolveExceptionSpec(CurrentLocation, 13129 Constructor->getType()->castAs<FunctionProtoType>()); 13130 MarkVTableUsed(CurrentLocation, ClassDecl); 13131 13132 // Add a context note for diagnostics produced after this point. 13133 Scope.addContextNote(CurrentLocation); 13134 13135 ConstructorUsingShadowDecl *Shadow = 13136 Constructor->getInheritedConstructor().getShadowDecl(); 13137 CXXConstructorDecl *InheritedCtor = 13138 Constructor->getInheritedConstructor().getConstructor(); 13139 13140 // [class.inhctor.init]p1: 13141 // initialization proceeds as if a defaulted default constructor is used to 13142 // initialize the D object and each base class subobject from which the 13143 // constructor was inherited 13144 13145 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13146 CXXRecordDecl *RD = Shadow->getParent(); 13147 SourceLocation InitLoc = Shadow->getLocation(); 13148 13149 // Build explicit initializers for all base classes from which the 13150 // constructor was inherited. 13151 SmallVector<CXXCtorInitializer*, 8> Inits; 13152 for (bool VBase : {false, true}) { 13153 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13154 if (B.isVirtual() != VBase) 13155 continue; 13156 13157 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13158 if (!BaseRD) 13159 continue; 13160 13161 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13162 if (!BaseCtor.first) 13163 continue; 13164 13165 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13166 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13167 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13168 13169 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13170 Inits.push_back(new (Context) CXXCtorInitializer( 13171 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13172 SourceLocation())); 13173 } 13174 } 13175 13176 // We now proceed as if for a defaulted default constructor, with the relevant 13177 // initializers replaced. 13178 13179 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13180 Constructor->setInvalidDecl(); 13181 return; 13182 } 13183 13184 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13185 Constructor->markUsed(Context); 13186 13187 if (ASTMutationListener *L = getASTMutationListener()) { 13188 L->CompletedImplicitDefinition(Constructor); 13189 } 13190 13191 DiagnoseUninitializedFields(*this, Constructor); 13192 } 13193 13194 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13195 // C++ [class.dtor]p2: 13196 // If a class has no user-declared destructor, a destructor is 13197 // declared implicitly. An implicitly-declared destructor is an 13198 // inline public member of its class. 13199 assert(ClassDecl->needsImplicitDestructor()); 13200 13201 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13202 if (DSM.isAlreadyBeingDeclared()) 13203 return nullptr; 13204 13205 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13206 CXXDestructor, 13207 false); 13208 13209 // Create the actual destructor declaration. 13210 CanQualType ClassType 13211 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13212 SourceLocation ClassLoc = ClassDecl->getLocation(); 13213 DeclarationName Name 13214 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13215 DeclarationNameInfo NameInfo(Name, ClassLoc); 13216 CXXDestructorDecl *Destructor = 13217 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13218 QualType(), nullptr, /*isInline=*/true, 13219 /*isImplicitlyDeclared=*/true, 13220 Constexpr ? CSK_constexpr : CSK_unspecified); 13221 Destructor->setAccess(AS_public); 13222 Destructor->setDefaulted(); 13223 13224 if (getLangOpts().CUDA) { 13225 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13226 Destructor, 13227 /* ConstRHS */ false, 13228 /* Diagnose */ false); 13229 } 13230 13231 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13232 13233 // We don't need to use SpecialMemberIsTrivial here; triviality for 13234 // destructors is easy to compute. 13235 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13236 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13237 ClassDecl->hasTrivialDestructorForCall()); 13238 13239 // Note that we have declared this destructor. 13240 ++getASTContext().NumImplicitDestructorsDeclared; 13241 13242 Scope *S = getScopeForContext(ClassDecl); 13243 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13244 13245 // We can't check whether an implicit destructor is deleted before we complete 13246 // the definition of the class, because its validity depends on the alignment 13247 // of the class. We'll check this from ActOnFields once the class is complete. 13248 if (ClassDecl->isCompleteDefinition() && 13249 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13250 SetDeclDeleted(Destructor, ClassLoc); 13251 13252 // Introduce this destructor into its scope. 13253 if (S) 13254 PushOnScopeChains(Destructor, S, false); 13255 ClassDecl->addDecl(Destructor); 13256 13257 return Destructor; 13258 } 13259 13260 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13261 CXXDestructorDecl *Destructor) { 13262 assert((Destructor->isDefaulted() && 13263 !Destructor->doesThisDeclarationHaveABody() && 13264 !Destructor->isDeleted()) && 13265 "DefineImplicitDestructor - call it for implicit default dtor"); 13266 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13267 return; 13268 13269 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13270 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13271 13272 SynthesizedFunctionScope Scope(*this, Destructor); 13273 13274 // The exception specification is needed because we are defining the 13275 // function. 13276 ResolveExceptionSpec(CurrentLocation, 13277 Destructor->getType()->castAs<FunctionProtoType>()); 13278 MarkVTableUsed(CurrentLocation, ClassDecl); 13279 13280 // Add a context note for diagnostics produced after this point. 13281 Scope.addContextNote(CurrentLocation); 13282 13283 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13284 Destructor->getParent()); 13285 13286 if (CheckDestructor(Destructor)) { 13287 Destructor->setInvalidDecl(); 13288 return; 13289 } 13290 13291 SourceLocation Loc = Destructor->getEndLoc().isValid() 13292 ? Destructor->getEndLoc() 13293 : Destructor->getLocation(); 13294 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13295 Destructor->markUsed(Context); 13296 13297 if (ASTMutationListener *L = getASTMutationListener()) { 13298 L->CompletedImplicitDefinition(Destructor); 13299 } 13300 } 13301 13302 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13303 CXXDestructorDecl *Destructor) { 13304 if (Destructor->isInvalidDecl()) 13305 return; 13306 13307 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13308 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13309 "implicit complete dtors unneeded outside MS ABI"); 13310 assert(ClassDecl->getNumVBases() > 0 && 13311 "complete dtor only exists for classes with vbases"); 13312 13313 SynthesizedFunctionScope Scope(*this, Destructor); 13314 13315 // Add a context note for diagnostics produced after this point. 13316 Scope.addContextNote(CurrentLocation); 13317 13318 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13319 } 13320 13321 /// Perform any semantic analysis which needs to be delayed until all 13322 /// pending class member declarations have been parsed. 13323 void Sema::ActOnFinishCXXMemberDecls() { 13324 // If the context is an invalid C++ class, just suppress these checks. 13325 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13326 if (Record->isInvalidDecl()) { 13327 DelayedOverridingExceptionSpecChecks.clear(); 13328 DelayedEquivalentExceptionSpecChecks.clear(); 13329 return; 13330 } 13331 checkForMultipleExportedDefaultConstructors(*this, Record); 13332 } 13333 } 13334 13335 void Sema::ActOnFinishCXXNonNestedClass() { 13336 referenceDLLExportedClassMethods(); 13337 13338 if (!DelayedDllExportMemberFunctions.empty()) { 13339 SmallVector<CXXMethodDecl*, 4> WorkList; 13340 std::swap(DelayedDllExportMemberFunctions, WorkList); 13341 for (CXXMethodDecl *M : WorkList) { 13342 DefineDefaultedFunction(*this, M, M->getLocation()); 13343 13344 // Pass the method to the consumer to get emitted. This is not necessary 13345 // for explicit instantiation definitions, as they will get emitted 13346 // anyway. 13347 if (M->getParent()->getTemplateSpecializationKind() != 13348 TSK_ExplicitInstantiationDefinition) 13349 ActOnFinishInlineFunctionDef(M); 13350 } 13351 } 13352 } 13353 13354 void Sema::referenceDLLExportedClassMethods() { 13355 if (!DelayedDllExportClasses.empty()) { 13356 // Calling ReferenceDllExportedMembers might cause the current function to 13357 // be called again, so use a local copy of DelayedDllExportClasses. 13358 SmallVector<CXXRecordDecl *, 4> WorkList; 13359 std::swap(DelayedDllExportClasses, WorkList); 13360 for (CXXRecordDecl *Class : WorkList) 13361 ReferenceDllExportedMembers(*this, Class); 13362 } 13363 } 13364 13365 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13366 assert(getLangOpts().CPlusPlus11 && 13367 "adjusting dtor exception specs was introduced in c++11"); 13368 13369 if (Destructor->isDependentContext()) 13370 return; 13371 13372 // C++11 [class.dtor]p3: 13373 // A declaration of a destructor that does not have an exception- 13374 // specification is implicitly considered to have the same exception- 13375 // specification as an implicit declaration. 13376 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13377 if (DtorType->hasExceptionSpec()) 13378 return; 13379 13380 // Replace the destructor's type, building off the existing one. Fortunately, 13381 // the only thing of interest in the destructor type is its extended info. 13382 // The return and arguments are fixed. 13383 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13384 EPI.ExceptionSpec.Type = EST_Unevaluated; 13385 EPI.ExceptionSpec.SourceDecl = Destructor; 13386 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13387 13388 // FIXME: If the destructor has a body that could throw, and the newly created 13389 // spec doesn't allow exceptions, we should emit a warning, because this 13390 // change in behavior can break conforming C++03 programs at runtime. 13391 // However, we don't have a body or an exception specification yet, so it 13392 // needs to be done somewhere else. 13393 } 13394 13395 namespace { 13396 /// An abstract base class for all helper classes used in building the 13397 // copy/move operators. These classes serve as factory functions and help us 13398 // avoid using the same Expr* in the AST twice. 13399 class ExprBuilder { 13400 ExprBuilder(const ExprBuilder&) = delete; 13401 ExprBuilder &operator=(const ExprBuilder&) = delete; 13402 13403 protected: 13404 static Expr *assertNotNull(Expr *E) { 13405 assert(E && "Expression construction must not fail."); 13406 return E; 13407 } 13408 13409 public: 13410 ExprBuilder() {} 13411 virtual ~ExprBuilder() {} 13412 13413 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13414 }; 13415 13416 class RefBuilder: public ExprBuilder { 13417 VarDecl *Var; 13418 QualType VarType; 13419 13420 public: 13421 Expr *build(Sema &S, SourceLocation Loc) const override { 13422 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13423 } 13424 13425 RefBuilder(VarDecl *Var, QualType VarType) 13426 : Var(Var), VarType(VarType) {} 13427 }; 13428 13429 class ThisBuilder: public ExprBuilder { 13430 public: 13431 Expr *build(Sema &S, SourceLocation Loc) const override { 13432 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13433 } 13434 }; 13435 13436 class CastBuilder: public ExprBuilder { 13437 const ExprBuilder &Builder; 13438 QualType Type; 13439 ExprValueKind Kind; 13440 const CXXCastPath &Path; 13441 13442 public: 13443 Expr *build(Sema &S, SourceLocation Loc) const override { 13444 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13445 CK_UncheckedDerivedToBase, Kind, 13446 &Path).get()); 13447 } 13448 13449 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13450 const CXXCastPath &Path) 13451 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13452 }; 13453 13454 class DerefBuilder: public ExprBuilder { 13455 const ExprBuilder &Builder; 13456 13457 public: 13458 Expr *build(Sema &S, SourceLocation Loc) const override { 13459 return assertNotNull( 13460 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13461 } 13462 13463 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13464 }; 13465 13466 class MemberBuilder: public ExprBuilder { 13467 const ExprBuilder &Builder; 13468 QualType Type; 13469 CXXScopeSpec SS; 13470 bool IsArrow; 13471 LookupResult &MemberLookup; 13472 13473 public: 13474 Expr *build(Sema &S, SourceLocation Loc) const override { 13475 return assertNotNull(S.BuildMemberReferenceExpr( 13476 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13477 nullptr, MemberLookup, nullptr, nullptr).get()); 13478 } 13479 13480 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13481 LookupResult &MemberLookup) 13482 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13483 MemberLookup(MemberLookup) {} 13484 }; 13485 13486 class MoveCastBuilder: public ExprBuilder { 13487 const ExprBuilder &Builder; 13488 13489 public: 13490 Expr *build(Sema &S, SourceLocation Loc) const override { 13491 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13492 } 13493 13494 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13495 }; 13496 13497 class LvalueConvBuilder: public ExprBuilder { 13498 const ExprBuilder &Builder; 13499 13500 public: 13501 Expr *build(Sema &S, SourceLocation Loc) const override { 13502 return assertNotNull( 13503 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13504 } 13505 13506 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13507 }; 13508 13509 class SubscriptBuilder: public ExprBuilder { 13510 const ExprBuilder &Base; 13511 const ExprBuilder &Index; 13512 13513 public: 13514 Expr *build(Sema &S, SourceLocation Loc) const override { 13515 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13516 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13517 } 13518 13519 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13520 : Base(Base), Index(Index) {} 13521 }; 13522 13523 } // end anonymous namespace 13524 13525 /// When generating a defaulted copy or move assignment operator, if a field 13526 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13527 /// do so. This optimization only applies for arrays of scalars, and for arrays 13528 /// of class type where the selected copy/move-assignment operator is trivial. 13529 static StmtResult 13530 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13531 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13532 // Compute the size of the memory buffer to be copied. 13533 QualType SizeType = S.Context.getSizeType(); 13534 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13535 S.Context.getTypeSizeInChars(T).getQuantity()); 13536 13537 // Take the address of the field references for "from" and "to". We 13538 // directly construct UnaryOperators here because semantic analysis 13539 // does not permit us to take the address of an xvalue. 13540 Expr *From = FromB.build(S, Loc); 13541 From = UnaryOperator::Create( 13542 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13543 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13544 Expr *To = ToB.build(S, Loc); 13545 To = UnaryOperator::Create( 13546 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13547 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13548 13549 const Type *E = T->getBaseElementTypeUnsafe(); 13550 bool NeedsCollectableMemCpy = 13551 E->isRecordType() && 13552 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13553 13554 // Create a reference to the __builtin_objc_memmove_collectable function 13555 StringRef MemCpyName = NeedsCollectableMemCpy ? 13556 "__builtin_objc_memmove_collectable" : 13557 "__builtin_memcpy"; 13558 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13559 Sema::LookupOrdinaryName); 13560 S.LookupName(R, S.TUScope, true); 13561 13562 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13563 if (!MemCpy) 13564 // Something went horribly wrong earlier, and we will have complained 13565 // about it. 13566 return StmtError(); 13567 13568 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13569 VK_RValue, Loc, nullptr); 13570 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13571 13572 Expr *CallArgs[] = { 13573 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13574 }; 13575 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13576 Loc, CallArgs, Loc); 13577 13578 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13579 return Call.getAs<Stmt>(); 13580 } 13581 13582 /// Builds a statement that copies/moves the given entity from \p From to 13583 /// \c To. 13584 /// 13585 /// This routine is used to copy/move the members of a class with an 13586 /// implicitly-declared copy/move assignment operator. When the entities being 13587 /// copied are arrays, this routine builds for loops to copy them. 13588 /// 13589 /// \param S The Sema object used for type-checking. 13590 /// 13591 /// \param Loc The location where the implicit copy/move is being generated. 13592 /// 13593 /// \param T The type of the expressions being copied/moved. Both expressions 13594 /// must have this type. 13595 /// 13596 /// \param To The expression we are copying/moving to. 13597 /// 13598 /// \param From The expression we are copying/moving from. 13599 /// 13600 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13601 /// Otherwise, it's a non-static member subobject. 13602 /// 13603 /// \param Copying Whether we're copying or moving. 13604 /// 13605 /// \param Depth Internal parameter recording the depth of the recursion. 13606 /// 13607 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13608 /// if a memcpy should be used instead. 13609 static StmtResult 13610 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13611 const ExprBuilder &To, const ExprBuilder &From, 13612 bool CopyingBaseSubobject, bool Copying, 13613 unsigned Depth = 0) { 13614 // C++11 [class.copy]p28: 13615 // Each subobject is assigned in the manner appropriate to its type: 13616 // 13617 // - if the subobject is of class type, as if by a call to operator= with 13618 // the subobject as the object expression and the corresponding 13619 // subobject of x as a single function argument (as if by explicit 13620 // qualification; that is, ignoring any possible virtual overriding 13621 // functions in more derived classes); 13622 // 13623 // C++03 [class.copy]p13: 13624 // - if the subobject is of class type, the copy assignment operator for 13625 // the class is used (as if by explicit qualification; that is, 13626 // ignoring any possible virtual overriding functions in more derived 13627 // classes); 13628 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13629 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13630 13631 // Look for operator=. 13632 DeclarationName Name 13633 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13634 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13635 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13636 13637 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13638 // operator. 13639 if (!S.getLangOpts().CPlusPlus11) { 13640 LookupResult::Filter F = OpLookup.makeFilter(); 13641 while (F.hasNext()) { 13642 NamedDecl *D = F.next(); 13643 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13644 if (Method->isCopyAssignmentOperator() || 13645 (!Copying && Method->isMoveAssignmentOperator())) 13646 continue; 13647 13648 F.erase(); 13649 } 13650 F.done(); 13651 } 13652 13653 // Suppress the protected check (C++ [class.protected]) for each of the 13654 // assignment operators we found. This strange dance is required when 13655 // we're assigning via a base classes's copy-assignment operator. To 13656 // ensure that we're getting the right base class subobject (without 13657 // ambiguities), we need to cast "this" to that subobject type; to 13658 // ensure that we don't go through the virtual call mechanism, we need 13659 // to qualify the operator= name with the base class (see below). However, 13660 // this means that if the base class has a protected copy assignment 13661 // operator, the protected member access check will fail. So, we 13662 // rewrite "protected" access to "public" access in this case, since we 13663 // know by construction that we're calling from a derived class. 13664 if (CopyingBaseSubobject) { 13665 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13666 L != LEnd; ++L) { 13667 if (L.getAccess() == AS_protected) 13668 L.setAccess(AS_public); 13669 } 13670 } 13671 13672 // Create the nested-name-specifier that will be used to qualify the 13673 // reference to operator=; this is required to suppress the virtual 13674 // call mechanism. 13675 CXXScopeSpec SS; 13676 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13677 SS.MakeTrivial(S.Context, 13678 NestedNameSpecifier::Create(S.Context, nullptr, false, 13679 CanonicalT), 13680 Loc); 13681 13682 // Create the reference to operator=. 13683 ExprResult OpEqualRef 13684 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13685 SS, /*TemplateKWLoc=*/SourceLocation(), 13686 /*FirstQualifierInScope=*/nullptr, 13687 OpLookup, 13688 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13689 /*SuppressQualifierCheck=*/true); 13690 if (OpEqualRef.isInvalid()) 13691 return StmtError(); 13692 13693 // Build the call to the assignment operator. 13694 13695 Expr *FromInst = From.build(S, Loc); 13696 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13697 OpEqualRef.getAs<Expr>(), 13698 Loc, FromInst, Loc); 13699 if (Call.isInvalid()) 13700 return StmtError(); 13701 13702 // If we built a call to a trivial 'operator=' while copying an array, 13703 // bail out. We'll replace the whole shebang with a memcpy. 13704 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13705 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13706 return StmtResult((Stmt*)nullptr); 13707 13708 // Convert to an expression-statement, and clean up any produced 13709 // temporaries. 13710 return S.ActOnExprStmt(Call); 13711 } 13712 13713 // - if the subobject is of scalar type, the built-in assignment 13714 // operator is used. 13715 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13716 if (!ArrayTy) { 13717 ExprResult Assignment = S.CreateBuiltinBinOp( 13718 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13719 if (Assignment.isInvalid()) 13720 return StmtError(); 13721 return S.ActOnExprStmt(Assignment); 13722 } 13723 13724 // - if the subobject is an array, each element is assigned, in the 13725 // manner appropriate to the element type; 13726 13727 // Construct a loop over the array bounds, e.g., 13728 // 13729 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13730 // 13731 // that will copy each of the array elements. 13732 QualType SizeType = S.Context.getSizeType(); 13733 13734 // Create the iteration variable. 13735 IdentifierInfo *IterationVarName = nullptr; 13736 { 13737 SmallString<8> Str; 13738 llvm::raw_svector_ostream OS(Str); 13739 OS << "__i" << Depth; 13740 IterationVarName = &S.Context.Idents.get(OS.str()); 13741 } 13742 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13743 IterationVarName, SizeType, 13744 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13745 SC_None); 13746 13747 // Initialize the iteration variable to zero. 13748 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13749 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13750 13751 // Creates a reference to the iteration variable. 13752 RefBuilder IterationVarRef(IterationVar, SizeType); 13753 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13754 13755 // Create the DeclStmt that holds the iteration variable. 13756 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13757 13758 // Subscript the "from" and "to" expressions with the iteration variable. 13759 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13760 MoveCastBuilder FromIndexMove(FromIndexCopy); 13761 const ExprBuilder *FromIndex; 13762 if (Copying) 13763 FromIndex = &FromIndexCopy; 13764 else 13765 FromIndex = &FromIndexMove; 13766 13767 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13768 13769 // Build the copy/move for an individual element of the array. 13770 StmtResult Copy = 13771 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13772 ToIndex, *FromIndex, CopyingBaseSubobject, 13773 Copying, Depth + 1); 13774 // Bail out if copying fails or if we determined that we should use memcpy. 13775 if (Copy.isInvalid() || !Copy.get()) 13776 return Copy; 13777 13778 // Create the comparison against the array bound. 13779 llvm::APInt Upper 13780 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13781 Expr *Comparison = BinaryOperator::Create( 13782 S.Context, IterationVarRefRVal.build(S, Loc), 13783 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13784 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides()); 13785 13786 // Create the pre-increment of the iteration variable. We can determine 13787 // whether the increment will overflow based on the value of the array 13788 // bound. 13789 Expr *Increment = UnaryOperator::Create( 13790 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13791 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 13792 13793 // Construct the loop that copies all elements of this array. 13794 return S.ActOnForStmt( 13795 Loc, Loc, InitStmt, 13796 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13797 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13798 } 13799 13800 static StmtResult 13801 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13802 const ExprBuilder &To, const ExprBuilder &From, 13803 bool CopyingBaseSubobject, bool Copying) { 13804 // Maybe we should use a memcpy? 13805 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13806 T.isTriviallyCopyableType(S.Context)) 13807 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13808 13809 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13810 CopyingBaseSubobject, 13811 Copying, 0)); 13812 13813 // If we ended up picking a trivial assignment operator for an array of a 13814 // non-trivially-copyable class type, just emit a memcpy. 13815 if (!Result.isInvalid() && !Result.get()) 13816 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13817 13818 return Result; 13819 } 13820 13821 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13822 // Note: The following rules are largely analoguous to the copy 13823 // constructor rules. Note that virtual bases are not taken into account 13824 // for determining the argument type of the operator. Note also that 13825 // operators taking an object instead of a reference are allowed. 13826 assert(ClassDecl->needsImplicitCopyAssignment()); 13827 13828 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13829 if (DSM.isAlreadyBeingDeclared()) 13830 return nullptr; 13831 13832 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13833 LangAS AS = getDefaultCXXMethodAddrSpace(); 13834 if (AS != LangAS::Default) 13835 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13836 QualType RetType = Context.getLValueReferenceType(ArgType); 13837 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13838 if (Const) 13839 ArgType = ArgType.withConst(); 13840 13841 ArgType = Context.getLValueReferenceType(ArgType); 13842 13843 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13844 CXXCopyAssignment, 13845 Const); 13846 13847 // An implicitly-declared copy assignment operator is an inline public 13848 // member of its class. 13849 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13850 SourceLocation ClassLoc = ClassDecl->getLocation(); 13851 DeclarationNameInfo NameInfo(Name, ClassLoc); 13852 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13853 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13854 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13855 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13856 SourceLocation()); 13857 CopyAssignment->setAccess(AS_public); 13858 CopyAssignment->setDefaulted(); 13859 CopyAssignment->setImplicit(); 13860 13861 if (getLangOpts().CUDA) { 13862 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13863 CopyAssignment, 13864 /* ConstRHS */ Const, 13865 /* Diagnose */ false); 13866 } 13867 13868 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13869 13870 // Add the parameter to the operator. 13871 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13872 ClassLoc, ClassLoc, 13873 /*Id=*/nullptr, ArgType, 13874 /*TInfo=*/nullptr, SC_None, 13875 nullptr); 13876 CopyAssignment->setParams(FromParam); 13877 13878 CopyAssignment->setTrivial( 13879 ClassDecl->needsOverloadResolutionForCopyAssignment() 13880 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13881 : ClassDecl->hasTrivialCopyAssignment()); 13882 13883 // Note that we have added this copy-assignment operator. 13884 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13885 13886 Scope *S = getScopeForContext(ClassDecl); 13887 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13888 13889 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 13890 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 13891 SetDeclDeleted(CopyAssignment, ClassLoc); 13892 } 13893 13894 if (S) 13895 PushOnScopeChains(CopyAssignment, S, false); 13896 ClassDecl->addDecl(CopyAssignment); 13897 13898 return CopyAssignment; 13899 } 13900 13901 /// Diagnose an implicit copy operation for a class which is odr-used, but 13902 /// which is deprecated because the class has a user-declared copy constructor, 13903 /// copy assignment operator, or destructor. 13904 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13905 assert(CopyOp->isImplicit()); 13906 13907 CXXRecordDecl *RD = CopyOp->getParent(); 13908 CXXMethodDecl *UserDeclaredOperation = nullptr; 13909 13910 // In Microsoft mode, assignment operations don't affect constructors and 13911 // vice versa. 13912 if (RD->hasUserDeclaredDestructor()) { 13913 UserDeclaredOperation = RD->getDestructor(); 13914 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13915 RD->hasUserDeclaredCopyConstructor() && 13916 !S.getLangOpts().MSVCCompat) { 13917 // Find any user-declared copy constructor. 13918 for (auto *I : RD->ctors()) { 13919 if (I->isCopyConstructor()) { 13920 UserDeclaredOperation = I; 13921 break; 13922 } 13923 } 13924 assert(UserDeclaredOperation); 13925 } else if (isa<CXXConstructorDecl>(CopyOp) && 13926 RD->hasUserDeclaredCopyAssignment() && 13927 !S.getLangOpts().MSVCCompat) { 13928 // Find any user-declared move assignment operator. 13929 for (auto *I : RD->methods()) { 13930 if (I->isCopyAssignmentOperator()) { 13931 UserDeclaredOperation = I; 13932 break; 13933 } 13934 } 13935 assert(UserDeclaredOperation); 13936 } 13937 13938 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13939 S.Diag(UserDeclaredOperation->getLocation(), 13940 isa<CXXDestructorDecl>(UserDeclaredOperation) 13941 ? diag::warn_deprecated_copy_dtor_operation 13942 : diag::warn_deprecated_copy_operation) 13943 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 13944 } 13945 } 13946 13947 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 13948 CXXMethodDecl *CopyAssignOperator) { 13949 assert((CopyAssignOperator->isDefaulted() && 13950 CopyAssignOperator->isOverloadedOperator() && 13951 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 13952 !CopyAssignOperator->doesThisDeclarationHaveABody() && 13953 !CopyAssignOperator->isDeleted()) && 13954 "DefineImplicitCopyAssignment called for wrong function"); 13955 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 13956 return; 13957 13958 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 13959 if (ClassDecl->isInvalidDecl()) { 13960 CopyAssignOperator->setInvalidDecl(); 13961 return; 13962 } 13963 13964 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 13965 13966 // The exception specification is needed because we are defining the 13967 // function. 13968 ResolveExceptionSpec(CurrentLocation, 13969 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 13970 13971 // Add a context note for diagnostics produced after this point. 13972 Scope.addContextNote(CurrentLocation); 13973 13974 // C++11 [class.copy]p18: 13975 // The [definition of an implicitly declared copy assignment operator] is 13976 // deprecated if the class has a user-declared copy constructor or a 13977 // user-declared destructor. 13978 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 13979 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 13980 13981 // C++0x [class.copy]p30: 13982 // The implicitly-defined or explicitly-defaulted copy assignment operator 13983 // for a non-union class X performs memberwise copy assignment of its 13984 // subobjects. The direct base classes of X are assigned first, in the 13985 // order of their declaration in the base-specifier-list, and then the 13986 // immediate non-static data members of X are assigned, in the order in 13987 // which they were declared in the class definition. 13988 13989 // The statements that form the synthesized function body. 13990 SmallVector<Stmt*, 8> Statements; 13991 13992 // The parameter for the "other" object, which we are copying from. 13993 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 13994 Qualifiers OtherQuals = Other->getType().getQualifiers(); 13995 QualType OtherRefType = Other->getType(); 13996 if (const LValueReferenceType *OtherRef 13997 = OtherRefType->getAs<LValueReferenceType>()) { 13998 OtherRefType = OtherRef->getPointeeType(); 13999 OtherQuals = OtherRefType.getQualifiers(); 14000 } 14001 14002 // Our location for everything implicitly-generated. 14003 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14004 ? CopyAssignOperator->getEndLoc() 14005 : CopyAssignOperator->getLocation(); 14006 14007 // Builds a DeclRefExpr for the "other" object. 14008 RefBuilder OtherRef(Other, OtherRefType); 14009 14010 // Builds the "this" pointer. 14011 ThisBuilder This; 14012 14013 // Assign base classes. 14014 bool Invalid = false; 14015 for (auto &Base : ClassDecl->bases()) { 14016 // Form the assignment: 14017 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14018 QualType BaseType = Base.getType().getUnqualifiedType(); 14019 if (!BaseType->isRecordType()) { 14020 Invalid = true; 14021 continue; 14022 } 14023 14024 CXXCastPath BasePath; 14025 BasePath.push_back(&Base); 14026 14027 // Construct the "from" expression, which is an implicit cast to the 14028 // appropriately-qualified base type. 14029 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14030 VK_LValue, BasePath); 14031 14032 // Dereference "this". 14033 DerefBuilder DerefThis(This); 14034 CastBuilder To(DerefThis, 14035 Context.getQualifiedType( 14036 BaseType, CopyAssignOperator->getMethodQualifiers()), 14037 VK_LValue, BasePath); 14038 14039 // Build the copy. 14040 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14041 To, From, 14042 /*CopyingBaseSubobject=*/true, 14043 /*Copying=*/true); 14044 if (Copy.isInvalid()) { 14045 CopyAssignOperator->setInvalidDecl(); 14046 return; 14047 } 14048 14049 // Success! Record the copy. 14050 Statements.push_back(Copy.getAs<Expr>()); 14051 } 14052 14053 // Assign non-static members. 14054 for (auto *Field : ClassDecl->fields()) { 14055 // FIXME: We should form some kind of AST representation for the implied 14056 // memcpy in a union copy operation. 14057 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14058 continue; 14059 14060 if (Field->isInvalidDecl()) { 14061 Invalid = true; 14062 continue; 14063 } 14064 14065 // Check for members of reference type; we can't copy those. 14066 if (Field->getType()->isReferenceType()) { 14067 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14068 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14069 Diag(Field->getLocation(), diag::note_declared_at); 14070 Invalid = true; 14071 continue; 14072 } 14073 14074 // Check for members of const-qualified, non-class type. 14075 QualType BaseType = Context.getBaseElementType(Field->getType()); 14076 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14077 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14078 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14079 Diag(Field->getLocation(), diag::note_declared_at); 14080 Invalid = true; 14081 continue; 14082 } 14083 14084 // Suppress assigning zero-width bitfields. 14085 if (Field->isZeroLengthBitField(Context)) 14086 continue; 14087 14088 QualType FieldType = Field->getType().getNonReferenceType(); 14089 if (FieldType->isIncompleteArrayType()) { 14090 assert(ClassDecl->hasFlexibleArrayMember() && 14091 "Incomplete array type is not valid"); 14092 continue; 14093 } 14094 14095 // Build references to the field in the object we're copying from and to. 14096 CXXScopeSpec SS; // Intentionally empty 14097 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14098 LookupMemberName); 14099 MemberLookup.addDecl(Field); 14100 MemberLookup.resolveKind(); 14101 14102 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14103 14104 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14105 14106 // Build the copy of this field. 14107 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14108 To, From, 14109 /*CopyingBaseSubobject=*/false, 14110 /*Copying=*/true); 14111 if (Copy.isInvalid()) { 14112 CopyAssignOperator->setInvalidDecl(); 14113 return; 14114 } 14115 14116 // Success! Record the copy. 14117 Statements.push_back(Copy.getAs<Stmt>()); 14118 } 14119 14120 if (!Invalid) { 14121 // Add a "return *this;" 14122 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14123 14124 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14125 if (Return.isInvalid()) 14126 Invalid = true; 14127 else 14128 Statements.push_back(Return.getAs<Stmt>()); 14129 } 14130 14131 if (Invalid) { 14132 CopyAssignOperator->setInvalidDecl(); 14133 return; 14134 } 14135 14136 StmtResult Body; 14137 { 14138 CompoundScopeRAII CompoundScope(*this); 14139 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14140 /*isStmtExpr=*/false); 14141 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14142 } 14143 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14144 CopyAssignOperator->markUsed(Context); 14145 14146 if (ASTMutationListener *L = getASTMutationListener()) { 14147 L->CompletedImplicitDefinition(CopyAssignOperator); 14148 } 14149 } 14150 14151 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14152 assert(ClassDecl->needsImplicitMoveAssignment()); 14153 14154 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14155 if (DSM.isAlreadyBeingDeclared()) 14156 return nullptr; 14157 14158 // Note: The following rules are largely analoguous to the move 14159 // constructor rules. 14160 14161 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14162 LangAS AS = getDefaultCXXMethodAddrSpace(); 14163 if (AS != LangAS::Default) 14164 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14165 QualType RetType = Context.getLValueReferenceType(ArgType); 14166 ArgType = Context.getRValueReferenceType(ArgType); 14167 14168 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14169 CXXMoveAssignment, 14170 false); 14171 14172 // An implicitly-declared move assignment operator is an inline public 14173 // member of its class. 14174 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14175 SourceLocation ClassLoc = ClassDecl->getLocation(); 14176 DeclarationNameInfo NameInfo(Name, ClassLoc); 14177 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14178 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14179 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14180 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 14181 SourceLocation()); 14182 MoveAssignment->setAccess(AS_public); 14183 MoveAssignment->setDefaulted(); 14184 MoveAssignment->setImplicit(); 14185 14186 if (getLangOpts().CUDA) { 14187 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14188 MoveAssignment, 14189 /* ConstRHS */ false, 14190 /* Diagnose */ false); 14191 } 14192 14193 // Build an exception specification pointing back at this member. 14194 FunctionProtoType::ExtProtoInfo EPI = 14195 getImplicitMethodEPI(*this, MoveAssignment); 14196 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14197 14198 // Add the parameter to the operator. 14199 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14200 ClassLoc, ClassLoc, 14201 /*Id=*/nullptr, ArgType, 14202 /*TInfo=*/nullptr, SC_None, 14203 nullptr); 14204 MoveAssignment->setParams(FromParam); 14205 14206 MoveAssignment->setTrivial( 14207 ClassDecl->needsOverloadResolutionForMoveAssignment() 14208 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14209 : ClassDecl->hasTrivialMoveAssignment()); 14210 14211 // Note that we have added this copy-assignment operator. 14212 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14213 14214 Scope *S = getScopeForContext(ClassDecl); 14215 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14216 14217 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14218 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14219 SetDeclDeleted(MoveAssignment, ClassLoc); 14220 } 14221 14222 if (S) 14223 PushOnScopeChains(MoveAssignment, S, false); 14224 ClassDecl->addDecl(MoveAssignment); 14225 14226 return MoveAssignment; 14227 } 14228 14229 /// Check if we're implicitly defining a move assignment operator for a class 14230 /// with virtual bases. Such a move assignment might move-assign the virtual 14231 /// base multiple times. 14232 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14233 SourceLocation CurrentLocation) { 14234 assert(!Class->isDependentContext() && "should not define dependent move"); 14235 14236 // Only a virtual base could get implicitly move-assigned multiple times. 14237 // Only a non-trivial move assignment can observe this. We only want to 14238 // diagnose if we implicitly define an assignment operator that assigns 14239 // two base classes, both of which move-assign the same virtual base. 14240 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14241 Class->getNumBases() < 2) 14242 return; 14243 14244 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14245 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14246 VBaseMap VBases; 14247 14248 for (auto &BI : Class->bases()) { 14249 Worklist.push_back(&BI); 14250 while (!Worklist.empty()) { 14251 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14252 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14253 14254 // If the base has no non-trivial move assignment operators, 14255 // we don't care about moves from it. 14256 if (!Base->hasNonTrivialMoveAssignment()) 14257 continue; 14258 14259 // If there's nothing virtual here, skip it. 14260 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14261 continue; 14262 14263 // If we're not actually going to call a move assignment for this base, 14264 // or the selected move assignment is trivial, skip it. 14265 Sema::SpecialMemberOverloadResult SMOR = 14266 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14267 /*ConstArg*/false, /*VolatileArg*/false, 14268 /*RValueThis*/true, /*ConstThis*/false, 14269 /*VolatileThis*/false); 14270 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14271 !SMOR.getMethod()->isMoveAssignmentOperator()) 14272 continue; 14273 14274 if (BaseSpec->isVirtual()) { 14275 // We're going to move-assign this virtual base, and its move 14276 // assignment operator is not trivial. If this can happen for 14277 // multiple distinct direct bases of Class, diagnose it. (If it 14278 // only happens in one base, we'll diagnose it when synthesizing 14279 // that base class's move assignment operator.) 14280 CXXBaseSpecifier *&Existing = 14281 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14282 .first->second; 14283 if (Existing && Existing != &BI) { 14284 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14285 << Class << Base; 14286 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14287 << (Base->getCanonicalDecl() == 14288 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14289 << Base << Existing->getType() << Existing->getSourceRange(); 14290 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14291 << (Base->getCanonicalDecl() == 14292 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14293 << Base << BI.getType() << BaseSpec->getSourceRange(); 14294 14295 // Only diagnose each vbase once. 14296 Existing = nullptr; 14297 } 14298 } else { 14299 // Only walk over bases that have defaulted move assignment operators. 14300 // We assume that any user-provided move assignment operator handles 14301 // the multiple-moves-of-vbase case itself somehow. 14302 if (!SMOR.getMethod()->isDefaulted()) 14303 continue; 14304 14305 // We're going to move the base classes of Base. Add them to the list. 14306 for (auto &BI : Base->bases()) 14307 Worklist.push_back(&BI); 14308 } 14309 } 14310 } 14311 } 14312 14313 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14314 CXXMethodDecl *MoveAssignOperator) { 14315 assert((MoveAssignOperator->isDefaulted() && 14316 MoveAssignOperator->isOverloadedOperator() && 14317 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14318 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14319 !MoveAssignOperator->isDeleted()) && 14320 "DefineImplicitMoveAssignment called for wrong function"); 14321 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14322 return; 14323 14324 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14325 if (ClassDecl->isInvalidDecl()) { 14326 MoveAssignOperator->setInvalidDecl(); 14327 return; 14328 } 14329 14330 // C++0x [class.copy]p28: 14331 // The implicitly-defined or move assignment operator for a non-union class 14332 // X performs memberwise move assignment of its subobjects. The direct base 14333 // classes of X are assigned first, in the order of their declaration in the 14334 // base-specifier-list, and then the immediate non-static data members of X 14335 // are assigned, in the order in which they were declared in the class 14336 // definition. 14337 14338 // Issue a warning if our implicit move assignment operator will move 14339 // from a virtual base more than once. 14340 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14341 14342 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14343 14344 // The exception specification is needed because we are defining the 14345 // function. 14346 ResolveExceptionSpec(CurrentLocation, 14347 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14348 14349 // Add a context note for diagnostics produced after this point. 14350 Scope.addContextNote(CurrentLocation); 14351 14352 // The statements that form the synthesized function body. 14353 SmallVector<Stmt*, 8> Statements; 14354 14355 // The parameter for the "other" object, which we are move from. 14356 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14357 QualType OtherRefType = 14358 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14359 14360 // Our location for everything implicitly-generated. 14361 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14362 ? MoveAssignOperator->getEndLoc() 14363 : MoveAssignOperator->getLocation(); 14364 14365 // Builds a reference to the "other" object. 14366 RefBuilder OtherRef(Other, OtherRefType); 14367 // Cast to rvalue. 14368 MoveCastBuilder MoveOther(OtherRef); 14369 14370 // Builds the "this" pointer. 14371 ThisBuilder This; 14372 14373 // Assign base classes. 14374 bool Invalid = false; 14375 for (auto &Base : ClassDecl->bases()) { 14376 // C++11 [class.copy]p28: 14377 // It is unspecified whether subobjects representing virtual base classes 14378 // are assigned more than once by the implicitly-defined copy assignment 14379 // operator. 14380 // FIXME: Do not assign to a vbase that will be assigned by some other base 14381 // class. For a move-assignment, this can result in the vbase being moved 14382 // multiple times. 14383 14384 // Form the assignment: 14385 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14386 QualType BaseType = Base.getType().getUnqualifiedType(); 14387 if (!BaseType->isRecordType()) { 14388 Invalid = true; 14389 continue; 14390 } 14391 14392 CXXCastPath BasePath; 14393 BasePath.push_back(&Base); 14394 14395 // Construct the "from" expression, which is an implicit cast to the 14396 // appropriately-qualified base type. 14397 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14398 14399 // Dereference "this". 14400 DerefBuilder DerefThis(This); 14401 14402 // Implicitly cast "this" to the appropriately-qualified base type. 14403 CastBuilder To(DerefThis, 14404 Context.getQualifiedType( 14405 BaseType, MoveAssignOperator->getMethodQualifiers()), 14406 VK_LValue, BasePath); 14407 14408 // Build the move. 14409 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14410 To, From, 14411 /*CopyingBaseSubobject=*/true, 14412 /*Copying=*/false); 14413 if (Move.isInvalid()) { 14414 MoveAssignOperator->setInvalidDecl(); 14415 return; 14416 } 14417 14418 // Success! Record the move. 14419 Statements.push_back(Move.getAs<Expr>()); 14420 } 14421 14422 // Assign non-static members. 14423 for (auto *Field : ClassDecl->fields()) { 14424 // FIXME: We should form some kind of AST representation for the implied 14425 // memcpy in a union copy operation. 14426 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14427 continue; 14428 14429 if (Field->isInvalidDecl()) { 14430 Invalid = true; 14431 continue; 14432 } 14433 14434 // Check for members of reference type; we can't move those. 14435 if (Field->getType()->isReferenceType()) { 14436 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14437 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14438 Diag(Field->getLocation(), diag::note_declared_at); 14439 Invalid = true; 14440 continue; 14441 } 14442 14443 // Check for members of const-qualified, non-class type. 14444 QualType BaseType = Context.getBaseElementType(Field->getType()); 14445 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14446 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14447 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14448 Diag(Field->getLocation(), diag::note_declared_at); 14449 Invalid = true; 14450 continue; 14451 } 14452 14453 // Suppress assigning zero-width bitfields. 14454 if (Field->isZeroLengthBitField(Context)) 14455 continue; 14456 14457 QualType FieldType = Field->getType().getNonReferenceType(); 14458 if (FieldType->isIncompleteArrayType()) { 14459 assert(ClassDecl->hasFlexibleArrayMember() && 14460 "Incomplete array type is not valid"); 14461 continue; 14462 } 14463 14464 // Build references to the field in the object we're copying from and to. 14465 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14466 LookupMemberName); 14467 MemberLookup.addDecl(Field); 14468 MemberLookup.resolveKind(); 14469 MemberBuilder From(MoveOther, OtherRefType, 14470 /*IsArrow=*/false, MemberLookup); 14471 MemberBuilder To(This, getCurrentThisType(), 14472 /*IsArrow=*/true, MemberLookup); 14473 14474 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14475 "Member reference with rvalue base must be rvalue except for reference " 14476 "members, which aren't allowed for move assignment."); 14477 14478 // Build the move of this field. 14479 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14480 To, From, 14481 /*CopyingBaseSubobject=*/false, 14482 /*Copying=*/false); 14483 if (Move.isInvalid()) { 14484 MoveAssignOperator->setInvalidDecl(); 14485 return; 14486 } 14487 14488 // Success! Record the copy. 14489 Statements.push_back(Move.getAs<Stmt>()); 14490 } 14491 14492 if (!Invalid) { 14493 // Add a "return *this;" 14494 ExprResult ThisObj = 14495 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14496 14497 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14498 if (Return.isInvalid()) 14499 Invalid = true; 14500 else 14501 Statements.push_back(Return.getAs<Stmt>()); 14502 } 14503 14504 if (Invalid) { 14505 MoveAssignOperator->setInvalidDecl(); 14506 return; 14507 } 14508 14509 StmtResult Body; 14510 { 14511 CompoundScopeRAII CompoundScope(*this); 14512 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14513 /*isStmtExpr=*/false); 14514 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14515 } 14516 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14517 MoveAssignOperator->markUsed(Context); 14518 14519 if (ASTMutationListener *L = getASTMutationListener()) { 14520 L->CompletedImplicitDefinition(MoveAssignOperator); 14521 } 14522 } 14523 14524 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14525 CXXRecordDecl *ClassDecl) { 14526 // C++ [class.copy]p4: 14527 // If the class definition does not explicitly declare a copy 14528 // constructor, one is declared implicitly. 14529 assert(ClassDecl->needsImplicitCopyConstructor()); 14530 14531 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14532 if (DSM.isAlreadyBeingDeclared()) 14533 return nullptr; 14534 14535 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14536 QualType ArgType = ClassType; 14537 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14538 if (Const) 14539 ArgType = ArgType.withConst(); 14540 14541 LangAS AS = getDefaultCXXMethodAddrSpace(); 14542 if (AS != LangAS::Default) 14543 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14544 14545 ArgType = Context.getLValueReferenceType(ArgType); 14546 14547 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14548 CXXCopyConstructor, 14549 Const); 14550 14551 DeclarationName Name 14552 = Context.DeclarationNames.getCXXConstructorName( 14553 Context.getCanonicalType(ClassType)); 14554 SourceLocation ClassLoc = ClassDecl->getLocation(); 14555 DeclarationNameInfo NameInfo(Name, ClassLoc); 14556 14557 // An implicitly-declared copy constructor is an inline public 14558 // member of its class. 14559 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14560 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14561 ExplicitSpecifier(), 14562 /*isInline=*/true, 14563 /*isImplicitlyDeclared=*/true, 14564 Constexpr ? CSK_constexpr : CSK_unspecified); 14565 CopyConstructor->setAccess(AS_public); 14566 CopyConstructor->setDefaulted(); 14567 14568 if (getLangOpts().CUDA) { 14569 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14570 CopyConstructor, 14571 /* ConstRHS */ Const, 14572 /* Diagnose */ false); 14573 } 14574 14575 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14576 14577 // Add the parameter to the constructor. 14578 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14579 ClassLoc, ClassLoc, 14580 /*IdentifierInfo=*/nullptr, 14581 ArgType, /*TInfo=*/nullptr, 14582 SC_None, nullptr); 14583 CopyConstructor->setParams(FromParam); 14584 14585 CopyConstructor->setTrivial( 14586 ClassDecl->needsOverloadResolutionForCopyConstructor() 14587 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14588 : ClassDecl->hasTrivialCopyConstructor()); 14589 14590 CopyConstructor->setTrivialForCall( 14591 ClassDecl->hasAttr<TrivialABIAttr>() || 14592 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14593 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14594 TAH_ConsiderTrivialABI) 14595 : ClassDecl->hasTrivialCopyConstructorForCall())); 14596 14597 // Note that we have declared this constructor. 14598 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14599 14600 Scope *S = getScopeForContext(ClassDecl); 14601 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14602 14603 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14604 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14605 SetDeclDeleted(CopyConstructor, ClassLoc); 14606 } 14607 14608 if (S) 14609 PushOnScopeChains(CopyConstructor, S, false); 14610 ClassDecl->addDecl(CopyConstructor); 14611 14612 return CopyConstructor; 14613 } 14614 14615 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14616 CXXConstructorDecl *CopyConstructor) { 14617 assert((CopyConstructor->isDefaulted() && 14618 CopyConstructor->isCopyConstructor() && 14619 !CopyConstructor->doesThisDeclarationHaveABody() && 14620 !CopyConstructor->isDeleted()) && 14621 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14622 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14623 return; 14624 14625 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14626 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14627 14628 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14629 14630 // The exception specification is needed because we are defining the 14631 // function. 14632 ResolveExceptionSpec(CurrentLocation, 14633 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14634 MarkVTableUsed(CurrentLocation, ClassDecl); 14635 14636 // Add a context note for diagnostics produced after this point. 14637 Scope.addContextNote(CurrentLocation); 14638 14639 // C++11 [class.copy]p7: 14640 // The [definition of an implicitly declared copy constructor] is 14641 // deprecated if the class has a user-declared copy assignment operator 14642 // or a user-declared destructor. 14643 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14644 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14645 14646 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14647 CopyConstructor->setInvalidDecl(); 14648 } else { 14649 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14650 ? CopyConstructor->getEndLoc() 14651 : CopyConstructor->getLocation(); 14652 Sema::CompoundScopeRAII CompoundScope(*this); 14653 CopyConstructor->setBody( 14654 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14655 CopyConstructor->markUsed(Context); 14656 } 14657 14658 if (ASTMutationListener *L = getASTMutationListener()) { 14659 L->CompletedImplicitDefinition(CopyConstructor); 14660 } 14661 } 14662 14663 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14664 CXXRecordDecl *ClassDecl) { 14665 assert(ClassDecl->needsImplicitMoveConstructor()); 14666 14667 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14668 if (DSM.isAlreadyBeingDeclared()) 14669 return nullptr; 14670 14671 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14672 14673 QualType ArgType = ClassType; 14674 LangAS AS = getDefaultCXXMethodAddrSpace(); 14675 if (AS != LangAS::Default) 14676 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14677 ArgType = Context.getRValueReferenceType(ArgType); 14678 14679 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14680 CXXMoveConstructor, 14681 false); 14682 14683 DeclarationName Name 14684 = Context.DeclarationNames.getCXXConstructorName( 14685 Context.getCanonicalType(ClassType)); 14686 SourceLocation ClassLoc = ClassDecl->getLocation(); 14687 DeclarationNameInfo NameInfo(Name, ClassLoc); 14688 14689 // C++11 [class.copy]p11: 14690 // An implicitly-declared copy/move constructor is an inline public 14691 // member of its class. 14692 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14693 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14694 ExplicitSpecifier(), 14695 /*isInline=*/true, 14696 /*isImplicitlyDeclared=*/true, 14697 Constexpr ? CSK_constexpr : CSK_unspecified); 14698 MoveConstructor->setAccess(AS_public); 14699 MoveConstructor->setDefaulted(); 14700 14701 if (getLangOpts().CUDA) { 14702 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14703 MoveConstructor, 14704 /* ConstRHS */ false, 14705 /* Diagnose */ false); 14706 } 14707 14708 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14709 14710 // Add the parameter to the constructor. 14711 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14712 ClassLoc, ClassLoc, 14713 /*IdentifierInfo=*/nullptr, 14714 ArgType, /*TInfo=*/nullptr, 14715 SC_None, nullptr); 14716 MoveConstructor->setParams(FromParam); 14717 14718 MoveConstructor->setTrivial( 14719 ClassDecl->needsOverloadResolutionForMoveConstructor() 14720 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14721 : ClassDecl->hasTrivialMoveConstructor()); 14722 14723 MoveConstructor->setTrivialForCall( 14724 ClassDecl->hasAttr<TrivialABIAttr>() || 14725 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14726 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14727 TAH_ConsiderTrivialABI) 14728 : ClassDecl->hasTrivialMoveConstructorForCall())); 14729 14730 // Note that we have declared this constructor. 14731 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14732 14733 Scope *S = getScopeForContext(ClassDecl); 14734 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14735 14736 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14737 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14738 SetDeclDeleted(MoveConstructor, ClassLoc); 14739 } 14740 14741 if (S) 14742 PushOnScopeChains(MoveConstructor, S, false); 14743 ClassDecl->addDecl(MoveConstructor); 14744 14745 return MoveConstructor; 14746 } 14747 14748 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14749 CXXConstructorDecl *MoveConstructor) { 14750 assert((MoveConstructor->isDefaulted() && 14751 MoveConstructor->isMoveConstructor() && 14752 !MoveConstructor->doesThisDeclarationHaveABody() && 14753 !MoveConstructor->isDeleted()) && 14754 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14755 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14756 return; 14757 14758 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14759 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14760 14761 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14762 14763 // The exception specification is needed because we are defining the 14764 // function. 14765 ResolveExceptionSpec(CurrentLocation, 14766 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14767 MarkVTableUsed(CurrentLocation, ClassDecl); 14768 14769 // Add a context note for diagnostics produced after this point. 14770 Scope.addContextNote(CurrentLocation); 14771 14772 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14773 MoveConstructor->setInvalidDecl(); 14774 } else { 14775 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14776 ? MoveConstructor->getEndLoc() 14777 : MoveConstructor->getLocation(); 14778 Sema::CompoundScopeRAII CompoundScope(*this); 14779 MoveConstructor->setBody(ActOnCompoundStmt( 14780 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14781 MoveConstructor->markUsed(Context); 14782 } 14783 14784 if (ASTMutationListener *L = getASTMutationListener()) { 14785 L->CompletedImplicitDefinition(MoveConstructor); 14786 } 14787 } 14788 14789 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14790 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14791 } 14792 14793 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14794 SourceLocation CurrentLocation, 14795 CXXConversionDecl *Conv) { 14796 SynthesizedFunctionScope Scope(*this, Conv); 14797 assert(!Conv->getReturnType()->isUndeducedType()); 14798 14799 CXXRecordDecl *Lambda = Conv->getParent(); 14800 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14801 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 14802 14803 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14804 CallOp = InstantiateFunctionDeclaration( 14805 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14806 if (!CallOp) 14807 return; 14808 14809 Invoker = InstantiateFunctionDeclaration( 14810 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14811 if (!Invoker) 14812 return; 14813 } 14814 14815 if (CallOp->isInvalidDecl()) 14816 return; 14817 14818 // Mark the call operator referenced (and add to pending instantiations 14819 // if necessary). 14820 // For both the conversion and static-invoker template specializations 14821 // we construct their body's in this function, so no need to add them 14822 // to the PendingInstantiations. 14823 MarkFunctionReferenced(CurrentLocation, CallOp); 14824 14825 // Fill in the __invoke function with a dummy implementation. IR generation 14826 // will fill in the actual details. Update its type in case it contained 14827 // an 'auto'. 14828 Invoker->markUsed(Context); 14829 Invoker->setReferenced(); 14830 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14831 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14832 14833 // Construct the body of the conversion function { return __invoke; }. 14834 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14835 VK_LValue, Conv->getLocation()); 14836 assert(FunctionRef && "Can't refer to __invoke function?"); 14837 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14838 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14839 Conv->getLocation())); 14840 Conv->markUsed(Context); 14841 Conv->setReferenced(); 14842 14843 if (ASTMutationListener *L = getASTMutationListener()) { 14844 L->CompletedImplicitDefinition(Conv); 14845 L->CompletedImplicitDefinition(Invoker); 14846 } 14847 } 14848 14849 14850 14851 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14852 SourceLocation CurrentLocation, 14853 CXXConversionDecl *Conv) 14854 { 14855 assert(!Conv->getParent()->isGenericLambda()); 14856 14857 SynthesizedFunctionScope Scope(*this, Conv); 14858 14859 // Copy-initialize the lambda object as needed to capture it. 14860 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14861 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14862 14863 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14864 Conv->getLocation(), 14865 Conv, DerefThis); 14866 14867 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14868 // behavior. Note that only the general conversion function does this 14869 // (since it's unusable otherwise); in the case where we inline the 14870 // block literal, it has block literal lifetime semantics. 14871 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14872 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 14873 CK_CopyAndAutoreleaseBlockObject, 14874 BuildBlock.get(), nullptr, VK_RValue); 14875 14876 if (BuildBlock.isInvalid()) { 14877 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14878 Conv->setInvalidDecl(); 14879 return; 14880 } 14881 14882 // Create the return statement that returns the block from the conversion 14883 // function. 14884 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14885 if (Return.isInvalid()) { 14886 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14887 Conv->setInvalidDecl(); 14888 return; 14889 } 14890 14891 // Set the body of the conversion function. 14892 Stmt *ReturnS = Return.get(); 14893 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14894 Conv->getLocation())); 14895 Conv->markUsed(Context); 14896 14897 // We're done; notify the mutation listener, if any. 14898 if (ASTMutationListener *L = getASTMutationListener()) { 14899 L->CompletedImplicitDefinition(Conv); 14900 } 14901 } 14902 14903 /// Determine whether the given list arguments contains exactly one 14904 /// "real" (non-default) argument. 14905 static bool hasOneRealArgument(MultiExprArg Args) { 14906 switch (Args.size()) { 14907 case 0: 14908 return false; 14909 14910 default: 14911 if (!Args[1]->isDefaultArgument()) 14912 return false; 14913 14914 LLVM_FALLTHROUGH; 14915 case 1: 14916 return !Args[0]->isDefaultArgument(); 14917 } 14918 14919 return false; 14920 } 14921 14922 ExprResult 14923 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14924 NamedDecl *FoundDecl, 14925 CXXConstructorDecl *Constructor, 14926 MultiExprArg ExprArgs, 14927 bool HadMultipleCandidates, 14928 bool IsListInitialization, 14929 bool IsStdInitListInitialization, 14930 bool RequiresZeroInit, 14931 unsigned ConstructKind, 14932 SourceRange ParenRange) { 14933 bool Elidable = false; 14934 14935 // C++0x [class.copy]p34: 14936 // When certain criteria are met, an implementation is allowed to 14937 // omit the copy/move construction of a class object, even if the 14938 // copy/move constructor and/or destructor for the object have 14939 // side effects. [...] 14940 // - when a temporary class object that has not been bound to a 14941 // reference (12.2) would be copied/moved to a class object 14942 // with the same cv-unqualified type, the copy/move operation 14943 // can be omitted by constructing the temporary object 14944 // directly into the target of the omitted copy/move 14945 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 14946 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 14947 Expr *SubExpr = ExprArgs[0]; 14948 Elidable = SubExpr->isTemporaryObject( 14949 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 14950 } 14951 14952 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 14953 FoundDecl, Constructor, 14954 Elidable, ExprArgs, HadMultipleCandidates, 14955 IsListInitialization, 14956 IsStdInitListInitialization, RequiresZeroInit, 14957 ConstructKind, ParenRange); 14958 } 14959 14960 ExprResult 14961 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14962 NamedDecl *FoundDecl, 14963 CXXConstructorDecl *Constructor, 14964 bool Elidable, 14965 MultiExprArg ExprArgs, 14966 bool HadMultipleCandidates, 14967 bool IsListInitialization, 14968 bool IsStdInitListInitialization, 14969 bool RequiresZeroInit, 14970 unsigned ConstructKind, 14971 SourceRange ParenRange) { 14972 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 14973 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 14974 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 14975 return ExprError(); 14976 } 14977 14978 return BuildCXXConstructExpr( 14979 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 14980 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 14981 RequiresZeroInit, ConstructKind, ParenRange); 14982 } 14983 14984 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 14985 /// including handling of its default argument expressions. 14986 ExprResult 14987 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14988 CXXConstructorDecl *Constructor, 14989 bool Elidable, 14990 MultiExprArg ExprArgs, 14991 bool HadMultipleCandidates, 14992 bool IsListInitialization, 14993 bool IsStdInitListInitialization, 14994 bool RequiresZeroInit, 14995 unsigned ConstructKind, 14996 SourceRange ParenRange) { 14997 assert(declaresSameEntity( 14998 Constructor->getParent(), 14999 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15000 "given constructor for wrong type"); 15001 MarkFunctionReferenced(ConstructLoc, Constructor); 15002 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15003 return ExprError(); 15004 if (getLangOpts().SYCLIsDevice && 15005 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15006 return ExprError(); 15007 15008 return CheckForImmediateInvocation( 15009 CXXConstructExpr::Create( 15010 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15011 HadMultipleCandidates, IsListInitialization, 15012 IsStdInitListInitialization, RequiresZeroInit, 15013 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15014 ParenRange), 15015 Constructor); 15016 } 15017 15018 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15019 assert(Field->hasInClassInitializer()); 15020 15021 // If we already have the in-class initializer nothing needs to be done. 15022 if (Field->getInClassInitializer()) 15023 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15024 15025 // If we might have already tried and failed to instantiate, don't try again. 15026 if (Field->isInvalidDecl()) 15027 return ExprError(); 15028 15029 // Maybe we haven't instantiated the in-class initializer. Go check the 15030 // pattern FieldDecl to see if it has one. 15031 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15032 15033 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15034 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15035 DeclContext::lookup_result Lookup = 15036 ClassPattern->lookup(Field->getDeclName()); 15037 15038 // Lookup can return at most two results: the pattern for the field, or the 15039 // injected class name of the parent record. No other member can have the 15040 // same name as the field. 15041 // In modules mode, lookup can return multiple results (coming from 15042 // different modules). 15043 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 15044 "more than two lookup results for field name"); 15045 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 15046 if (!Pattern) { 15047 assert(isa<CXXRecordDecl>(Lookup[0]) && 15048 "cannot have other non-field member with same name"); 15049 for (auto L : Lookup) 15050 if (isa<FieldDecl>(L)) { 15051 Pattern = cast<FieldDecl>(L); 15052 break; 15053 } 15054 assert(Pattern && "We must have set the Pattern!"); 15055 } 15056 15057 if (!Pattern->hasInClassInitializer() || 15058 InstantiateInClassInitializer(Loc, Field, Pattern, 15059 getTemplateInstantiationArgs(Field))) { 15060 // Don't diagnose this again. 15061 Field->setInvalidDecl(); 15062 return ExprError(); 15063 } 15064 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15065 } 15066 15067 // DR1351: 15068 // If the brace-or-equal-initializer of a non-static data member 15069 // invokes a defaulted default constructor of its class or of an 15070 // enclosing class in a potentially evaluated subexpression, the 15071 // program is ill-formed. 15072 // 15073 // This resolution is unworkable: the exception specification of the 15074 // default constructor can be needed in an unevaluated context, in 15075 // particular, in the operand of a noexcept-expression, and we can be 15076 // unable to compute an exception specification for an enclosed class. 15077 // 15078 // Any attempt to resolve the exception specification of a defaulted default 15079 // constructor before the initializer is lexically complete will ultimately 15080 // come here at which point we can diagnose it. 15081 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15082 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 15083 << OutermostClass << Field; 15084 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 15085 // Recover by marking the field invalid, unless we're in a SFINAE context. 15086 if (!isSFINAEContext()) 15087 Field->setInvalidDecl(); 15088 return ExprError(); 15089 } 15090 15091 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15092 if (VD->isInvalidDecl()) return; 15093 // If initializing the variable failed, don't also diagnose problems with 15094 // the desctructor, they're likely related. 15095 if (VD->getInit() && VD->getInit()->containsErrors()) 15096 return; 15097 15098 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15099 if (ClassDecl->isInvalidDecl()) return; 15100 if (ClassDecl->hasIrrelevantDestructor()) return; 15101 if (ClassDecl->isDependentContext()) return; 15102 15103 if (VD->isNoDestroy(getASTContext())) 15104 return; 15105 15106 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15107 15108 // If this is an array, we'll require the destructor during initialization, so 15109 // we can skip over this. We still want to emit exit-time destructor warnings 15110 // though. 15111 if (!VD->getType()->isArrayType()) { 15112 MarkFunctionReferenced(VD->getLocation(), Destructor); 15113 CheckDestructorAccess(VD->getLocation(), Destructor, 15114 PDiag(diag::err_access_dtor_var) 15115 << VD->getDeclName() << VD->getType()); 15116 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15117 } 15118 15119 if (Destructor->isTrivial()) return; 15120 15121 // If the destructor is constexpr, check whether the variable has constant 15122 // destruction now. 15123 if (Destructor->isConstexpr()) { 15124 bool HasConstantInit = false; 15125 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15126 HasConstantInit = VD->evaluateValue(); 15127 SmallVector<PartialDiagnosticAt, 8> Notes; 15128 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15129 HasConstantInit) { 15130 Diag(VD->getLocation(), 15131 diag::err_constexpr_var_requires_const_destruction) << VD; 15132 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15133 Diag(Notes[I].first, Notes[I].second); 15134 } 15135 } 15136 15137 if (!VD->hasGlobalStorage()) return; 15138 15139 // Emit warning for non-trivial dtor in global scope (a real global, 15140 // class-static, function-static). 15141 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15142 15143 // TODO: this should be re-enabled for static locals by !CXAAtExit 15144 if (!VD->isStaticLocal()) 15145 Diag(VD->getLocation(), diag::warn_global_destructor); 15146 } 15147 15148 /// Given a constructor and the set of arguments provided for the 15149 /// constructor, convert the arguments and add any required default arguments 15150 /// to form a proper call to this constructor. 15151 /// 15152 /// \returns true if an error occurred, false otherwise. 15153 bool 15154 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15155 MultiExprArg ArgsPtr, 15156 SourceLocation Loc, 15157 SmallVectorImpl<Expr*> &ConvertedArgs, 15158 bool AllowExplicit, 15159 bool IsListInitialization) { 15160 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15161 unsigned NumArgs = ArgsPtr.size(); 15162 Expr **Args = ArgsPtr.data(); 15163 15164 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15165 unsigned NumParams = Proto->getNumParams(); 15166 15167 // If too few arguments are available, we'll fill in the rest with defaults. 15168 if (NumArgs < NumParams) 15169 ConvertedArgs.reserve(NumParams); 15170 else 15171 ConvertedArgs.reserve(NumArgs); 15172 15173 VariadicCallType CallType = 15174 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15175 SmallVector<Expr *, 8> AllArgs; 15176 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15177 Proto, 0, 15178 llvm::makeArrayRef(Args, NumArgs), 15179 AllArgs, 15180 CallType, AllowExplicit, 15181 IsListInitialization); 15182 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15183 15184 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15185 15186 CheckConstructorCall(Constructor, 15187 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15188 Proto, Loc); 15189 15190 return Invalid; 15191 } 15192 15193 static inline bool 15194 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15195 const FunctionDecl *FnDecl) { 15196 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15197 if (isa<NamespaceDecl>(DC)) { 15198 return SemaRef.Diag(FnDecl->getLocation(), 15199 diag::err_operator_new_delete_declared_in_namespace) 15200 << FnDecl->getDeclName(); 15201 } 15202 15203 if (isa<TranslationUnitDecl>(DC) && 15204 FnDecl->getStorageClass() == SC_Static) { 15205 return SemaRef.Diag(FnDecl->getLocation(), 15206 diag::err_operator_new_delete_declared_static) 15207 << FnDecl->getDeclName(); 15208 } 15209 15210 return false; 15211 } 15212 15213 static QualType 15214 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 15215 QualType QTy = PtrTy->getPointeeType(); 15216 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 15217 return SemaRef.Context.getPointerType(QTy); 15218 } 15219 15220 static inline bool 15221 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15222 CanQualType ExpectedResultType, 15223 CanQualType ExpectedFirstParamType, 15224 unsigned DependentParamTypeDiag, 15225 unsigned InvalidParamTypeDiag) { 15226 QualType ResultType = 15227 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15228 15229 // The operator is valid on any address space for OpenCL. 15230 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15231 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 15232 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15233 } 15234 } 15235 15236 // Check that the result type is what we expect. 15237 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15238 // Reject even if the type is dependent; an operator delete function is 15239 // required to have a non-dependent result type. 15240 return SemaRef.Diag( 15241 FnDecl->getLocation(), 15242 ResultType->isDependentType() 15243 ? diag::err_operator_new_delete_dependent_result_type 15244 : diag::err_operator_new_delete_invalid_result_type) 15245 << FnDecl->getDeclName() << ExpectedResultType; 15246 } 15247 15248 // A function template must have at least 2 parameters. 15249 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15250 return SemaRef.Diag(FnDecl->getLocation(), 15251 diag::err_operator_new_delete_template_too_few_parameters) 15252 << FnDecl->getDeclName(); 15253 15254 // The function decl must have at least 1 parameter. 15255 if (FnDecl->getNumParams() == 0) 15256 return SemaRef.Diag(FnDecl->getLocation(), 15257 diag::err_operator_new_delete_too_few_parameters) 15258 << FnDecl->getDeclName(); 15259 15260 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15261 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15262 // The operator is valid on any address space for OpenCL. 15263 if (auto *PtrTy = 15264 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 15265 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15266 } 15267 } 15268 15269 // Check that the first parameter type is what we expect. 15270 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15271 ExpectedFirstParamType) { 15272 // The first parameter type is not allowed to be dependent. As a tentative 15273 // DR resolution, we allow a dependent parameter type if it is the right 15274 // type anyway, to allow destroying operator delete in class templates. 15275 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15276 ? DependentParamTypeDiag 15277 : InvalidParamTypeDiag) 15278 << FnDecl->getDeclName() << ExpectedFirstParamType; 15279 } 15280 15281 return false; 15282 } 15283 15284 static bool 15285 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15286 // C++ [basic.stc.dynamic.allocation]p1: 15287 // A program is ill-formed if an allocation function is declared in a 15288 // namespace scope other than global scope or declared static in global 15289 // scope. 15290 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15291 return true; 15292 15293 CanQualType SizeTy = 15294 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15295 15296 // C++ [basic.stc.dynamic.allocation]p1: 15297 // The return type shall be void*. The first parameter shall have type 15298 // std::size_t. 15299 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15300 SizeTy, 15301 diag::err_operator_new_dependent_param_type, 15302 diag::err_operator_new_param_type)) 15303 return true; 15304 15305 // C++ [basic.stc.dynamic.allocation]p1: 15306 // The first parameter shall not have an associated default argument. 15307 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15308 return SemaRef.Diag(FnDecl->getLocation(), 15309 diag::err_operator_new_default_arg) 15310 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15311 15312 return false; 15313 } 15314 15315 static bool 15316 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15317 // C++ [basic.stc.dynamic.deallocation]p1: 15318 // A program is ill-formed if deallocation functions are declared in a 15319 // namespace scope other than global scope or declared static in global 15320 // scope. 15321 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15322 return true; 15323 15324 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15325 15326 // C++ P0722: 15327 // Within a class C, the first parameter of a destroying operator delete 15328 // shall be of type C *. The first parameter of any other deallocation 15329 // function shall be of type void *. 15330 CanQualType ExpectedFirstParamType = 15331 MD && MD->isDestroyingOperatorDelete() 15332 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15333 SemaRef.Context.getRecordType(MD->getParent()))) 15334 : SemaRef.Context.VoidPtrTy; 15335 15336 // C++ [basic.stc.dynamic.deallocation]p2: 15337 // Each deallocation function shall return void 15338 if (CheckOperatorNewDeleteTypes( 15339 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15340 diag::err_operator_delete_dependent_param_type, 15341 diag::err_operator_delete_param_type)) 15342 return true; 15343 15344 // C++ P0722: 15345 // A destroying operator delete shall be a usual deallocation function. 15346 if (MD && !MD->getParent()->isDependentContext() && 15347 MD->isDestroyingOperatorDelete() && 15348 !SemaRef.isUsualDeallocationFunction(MD)) { 15349 SemaRef.Diag(MD->getLocation(), 15350 diag::err_destroying_operator_delete_not_usual); 15351 return true; 15352 } 15353 15354 return false; 15355 } 15356 15357 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15358 /// of this overloaded operator is well-formed. If so, returns false; 15359 /// otherwise, emits appropriate diagnostics and returns true. 15360 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15361 assert(FnDecl && FnDecl->isOverloadedOperator() && 15362 "Expected an overloaded operator declaration"); 15363 15364 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15365 15366 // C++ [over.oper]p5: 15367 // The allocation and deallocation functions, operator new, 15368 // operator new[], operator delete and operator delete[], are 15369 // described completely in 3.7.3. The attributes and restrictions 15370 // found in the rest of this subclause do not apply to them unless 15371 // explicitly stated in 3.7.3. 15372 if (Op == OO_Delete || Op == OO_Array_Delete) 15373 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15374 15375 if (Op == OO_New || Op == OO_Array_New) 15376 return CheckOperatorNewDeclaration(*this, FnDecl); 15377 15378 // C++ [over.oper]p6: 15379 // An operator function shall either be a non-static member 15380 // function or be a non-member function and have at least one 15381 // parameter whose type is a class, a reference to a class, an 15382 // enumeration, or a reference to an enumeration. 15383 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15384 if (MethodDecl->isStatic()) 15385 return Diag(FnDecl->getLocation(), 15386 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15387 } else { 15388 bool ClassOrEnumParam = false; 15389 for (auto Param : FnDecl->parameters()) { 15390 QualType ParamType = Param->getType().getNonReferenceType(); 15391 if (ParamType->isDependentType() || ParamType->isRecordType() || 15392 ParamType->isEnumeralType()) { 15393 ClassOrEnumParam = true; 15394 break; 15395 } 15396 } 15397 15398 if (!ClassOrEnumParam) 15399 return Diag(FnDecl->getLocation(), 15400 diag::err_operator_overload_needs_class_or_enum) 15401 << FnDecl->getDeclName(); 15402 } 15403 15404 // C++ [over.oper]p8: 15405 // An operator function cannot have default arguments (8.3.6), 15406 // except where explicitly stated below. 15407 // 15408 // Only the function-call operator allows default arguments 15409 // (C++ [over.call]p1). 15410 if (Op != OO_Call) { 15411 for (auto Param : FnDecl->parameters()) { 15412 if (Param->hasDefaultArg()) 15413 return Diag(Param->getLocation(), 15414 diag::err_operator_overload_default_arg) 15415 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15416 } 15417 } 15418 15419 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15420 { false, false, false } 15421 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15422 , { Unary, Binary, MemberOnly } 15423 #include "clang/Basic/OperatorKinds.def" 15424 }; 15425 15426 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15427 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15428 bool MustBeMemberOperator = OperatorUses[Op][2]; 15429 15430 // C++ [over.oper]p8: 15431 // [...] Operator functions cannot have more or fewer parameters 15432 // than the number required for the corresponding operator, as 15433 // described in the rest of this subclause. 15434 unsigned NumParams = FnDecl->getNumParams() 15435 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15436 if (Op != OO_Call && 15437 ((NumParams == 1 && !CanBeUnaryOperator) || 15438 (NumParams == 2 && !CanBeBinaryOperator) || 15439 (NumParams < 1) || (NumParams > 2))) { 15440 // We have the wrong number of parameters. 15441 unsigned ErrorKind; 15442 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15443 ErrorKind = 2; // 2 -> unary or binary. 15444 } else if (CanBeUnaryOperator) { 15445 ErrorKind = 0; // 0 -> unary 15446 } else { 15447 assert(CanBeBinaryOperator && 15448 "All non-call overloaded operators are unary or binary!"); 15449 ErrorKind = 1; // 1 -> binary 15450 } 15451 15452 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15453 << FnDecl->getDeclName() << NumParams << ErrorKind; 15454 } 15455 15456 // Overloaded operators other than operator() cannot be variadic. 15457 if (Op != OO_Call && 15458 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15459 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15460 << FnDecl->getDeclName(); 15461 } 15462 15463 // Some operators must be non-static member functions. 15464 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15465 return Diag(FnDecl->getLocation(), 15466 diag::err_operator_overload_must_be_member) 15467 << FnDecl->getDeclName(); 15468 } 15469 15470 // C++ [over.inc]p1: 15471 // The user-defined function called operator++ implements the 15472 // prefix and postfix ++ operator. If this function is a member 15473 // function with no parameters, or a non-member function with one 15474 // parameter of class or enumeration type, it defines the prefix 15475 // increment operator ++ for objects of that type. If the function 15476 // is a member function with one parameter (which shall be of type 15477 // int) or a non-member function with two parameters (the second 15478 // of which shall be of type int), it defines the postfix 15479 // increment operator ++ for objects of that type. 15480 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15481 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15482 QualType ParamType = LastParam->getType(); 15483 15484 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15485 !ParamType->isDependentType()) 15486 return Diag(LastParam->getLocation(), 15487 diag::err_operator_overload_post_incdec_must_be_int) 15488 << LastParam->getType() << (Op == OO_MinusMinus); 15489 } 15490 15491 return false; 15492 } 15493 15494 static bool 15495 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15496 FunctionTemplateDecl *TpDecl) { 15497 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15498 15499 // Must have one or two template parameters. 15500 if (TemplateParams->size() == 1) { 15501 NonTypeTemplateParmDecl *PmDecl = 15502 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15503 15504 // The template parameter must be a char parameter pack. 15505 if (PmDecl && PmDecl->isTemplateParameterPack() && 15506 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15507 return false; 15508 15509 } else if (TemplateParams->size() == 2) { 15510 TemplateTypeParmDecl *PmType = 15511 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15512 NonTypeTemplateParmDecl *PmArgs = 15513 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15514 15515 // The second template parameter must be a parameter pack with the 15516 // first template parameter as its type. 15517 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15518 PmArgs->isTemplateParameterPack()) { 15519 const TemplateTypeParmType *TArgs = 15520 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15521 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15522 TArgs->getIndex() == PmType->getIndex()) { 15523 if (!SemaRef.inTemplateInstantiation()) 15524 SemaRef.Diag(TpDecl->getLocation(), 15525 diag::ext_string_literal_operator_template); 15526 return false; 15527 } 15528 } 15529 } 15530 15531 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15532 diag::err_literal_operator_template) 15533 << TpDecl->getTemplateParameters()->getSourceRange(); 15534 return true; 15535 } 15536 15537 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15538 /// of this literal operator function is well-formed. If so, returns 15539 /// false; otherwise, emits appropriate diagnostics and returns true. 15540 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15541 if (isa<CXXMethodDecl>(FnDecl)) { 15542 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15543 << FnDecl->getDeclName(); 15544 return true; 15545 } 15546 15547 if (FnDecl->isExternC()) { 15548 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15549 if (const LinkageSpecDecl *LSD = 15550 FnDecl->getDeclContext()->getExternCContext()) 15551 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15552 return true; 15553 } 15554 15555 // This might be the definition of a literal operator template. 15556 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15557 15558 // This might be a specialization of a literal operator template. 15559 if (!TpDecl) 15560 TpDecl = FnDecl->getPrimaryTemplate(); 15561 15562 // template <char...> type operator "" name() and 15563 // template <class T, T...> type operator "" name() are the only valid 15564 // template signatures, and the only valid signatures with no parameters. 15565 if (TpDecl) { 15566 if (FnDecl->param_size() != 0) { 15567 Diag(FnDecl->getLocation(), 15568 diag::err_literal_operator_template_with_params); 15569 return true; 15570 } 15571 15572 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15573 return true; 15574 15575 } else if (FnDecl->param_size() == 1) { 15576 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15577 15578 QualType ParamType = Param->getType().getUnqualifiedType(); 15579 15580 // Only unsigned long long int, long double, any character type, and const 15581 // char * are allowed as the only parameters. 15582 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15583 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15584 Context.hasSameType(ParamType, Context.CharTy) || 15585 Context.hasSameType(ParamType, Context.WideCharTy) || 15586 Context.hasSameType(ParamType, Context.Char8Ty) || 15587 Context.hasSameType(ParamType, Context.Char16Ty) || 15588 Context.hasSameType(ParamType, Context.Char32Ty)) { 15589 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15590 QualType InnerType = Ptr->getPointeeType(); 15591 15592 // Pointer parameter must be a const char *. 15593 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15594 Context.CharTy) && 15595 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15596 Diag(Param->getSourceRange().getBegin(), 15597 diag::err_literal_operator_param) 15598 << ParamType << "'const char *'" << Param->getSourceRange(); 15599 return true; 15600 } 15601 15602 } else if (ParamType->isRealFloatingType()) { 15603 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15604 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15605 return true; 15606 15607 } else if (ParamType->isIntegerType()) { 15608 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15609 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15610 return true; 15611 15612 } else { 15613 Diag(Param->getSourceRange().getBegin(), 15614 diag::err_literal_operator_invalid_param) 15615 << ParamType << Param->getSourceRange(); 15616 return true; 15617 } 15618 15619 } else if (FnDecl->param_size() == 2) { 15620 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15621 15622 // First, verify that the first parameter is correct. 15623 15624 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15625 15626 // Two parameter function must have a pointer to const as a 15627 // first parameter; let's strip those qualifiers. 15628 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15629 15630 if (!PT) { 15631 Diag((*Param)->getSourceRange().getBegin(), 15632 diag::err_literal_operator_param) 15633 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15634 return true; 15635 } 15636 15637 QualType PointeeType = PT->getPointeeType(); 15638 // First parameter must be const 15639 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15640 Diag((*Param)->getSourceRange().getBegin(), 15641 diag::err_literal_operator_param) 15642 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15643 return true; 15644 } 15645 15646 QualType InnerType = PointeeType.getUnqualifiedType(); 15647 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15648 // const char32_t* are allowed as the first parameter to a two-parameter 15649 // function 15650 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15651 Context.hasSameType(InnerType, Context.WideCharTy) || 15652 Context.hasSameType(InnerType, Context.Char8Ty) || 15653 Context.hasSameType(InnerType, Context.Char16Ty) || 15654 Context.hasSameType(InnerType, Context.Char32Ty))) { 15655 Diag((*Param)->getSourceRange().getBegin(), 15656 diag::err_literal_operator_param) 15657 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15658 return true; 15659 } 15660 15661 // Move on to the second and final parameter. 15662 ++Param; 15663 15664 // The second parameter must be a std::size_t. 15665 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15666 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15667 Diag((*Param)->getSourceRange().getBegin(), 15668 diag::err_literal_operator_param) 15669 << SecondParamType << Context.getSizeType() 15670 << (*Param)->getSourceRange(); 15671 return true; 15672 } 15673 } else { 15674 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15675 return true; 15676 } 15677 15678 // Parameters are good. 15679 15680 // A parameter-declaration-clause containing a default argument is not 15681 // equivalent to any of the permitted forms. 15682 for (auto Param : FnDecl->parameters()) { 15683 if (Param->hasDefaultArg()) { 15684 Diag(Param->getDefaultArgRange().getBegin(), 15685 diag::err_literal_operator_default_argument) 15686 << Param->getDefaultArgRange(); 15687 break; 15688 } 15689 } 15690 15691 StringRef LiteralName 15692 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15693 if (LiteralName[0] != '_' && 15694 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15695 // C++11 [usrlit.suffix]p1: 15696 // Literal suffix identifiers that do not start with an underscore 15697 // are reserved for future standardization. 15698 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15699 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15700 } 15701 15702 return false; 15703 } 15704 15705 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15706 /// linkage specification, including the language and (if present) 15707 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15708 /// language string literal. LBraceLoc, if valid, provides the location of 15709 /// the '{' brace. Otherwise, this linkage specification does not 15710 /// have any braces. 15711 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15712 Expr *LangStr, 15713 SourceLocation LBraceLoc) { 15714 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15715 if (!Lit->isAscii()) { 15716 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15717 << LangStr->getSourceRange(); 15718 return nullptr; 15719 } 15720 15721 StringRef Lang = Lit->getString(); 15722 LinkageSpecDecl::LanguageIDs Language; 15723 if (Lang == "C") 15724 Language = LinkageSpecDecl::lang_c; 15725 else if (Lang == "C++") 15726 Language = LinkageSpecDecl::lang_cxx; 15727 else { 15728 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15729 << LangStr->getSourceRange(); 15730 return nullptr; 15731 } 15732 15733 // FIXME: Add all the various semantics of linkage specifications 15734 15735 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15736 LangStr->getExprLoc(), Language, 15737 LBraceLoc.isValid()); 15738 CurContext->addDecl(D); 15739 PushDeclContext(S, D); 15740 return D; 15741 } 15742 15743 /// ActOnFinishLinkageSpecification - Complete the definition of 15744 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15745 /// valid, it's the position of the closing '}' brace in a linkage 15746 /// specification that uses braces. 15747 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15748 Decl *LinkageSpec, 15749 SourceLocation RBraceLoc) { 15750 if (RBraceLoc.isValid()) { 15751 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15752 LSDecl->setRBraceLoc(RBraceLoc); 15753 } 15754 PopDeclContext(); 15755 return LinkageSpec; 15756 } 15757 15758 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15759 const ParsedAttributesView &AttrList, 15760 SourceLocation SemiLoc) { 15761 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15762 // Attribute declarations appertain to empty declaration so we handle 15763 // them here. 15764 ProcessDeclAttributeList(S, ED, AttrList); 15765 15766 CurContext->addDecl(ED); 15767 return ED; 15768 } 15769 15770 /// Perform semantic analysis for the variable declaration that 15771 /// occurs within a C++ catch clause, returning the newly-created 15772 /// variable. 15773 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15774 TypeSourceInfo *TInfo, 15775 SourceLocation StartLoc, 15776 SourceLocation Loc, 15777 IdentifierInfo *Name) { 15778 bool Invalid = false; 15779 QualType ExDeclType = TInfo->getType(); 15780 15781 // Arrays and functions decay. 15782 if (ExDeclType->isArrayType()) 15783 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15784 else if (ExDeclType->isFunctionType()) 15785 ExDeclType = Context.getPointerType(ExDeclType); 15786 15787 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15788 // The exception-declaration shall not denote a pointer or reference to an 15789 // incomplete type, other than [cv] void*. 15790 // N2844 forbids rvalue references. 15791 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15792 Diag(Loc, diag::err_catch_rvalue_ref); 15793 Invalid = true; 15794 } 15795 15796 if (ExDeclType->isVariablyModifiedType()) { 15797 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15798 Invalid = true; 15799 } 15800 15801 QualType BaseType = ExDeclType; 15802 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15803 unsigned DK = diag::err_catch_incomplete; 15804 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15805 BaseType = Ptr->getPointeeType(); 15806 Mode = 1; 15807 DK = diag::err_catch_incomplete_ptr; 15808 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15809 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15810 BaseType = Ref->getPointeeType(); 15811 Mode = 2; 15812 DK = diag::err_catch_incomplete_ref; 15813 } 15814 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15815 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15816 Invalid = true; 15817 15818 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15819 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15820 Invalid = true; 15821 } 15822 15823 if (!Invalid && !ExDeclType->isDependentType() && 15824 RequireNonAbstractType(Loc, ExDeclType, 15825 diag::err_abstract_type_in_decl, 15826 AbstractVariableType)) 15827 Invalid = true; 15828 15829 // Only the non-fragile NeXT runtime currently supports C++ catches 15830 // of ObjC types, and no runtime supports catching ObjC types by value. 15831 if (!Invalid && getLangOpts().ObjC) { 15832 QualType T = ExDeclType; 15833 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15834 T = RT->getPointeeType(); 15835 15836 if (T->isObjCObjectType()) { 15837 Diag(Loc, diag::err_objc_object_catch); 15838 Invalid = true; 15839 } else if (T->isObjCObjectPointerType()) { 15840 // FIXME: should this be a test for macosx-fragile specifically? 15841 if (getLangOpts().ObjCRuntime.isFragile()) 15842 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15843 } 15844 } 15845 15846 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15847 ExDeclType, TInfo, SC_None); 15848 ExDecl->setExceptionVariable(true); 15849 15850 // In ARC, infer 'retaining' for variables of retainable type. 15851 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15852 Invalid = true; 15853 15854 if (!Invalid && !ExDeclType->isDependentType()) { 15855 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15856 // Insulate this from anything else we might currently be parsing. 15857 EnterExpressionEvaluationContext scope( 15858 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15859 15860 // C++ [except.handle]p16: 15861 // The object declared in an exception-declaration or, if the 15862 // exception-declaration does not specify a name, a temporary (12.2) is 15863 // copy-initialized (8.5) from the exception object. [...] 15864 // The object is destroyed when the handler exits, after the destruction 15865 // of any automatic objects initialized within the handler. 15866 // 15867 // We just pretend to initialize the object with itself, then make sure 15868 // it can be destroyed later. 15869 QualType initType = Context.getExceptionObjectType(ExDeclType); 15870 15871 InitializedEntity entity = 15872 InitializedEntity::InitializeVariable(ExDecl); 15873 InitializationKind initKind = 15874 InitializationKind::CreateCopy(Loc, SourceLocation()); 15875 15876 Expr *opaqueValue = 15877 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15878 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15879 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15880 if (result.isInvalid()) 15881 Invalid = true; 15882 else { 15883 // If the constructor used was non-trivial, set this as the 15884 // "initializer". 15885 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15886 if (!construct->getConstructor()->isTrivial()) { 15887 Expr *init = MaybeCreateExprWithCleanups(construct); 15888 ExDecl->setInit(init); 15889 } 15890 15891 // And make sure it's destructable. 15892 FinalizeVarWithDestructor(ExDecl, recordType); 15893 } 15894 } 15895 } 15896 15897 if (Invalid) 15898 ExDecl->setInvalidDecl(); 15899 15900 return ExDecl; 15901 } 15902 15903 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15904 /// handler. 15905 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15906 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15907 bool Invalid = D.isInvalidType(); 15908 15909 // Check for unexpanded parameter packs. 15910 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15911 UPPC_ExceptionType)) { 15912 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15913 D.getIdentifierLoc()); 15914 Invalid = true; 15915 } 15916 15917 IdentifierInfo *II = D.getIdentifier(); 15918 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15919 LookupOrdinaryName, 15920 ForVisibleRedeclaration)) { 15921 // The scope should be freshly made just for us. There is just no way 15922 // it contains any previous declaration, except for function parameters in 15923 // a function-try-block's catch statement. 15924 assert(!S->isDeclScope(PrevDecl)); 15925 if (isDeclInScope(PrevDecl, CurContext, S)) { 15926 Diag(D.getIdentifierLoc(), diag::err_redefinition) 15927 << D.getIdentifier(); 15928 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15929 Invalid = true; 15930 } else if (PrevDecl->isTemplateParameter()) 15931 // Maybe we will complain about the shadowed template parameter. 15932 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15933 } 15934 15935 if (D.getCXXScopeSpec().isSet() && !Invalid) { 15936 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 15937 << D.getCXXScopeSpec().getRange(); 15938 Invalid = true; 15939 } 15940 15941 VarDecl *ExDecl = BuildExceptionDeclaration( 15942 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 15943 if (Invalid) 15944 ExDecl->setInvalidDecl(); 15945 15946 // Add the exception declaration into this scope. 15947 if (II) 15948 PushOnScopeChains(ExDecl, S); 15949 else 15950 CurContext->addDecl(ExDecl); 15951 15952 ProcessDeclAttributes(S, ExDecl, D); 15953 return ExDecl; 15954 } 15955 15956 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15957 Expr *AssertExpr, 15958 Expr *AssertMessageExpr, 15959 SourceLocation RParenLoc) { 15960 StringLiteral *AssertMessage = 15961 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 15962 15963 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 15964 return nullptr; 15965 15966 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 15967 AssertMessage, RParenLoc, false); 15968 } 15969 15970 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15971 Expr *AssertExpr, 15972 StringLiteral *AssertMessage, 15973 SourceLocation RParenLoc, 15974 bool Failed) { 15975 assert(AssertExpr != nullptr && "Expected non-null condition"); 15976 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 15977 !Failed) { 15978 // In a static_assert-declaration, the constant-expression shall be a 15979 // constant expression that can be contextually converted to bool. 15980 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 15981 if (Converted.isInvalid()) 15982 Failed = true; 15983 15984 ExprResult FullAssertExpr = 15985 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 15986 /*DiscardedValue*/ false, 15987 /*IsConstexpr*/ true); 15988 if (FullAssertExpr.isInvalid()) 15989 Failed = true; 15990 else 15991 AssertExpr = FullAssertExpr.get(); 15992 15993 llvm::APSInt Cond; 15994 if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond, 15995 diag::err_static_assert_expression_is_not_constant, 15996 /*AllowFold=*/false).isInvalid()) 15997 Failed = true; 15998 15999 if (!Failed && !Cond) { 16000 SmallString<256> MsgBuffer; 16001 llvm::raw_svector_ostream Msg(MsgBuffer); 16002 if (AssertMessage) 16003 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16004 16005 Expr *InnerCond = nullptr; 16006 std::string InnerCondDescription; 16007 std::tie(InnerCond, InnerCondDescription) = 16008 findFailedBooleanCondition(Converted.get()); 16009 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16010 // Drill down into concept specialization expressions to see why they 16011 // weren't satisfied. 16012 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16013 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16014 ConstraintSatisfaction Satisfaction; 16015 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16016 DiagnoseUnsatisfiedConstraint(Satisfaction); 16017 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16018 && !isa<IntegerLiteral>(InnerCond)) { 16019 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16020 << InnerCondDescription << !AssertMessage 16021 << Msg.str() << InnerCond->getSourceRange(); 16022 } else { 16023 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16024 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16025 } 16026 Failed = true; 16027 } 16028 } else { 16029 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16030 /*DiscardedValue*/false, 16031 /*IsConstexpr*/true); 16032 if (FullAssertExpr.isInvalid()) 16033 Failed = true; 16034 else 16035 AssertExpr = FullAssertExpr.get(); 16036 } 16037 16038 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16039 AssertExpr, AssertMessage, RParenLoc, 16040 Failed); 16041 16042 CurContext->addDecl(Decl); 16043 return Decl; 16044 } 16045 16046 /// Perform semantic analysis of the given friend type declaration. 16047 /// 16048 /// \returns A friend declaration that. 16049 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16050 SourceLocation FriendLoc, 16051 TypeSourceInfo *TSInfo) { 16052 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16053 16054 QualType T = TSInfo->getType(); 16055 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16056 16057 // C++03 [class.friend]p2: 16058 // An elaborated-type-specifier shall be used in a friend declaration 16059 // for a class.* 16060 // 16061 // * The class-key of the elaborated-type-specifier is required. 16062 if (!CodeSynthesisContexts.empty()) { 16063 // Do not complain about the form of friend template types during any kind 16064 // of code synthesis. For template instantiation, we will have complained 16065 // when the template was defined. 16066 } else { 16067 if (!T->isElaboratedTypeSpecifier()) { 16068 // If we evaluated the type to a record type, suggest putting 16069 // a tag in front. 16070 if (const RecordType *RT = T->getAs<RecordType>()) { 16071 RecordDecl *RD = RT->getDecl(); 16072 16073 SmallString<16> InsertionText(" "); 16074 InsertionText += RD->getKindName(); 16075 16076 Diag(TypeRange.getBegin(), 16077 getLangOpts().CPlusPlus11 ? 16078 diag::warn_cxx98_compat_unelaborated_friend_type : 16079 diag::ext_unelaborated_friend_type) 16080 << (unsigned) RD->getTagKind() 16081 << T 16082 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16083 InsertionText); 16084 } else { 16085 Diag(FriendLoc, 16086 getLangOpts().CPlusPlus11 ? 16087 diag::warn_cxx98_compat_nonclass_type_friend : 16088 diag::ext_nonclass_type_friend) 16089 << T 16090 << TypeRange; 16091 } 16092 } else if (T->getAs<EnumType>()) { 16093 Diag(FriendLoc, 16094 getLangOpts().CPlusPlus11 ? 16095 diag::warn_cxx98_compat_enum_friend : 16096 diag::ext_enum_friend) 16097 << T 16098 << TypeRange; 16099 } 16100 16101 // C++11 [class.friend]p3: 16102 // A friend declaration that does not declare a function shall have one 16103 // of the following forms: 16104 // friend elaborated-type-specifier ; 16105 // friend simple-type-specifier ; 16106 // friend typename-specifier ; 16107 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16108 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16109 } 16110 16111 // If the type specifier in a friend declaration designates a (possibly 16112 // cv-qualified) class type, that class is declared as a friend; otherwise, 16113 // the friend declaration is ignored. 16114 return FriendDecl::Create(Context, CurContext, 16115 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16116 FriendLoc); 16117 } 16118 16119 /// Handle a friend tag declaration where the scope specifier was 16120 /// templated. 16121 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16122 unsigned TagSpec, SourceLocation TagLoc, 16123 CXXScopeSpec &SS, IdentifierInfo *Name, 16124 SourceLocation NameLoc, 16125 const ParsedAttributesView &Attr, 16126 MultiTemplateParamsArg TempParamLists) { 16127 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16128 16129 bool IsMemberSpecialization = false; 16130 bool Invalid = false; 16131 16132 if (TemplateParameterList *TemplateParams = 16133 MatchTemplateParametersToScopeSpecifier( 16134 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16135 IsMemberSpecialization, Invalid)) { 16136 if (TemplateParams->size() > 0) { 16137 // This is a declaration of a class template. 16138 if (Invalid) 16139 return nullptr; 16140 16141 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16142 NameLoc, Attr, TemplateParams, AS_public, 16143 /*ModulePrivateLoc=*/SourceLocation(), 16144 FriendLoc, TempParamLists.size() - 1, 16145 TempParamLists.data()).get(); 16146 } else { 16147 // The "template<>" header is extraneous. 16148 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16149 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16150 IsMemberSpecialization = true; 16151 } 16152 } 16153 16154 if (Invalid) return nullptr; 16155 16156 bool isAllExplicitSpecializations = true; 16157 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16158 if (TempParamLists[I]->size()) { 16159 isAllExplicitSpecializations = false; 16160 break; 16161 } 16162 } 16163 16164 // FIXME: don't ignore attributes. 16165 16166 // If it's explicit specializations all the way down, just forget 16167 // about the template header and build an appropriate non-templated 16168 // friend. TODO: for source fidelity, remember the headers. 16169 if (isAllExplicitSpecializations) { 16170 if (SS.isEmpty()) { 16171 bool Owned = false; 16172 bool IsDependent = false; 16173 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16174 Attr, AS_public, 16175 /*ModulePrivateLoc=*/SourceLocation(), 16176 MultiTemplateParamsArg(), Owned, IsDependent, 16177 /*ScopedEnumKWLoc=*/SourceLocation(), 16178 /*ScopedEnumUsesClassTag=*/false, 16179 /*UnderlyingType=*/TypeResult(), 16180 /*IsTypeSpecifier=*/false, 16181 /*IsTemplateParamOrArg=*/false); 16182 } 16183 16184 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16185 ElaboratedTypeKeyword Keyword 16186 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16187 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16188 *Name, NameLoc); 16189 if (T.isNull()) 16190 return nullptr; 16191 16192 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16193 if (isa<DependentNameType>(T)) { 16194 DependentNameTypeLoc TL = 16195 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16196 TL.setElaboratedKeywordLoc(TagLoc); 16197 TL.setQualifierLoc(QualifierLoc); 16198 TL.setNameLoc(NameLoc); 16199 } else { 16200 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16201 TL.setElaboratedKeywordLoc(TagLoc); 16202 TL.setQualifierLoc(QualifierLoc); 16203 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16204 } 16205 16206 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16207 TSI, FriendLoc, TempParamLists); 16208 Friend->setAccess(AS_public); 16209 CurContext->addDecl(Friend); 16210 return Friend; 16211 } 16212 16213 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16214 16215 16216 16217 // Handle the case of a templated-scope friend class. e.g. 16218 // template <class T> class A<T>::B; 16219 // FIXME: we don't support these right now. 16220 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16221 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16222 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16223 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16224 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16225 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16226 TL.setElaboratedKeywordLoc(TagLoc); 16227 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16228 TL.setNameLoc(NameLoc); 16229 16230 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16231 TSI, FriendLoc, TempParamLists); 16232 Friend->setAccess(AS_public); 16233 Friend->setUnsupportedFriend(true); 16234 CurContext->addDecl(Friend); 16235 return Friend; 16236 } 16237 16238 /// Handle a friend type declaration. This works in tandem with 16239 /// ActOnTag. 16240 /// 16241 /// Notes on friend class templates: 16242 /// 16243 /// We generally treat friend class declarations as if they were 16244 /// declaring a class. So, for example, the elaborated type specifier 16245 /// in a friend declaration is required to obey the restrictions of a 16246 /// class-head (i.e. no typedefs in the scope chain), template 16247 /// parameters are required to match up with simple template-ids, &c. 16248 /// However, unlike when declaring a template specialization, it's 16249 /// okay to refer to a template specialization without an empty 16250 /// template parameter declaration, e.g. 16251 /// friend class A<T>::B<unsigned>; 16252 /// We permit this as a special case; if there are any template 16253 /// parameters present at all, require proper matching, i.e. 16254 /// template <> template \<class T> friend class A<int>::B; 16255 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16256 MultiTemplateParamsArg TempParams) { 16257 SourceLocation Loc = DS.getBeginLoc(); 16258 16259 assert(DS.isFriendSpecified()); 16260 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16261 16262 // C++ [class.friend]p3: 16263 // A friend declaration that does not declare a function shall have one of 16264 // the following forms: 16265 // friend elaborated-type-specifier ; 16266 // friend simple-type-specifier ; 16267 // friend typename-specifier ; 16268 // 16269 // Any declaration with a type qualifier does not have that form. (It's 16270 // legal to specify a qualified type as a friend, you just can't write the 16271 // keywords.) 16272 if (DS.getTypeQualifiers()) { 16273 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16274 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16275 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16276 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16277 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16278 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16279 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16280 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16281 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16282 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16283 } 16284 16285 // Try to convert the decl specifier to a type. This works for 16286 // friend templates because ActOnTag never produces a ClassTemplateDecl 16287 // for a TUK_Friend. 16288 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 16289 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16290 QualType T = TSI->getType(); 16291 if (TheDeclarator.isInvalidType()) 16292 return nullptr; 16293 16294 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16295 return nullptr; 16296 16297 // This is definitely an error in C++98. It's probably meant to 16298 // be forbidden in C++0x, too, but the specification is just 16299 // poorly written. 16300 // 16301 // The problem is with declarations like the following: 16302 // template <T> friend A<T>::foo; 16303 // where deciding whether a class C is a friend or not now hinges 16304 // on whether there exists an instantiation of A that causes 16305 // 'foo' to equal C. There are restrictions on class-heads 16306 // (which we declare (by fiat) elaborated friend declarations to 16307 // be) that makes this tractable. 16308 // 16309 // FIXME: handle "template <> friend class A<T>;", which 16310 // is possibly well-formed? Who even knows? 16311 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16312 Diag(Loc, diag::err_tagless_friend_type_template) 16313 << DS.getSourceRange(); 16314 return nullptr; 16315 } 16316 16317 // C++98 [class.friend]p1: A friend of a class is a function 16318 // or class that is not a member of the class . . . 16319 // This is fixed in DR77, which just barely didn't make the C++03 16320 // deadline. It's also a very silly restriction that seriously 16321 // affects inner classes and which nobody else seems to implement; 16322 // thus we never diagnose it, not even in -pedantic. 16323 // 16324 // But note that we could warn about it: it's always useless to 16325 // friend one of your own members (it's not, however, worthless to 16326 // friend a member of an arbitrary specialization of your template). 16327 16328 Decl *D; 16329 if (!TempParams.empty()) 16330 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16331 TempParams, 16332 TSI, 16333 DS.getFriendSpecLoc()); 16334 else 16335 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16336 16337 if (!D) 16338 return nullptr; 16339 16340 D->setAccess(AS_public); 16341 CurContext->addDecl(D); 16342 16343 return D; 16344 } 16345 16346 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16347 MultiTemplateParamsArg TemplateParams) { 16348 const DeclSpec &DS = D.getDeclSpec(); 16349 16350 assert(DS.isFriendSpecified()); 16351 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16352 16353 SourceLocation Loc = D.getIdentifierLoc(); 16354 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16355 16356 // C++ [class.friend]p1 16357 // A friend of a class is a function or class.... 16358 // Note that this sees through typedefs, which is intended. 16359 // It *doesn't* see through dependent types, which is correct 16360 // according to [temp.arg.type]p3: 16361 // If a declaration acquires a function type through a 16362 // type dependent on a template-parameter and this causes 16363 // a declaration that does not use the syntactic form of a 16364 // function declarator to have a function type, the program 16365 // is ill-formed. 16366 if (!TInfo->getType()->isFunctionType()) { 16367 Diag(Loc, diag::err_unexpected_friend); 16368 16369 // It might be worthwhile to try to recover by creating an 16370 // appropriate declaration. 16371 return nullptr; 16372 } 16373 16374 // C++ [namespace.memdef]p3 16375 // - If a friend declaration in a non-local class first declares a 16376 // class or function, the friend class or function is a member 16377 // of the innermost enclosing namespace. 16378 // - The name of the friend is not found by simple name lookup 16379 // until a matching declaration is provided in that namespace 16380 // scope (either before or after the class declaration granting 16381 // friendship). 16382 // - If a friend function is called, its name may be found by the 16383 // name lookup that considers functions from namespaces and 16384 // classes associated with the types of the function arguments. 16385 // - When looking for a prior declaration of a class or a function 16386 // declared as a friend, scopes outside the innermost enclosing 16387 // namespace scope are not considered. 16388 16389 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16390 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16391 assert(NameInfo.getName()); 16392 16393 // Check for unexpanded parameter packs. 16394 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16395 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16396 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16397 return nullptr; 16398 16399 // The context we found the declaration in, or in which we should 16400 // create the declaration. 16401 DeclContext *DC; 16402 Scope *DCScope = S; 16403 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16404 ForExternalRedeclaration); 16405 16406 // There are five cases here. 16407 // - There's no scope specifier and we're in a local class. Only look 16408 // for functions declared in the immediately-enclosing block scope. 16409 // We recover from invalid scope qualifiers as if they just weren't there. 16410 FunctionDecl *FunctionContainingLocalClass = nullptr; 16411 if ((SS.isInvalid() || !SS.isSet()) && 16412 (FunctionContainingLocalClass = 16413 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16414 // C++11 [class.friend]p11: 16415 // If a friend declaration appears in a local class and the name 16416 // specified is an unqualified name, a prior declaration is 16417 // looked up without considering scopes that are outside the 16418 // innermost enclosing non-class scope. For a friend function 16419 // declaration, if there is no prior declaration, the program is 16420 // ill-formed. 16421 16422 // Find the innermost enclosing non-class scope. This is the block 16423 // scope containing the local class definition (or for a nested class, 16424 // the outer local class). 16425 DCScope = S->getFnParent(); 16426 16427 // Look up the function name in the scope. 16428 Previous.clear(LookupLocalFriendName); 16429 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16430 16431 if (!Previous.empty()) { 16432 // All possible previous declarations must have the same context: 16433 // either they were declared at block scope or they are members of 16434 // one of the enclosing local classes. 16435 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16436 } else { 16437 // This is ill-formed, but provide the context that we would have 16438 // declared the function in, if we were permitted to, for error recovery. 16439 DC = FunctionContainingLocalClass; 16440 } 16441 adjustContextForLocalExternDecl(DC); 16442 16443 // C++ [class.friend]p6: 16444 // A function can be defined in a friend declaration of a class if and 16445 // only if the class is a non-local class (9.8), the function name is 16446 // unqualified, and the function has namespace scope. 16447 if (D.isFunctionDefinition()) { 16448 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16449 } 16450 16451 // - There's no scope specifier, in which case we just go to the 16452 // appropriate scope and look for a function or function template 16453 // there as appropriate. 16454 } else if (SS.isInvalid() || !SS.isSet()) { 16455 // C++11 [namespace.memdef]p3: 16456 // If the name in a friend declaration is neither qualified nor 16457 // a template-id and the declaration is a function or an 16458 // elaborated-type-specifier, the lookup to determine whether 16459 // the entity has been previously declared shall not consider 16460 // any scopes outside the innermost enclosing namespace. 16461 bool isTemplateId = 16462 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16463 16464 // Find the appropriate context according to the above. 16465 DC = CurContext; 16466 16467 // Skip class contexts. If someone can cite chapter and verse 16468 // for this behavior, that would be nice --- it's what GCC and 16469 // EDG do, and it seems like a reasonable intent, but the spec 16470 // really only says that checks for unqualified existing 16471 // declarations should stop at the nearest enclosing namespace, 16472 // not that they should only consider the nearest enclosing 16473 // namespace. 16474 while (DC->isRecord()) 16475 DC = DC->getParent(); 16476 16477 DeclContext *LookupDC = DC; 16478 while (LookupDC->isTransparentContext()) 16479 LookupDC = LookupDC->getParent(); 16480 16481 while (true) { 16482 LookupQualifiedName(Previous, LookupDC); 16483 16484 if (!Previous.empty()) { 16485 DC = LookupDC; 16486 break; 16487 } 16488 16489 if (isTemplateId) { 16490 if (isa<TranslationUnitDecl>(LookupDC)) break; 16491 } else { 16492 if (LookupDC->isFileContext()) break; 16493 } 16494 LookupDC = LookupDC->getParent(); 16495 } 16496 16497 DCScope = getScopeForDeclContext(S, DC); 16498 16499 // - There's a non-dependent scope specifier, in which case we 16500 // compute it and do a previous lookup there for a function 16501 // or function template. 16502 } else if (!SS.getScopeRep()->isDependent()) { 16503 DC = computeDeclContext(SS); 16504 if (!DC) return nullptr; 16505 16506 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16507 16508 LookupQualifiedName(Previous, DC); 16509 16510 // C++ [class.friend]p1: A friend of a class is a function or 16511 // class that is not a member of the class . . . 16512 if (DC->Equals(CurContext)) 16513 Diag(DS.getFriendSpecLoc(), 16514 getLangOpts().CPlusPlus11 ? 16515 diag::warn_cxx98_compat_friend_is_member : 16516 diag::err_friend_is_member); 16517 16518 if (D.isFunctionDefinition()) { 16519 // C++ [class.friend]p6: 16520 // A function can be defined in a friend declaration of a class if and 16521 // only if the class is a non-local class (9.8), the function name is 16522 // unqualified, and the function has namespace scope. 16523 // 16524 // FIXME: We should only do this if the scope specifier names the 16525 // innermost enclosing namespace; otherwise the fixit changes the 16526 // meaning of the code. 16527 SemaDiagnosticBuilder DB 16528 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16529 16530 DB << SS.getScopeRep(); 16531 if (DC->isFileContext()) 16532 DB << FixItHint::CreateRemoval(SS.getRange()); 16533 SS.clear(); 16534 } 16535 16536 // - There's a scope specifier that does not match any template 16537 // parameter lists, in which case we use some arbitrary context, 16538 // create a method or method template, and wait for instantiation. 16539 // - There's a scope specifier that does match some template 16540 // parameter lists, which we don't handle right now. 16541 } else { 16542 if (D.isFunctionDefinition()) { 16543 // C++ [class.friend]p6: 16544 // A function can be defined in a friend declaration of a class if and 16545 // only if the class is a non-local class (9.8), the function name is 16546 // unqualified, and the function has namespace scope. 16547 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16548 << SS.getScopeRep(); 16549 } 16550 16551 DC = CurContext; 16552 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16553 } 16554 16555 if (!DC->isRecord()) { 16556 int DiagArg = -1; 16557 switch (D.getName().getKind()) { 16558 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16559 case UnqualifiedIdKind::IK_ConstructorName: 16560 DiagArg = 0; 16561 break; 16562 case UnqualifiedIdKind::IK_DestructorName: 16563 DiagArg = 1; 16564 break; 16565 case UnqualifiedIdKind::IK_ConversionFunctionId: 16566 DiagArg = 2; 16567 break; 16568 case UnqualifiedIdKind::IK_DeductionGuideName: 16569 DiagArg = 3; 16570 break; 16571 case UnqualifiedIdKind::IK_Identifier: 16572 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16573 case UnqualifiedIdKind::IK_LiteralOperatorId: 16574 case UnqualifiedIdKind::IK_OperatorFunctionId: 16575 case UnqualifiedIdKind::IK_TemplateId: 16576 break; 16577 } 16578 // This implies that it has to be an operator or function. 16579 if (DiagArg >= 0) { 16580 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16581 return nullptr; 16582 } 16583 } 16584 16585 // FIXME: This is an egregious hack to cope with cases where the scope stack 16586 // does not contain the declaration context, i.e., in an out-of-line 16587 // definition of a class. 16588 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16589 if (!DCScope) { 16590 FakeDCScope.setEntity(DC); 16591 DCScope = &FakeDCScope; 16592 } 16593 16594 bool AddToScope = true; 16595 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16596 TemplateParams, AddToScope); 16597 if (!ND) return nullptr; 16598 16599 assert(ND->getLexicalDeclContext() == CurContext); 16600 16601 // If we performed typo correction, we might have added a scope specifier 16602 // and changed the decl context. 16603 DC = ND->getDeclContext(); 16604 16605 // Add the function declaration to the appropriate lookup tables, 16606 // adjusting the redeclarations list as necessary. We don't 16607 // want to do this yet if the friending class is dependent. 16608 // 16609 // Also update the scope-based lookup if the target context's 16610 // lookup context is in lexical scope. 16611 if (!CurContext->isDependentContext()) { 16612 DC = DC->getRedeclContext(); 16613 DC->makeDeclVisibleInContext(ND); 16614 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16615 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16616 } 16617 16618 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16619 D.getIdentifierLoc(), ND, 16620 DS.getFriendSpecLoc()); 16621 FrD->setAccess(AS_public); 16622 CurContext->addDecl(FrD); 16623 16624 if (ND->isInvalidDecl()) { 16625 FrD->setInvalidDecl(); 16626 } else { 16627 if (DC->isRecord()) CheckFriendAccess(ND); 16628 16629 FunctionDecl *FD; 16630 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16631 FD = FTD->getTemplatedDecl(); 16632 else 16633 FD = cast<FunctionDecl>(ND); 16634 16635 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16636 // default argument expression, that declaration shall be a definition 16637 // and shall be the only declaration of the function or function 16638 // template in the translation unit. 16639 if (functionDeclHasDefaultArgument(FD)) { 16640 // We can't look at FD->getPreviousDecl() because it may not have been set 16641 // if we're in a dependent context. If the function is known to be a 16642 // redeclaration, we will have narrowed Previous down to the right decl. 16643 if (D.isRedeclaration()) { 16644 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16645 Diag(Previous.getRepresentativeDecl()->getLocation(), 16646 diag::note_previous_declaration); 16647 } else if (!D.isFunctionDefinition()) 16648 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16649 } 16650 16651 // Mark templated-scope function declarations as unsupported. 16652 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16653 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16654 << SS.getScopeRep() << SS.getRange() 16655 << cast<CXXRecordDecl>(CurContext); 16656 FrD->setUnsupportedFriend(true); 16657 } 16658 } 16659 16660 return ND; 16661 } 16662 16663 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16664 AdjustDeclIfTemplate(Dcl); 16665 16666 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16667 if (!Fn) { 16668 Diag(DelLoc, diag::err_deleted_non_function); 16669 return; 16670 } 16671 16672 // Deleted function does not have a body. 16673 Fn->setWillHaveBody(false); 16674 16675 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16676 // Don't consider the implicit declaration we generate for explicit 16677 // specializations. FIXME: Do not generate these implicit declarations. 16678 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16679 Prev->getPreviousDecl()) && 16680 !Prev->isDefined()) { 16681 Diag(DelLoc, diag::err_deleted_decl_not_first); 16682 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16683 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16684 : diag::note_previous_declaration); 16685 // We can't recover from this; the declaration might have already 16686 // been used. 16687 Fn->setInvalidDecl(); 16688 return; 16689 } 16690 16691 // To maintain the invariant that functions are only deleted on their first 16692 // declaration, mark the implicitly-instantiated declaration of the 16693 // explicitly-specialized function as deleted instead of marking the 16694 // instantiated redeclaration. 16695 Fn = Fn->getCanonicalDecl(); 16696 } 16697 16698 // dllimport/dllexport cannot be deleted. 16699 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16700 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16701 Fn->setInvalidDecl(); 16702 } 16703 16704 // C++11 [basic.start.main]p3: 16705 // A program that defines main as deleted [...] is ill-formed. 16706 if (Fn->isMain()) 16707 Diag(DelLoc, diag::err_deleted_main); 16708 16709 // C++11 [dcl.fct.def.delete]p4: 16710 // A deleted function is implicitly inline. 16711 Fn->setImplicitlyInline(); 16712 Fn->setDeletedAsWritten(); 16713 } 16714 16715 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16716 if (!Dcl || Dcl->isInvalidDecl()) 16717 return; 16718 16719 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16720 if (!FD) { 16721 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16722 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16723 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16724 return; 16725 } 16726 } 16727 16728 Diag(DefaultLoc, diag::err_default_special_members) 16729 << getLangOpts().CPlusPlus20; 16730 return; 16731 } 16732 16733 // Reject if this can't possibly be a defaultable function. 16734 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16735 if (!DefKind && 16736 // A dependent function that doesn't locally look defaultable can 16737 // still instantiate to a defaultable function if it's a constructor 16738 // or assignment operator. 16739 (!FD->isDependentContext() || 16740 (!isa<CXXConstructorDecl>(FD) && 16741 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16742 Diag(DefaultLoc, diag::err_default_special_members) 16743 << getLangOpts().CPlusPlus20; 16744 return; 16745 } 16746 16747 if (DefKind.isComparison() && 16748 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16749 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16750 << (int)DefKind.asComparison(); 16751 return; 16752 } 16753 16754 // Issue compatibility warning. We already warned if the operator is 16755 // 'operator<=>' when parsing the '<=>' token. 16756 if (DefKind.isComparison() && 16757 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16758 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16759 ? diag::warn_cxx17_compat_defaulted_comparison 16760 : diag::ext_defaulted_comparison); 16761 } 16762 16763 FD->setDefaulted(); 16764 FD->setExplicitlyDefaulted(); 16765 16766 // Defer checking functions that are defaulted in a dependent context. 16767 if (FD->isDependentContext()) 16768 return; 16769 16770 // Unset that we will have a body for this function. We might not, 16771 // if it turns out to be trivial, and we don't need this marking now 16772 // that we've marked it as defaulted. 16773 FD->setWillHaveBody(false); 16774 16775 // If this definition appears within the record, do the checking when 16776 // the record is complete. This is always the case for a defaulted 16777 // comparison. 16778 if (DefKind.isComparison()) 16779 return; 16780 auto *MD = cast<CXXMethodDecl>(FD); 16781 16782 const FunctionDecl *Primary = FD; 16783 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16784 // Ask the template instantiation pattern that actually had the 16785 // '= default' on it. 16786 Primary = Pattern; 16787 16788 // If the method was defaulted on its first declaration, we will have 16789 // already performed the checking in CheckCompletedCXXClass. Such a 16790 // declaration doesn't trigger an implicit definition. 16791 if (Primary->getCanonicalDecl()->isDefaulted()) 16792 return; 16793 16794 // FIXME: Once we support defining comparisons out of class, check for a 16795 // defaulted comparison here. 16796 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16797 MD->setInvalidDecl(); 16798 else 16799 DefineDefaultedFunction(*this, MD, DefaultLoc); 16800 } 16801 16802 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16803 for (Stmt *SubStmt : S->children()) { 16804 if (!SubStmt) 16805 continue; 16806 if (isa<ReturnStmt>(SubStmt)) 16807 Self.Diag(SubStmt->getBeginLoc(), 16808 diag::err_return_in_constructor_handler); 16809 if (!isa<Expr>(SubStmt)) 16810 SearchForReturnInStmt(Self, SubStmt); 16811 } 16812 } 16813 16814 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16815 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16816 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16817 SearchForReturnInStmt(*this, Handler); 16818 } 16819 } 16820 16821 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16822 const CXXMethodDecl *Old) { 16823 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16824 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16825 16826 if (OldFT->hasExtParameterInfos()) { 16827 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16828 // A parameter of the overriding method should be annotated with noescape 16829 // if the corresponding parameter of the overridden method is annotated. 16830 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16831 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16832 Diag(New->getParamDecl(I)->getLocation(), 16833 diag::warn_overriding_method_missing_noescape); 16834 Diag(Old->getParamDecl(I)->getLocation(), 16835 diag::note_overridden_marked_noescape); 16836 } 16837 } 16838 16839 // Virtual overrides must have the same code_seg. 16840 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16841 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16842 if ((NewCSA || OldCSA) && 16843 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16844 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16845 Diag(Old->getLocation(), diag::note_previous_declaration); 16846 return true; 16847 } 16848 16849 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16850 16851 // If the calling conventions match, everything is fine 16852 if (NewCC == OldCC) 16853 return false; 16854 16855 // If the calling conventions mismatch because the new function is static, 16856 // suppress the calling convention mismatch error; the error about static 16857 // function override (err_static_overrides_virtual from 16858 // Sema::CheckFunctionDeclaration) is more clear. 16859 if (New->getStorageClass() == SC_Static) 16860 return false; 16861 16862 Diag(New->getLocation(), 16863 diag::err_conflicting_overriding_cc_attributes) 16864 << New->getDeclName() << New->getType() << Old->getType(); 16865 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16866 return true; 16867 } 16868 16869 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16870 const CXXMethodDecl *Old) { 16871 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 16872 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 16873 16874 if (Context.hasSameType(NewTy, OldTy) || 16875 NewTy->isDependentType() || OldTy->isDependentType()) 16876 return false; 16877 16878 // Check if the return types are covariant 16879 QualType NewClassTy, OldClassTy; 16880 16881 /// Both types must be pointers or references to classes. 16882 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16883 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16884 NewClassTy = NewPT->getPointeeType(); 16885 OldClassTy = OldPT->getPointeeType(); 16886 } 16887 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16888 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16889 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16890 NewClassTy = NewRT->getPointeeType(); 16891 OldClassTy = OldRT->getPointeeType(); 16892 } 16893 } 16894 } 16895 16896 // The return types aren't either both pointers or references to a class type. 16897 if (NewClassTy.isNull()) { 16898 Diag(New->getLocation(), 16899 diag::err_different_return_type_for_overriding_virtual_function) 16900 << New->getDeclName() << NewTy << OldTy 16901 << New->getReturnTypeSourceRange(); 16902 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16903 << Old->getReturnTypeSourceRange(); 16904 16905 return true; 16906 } 16907 16908 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16909 // C++14 [class.virtual]p8: 16910 // If the class type in the covariant return type of D::f differs from 16911 // that of B::f, the class type in the return type of D::f shall be 16912 // complete at the point of declaration of D::f or shall be the class 16913 // type D. 16914 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16915 if (!RT->isBeingDefined() && 16916 RequireCompleteType(New->getLocation(), NewClassTy, 16917 diag::err_covariant_return_incomplete, 16918 New->getDeclName())) 16919 return true; 16920 } 16921 16922 // Check if the new class derives from the old class. 16923 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 16924 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 16925 << New->getDeclName() << NewTy << OldTy 16926 << New->getReturnTypeSourceRange(); 16927 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16928 << Old->getReturnTypeSourceRange(); 16929 return true; 16930 } 16931 16932 // Check if we the conversion from derived to base is valid. 16933 if (CheckDerivedToBaseConversion( 16934 NewClassTy, OldClassTy, 16935 diag::err_covariant_return_inaccessible_base, 16936 diag::err_covariant_return_ambiguous_derived_to_base_conv, 16937 New->getLocation(), New->getReturnTypeSourceRange(), 16938 New->getDeclName(), nullptr)) { 16939 // FIXME: this note won't trigger for delayed access control 16940 // diagnostics, and it's impossible to get an undelayed error 16941 // here from access control during the original parse because 16942 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 16943 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16944 << Old->getReturnTypeSourceRange(); 16945 return true; 16946 } 16947 } 16948 16949 // The qualifiers of the return types must be the same. 16950 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 16951 Diag(New->getLocation(), 16952 diag::err_covariant_return_type_different_qualifications) 16953 << New->getDeclName() << NewTy << OldTy 16954 << New->getReturnTypeSourceRange(); 16955 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16956 << Old->getReturnTypeSourceRange(); 16957 return true; 16958 } 16959 16960 16961 // The new class type must have the same or less qualifiers as the old type. 16962 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 16963 Diag(New->getLocation(), 16964 diag::err_covariant_return_type_class_type_more_qualified) 16965 << New->getDeclName() << NewTy << OldTy 16966 << New->getReturnTypeSourceRange(); 16967 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16968 << Old->getReturnTypeSourceRange(); 16969 return true; 16970 } 16971 16972 return false; 16973 } 16974 16975 /// Mark the given method pure. 16976 /// 16977 /// \param Method the method to be marked pure. 16978 /// 16979 /// \param InitRange the source range that covers the "0" initializer. 16980 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 16981 SourceLocation EndLoc = InitRange.getEnd(); 16982 if (EndLoc.isValid()) 16983 Method->setRangeEnd(EndLoc); 16984 16985 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 16986 Method->setPure(); 16987 return false; 16988 } 16989 16990 if (!Method->isInvalidDecl()) 16991 Diag(Method->getLocation(), diag::err_non_virtual_pure) 16992 << Method->getDeclName() << InitRange; 16993 return true; 16994 } 16995 16996 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 16997 if (D->getFriendObjectKind()) 16998 Diag(D->getLocation(), diag::err_pure_friend); 16999 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17000 CheckPureMethod(M, ZeroLoc); 17001 else 17002 Diag(D->getLocation(), diag::err_illegal_initializer); 17003 } 17004 17005 /// Determine whether the given declaration is a global variable or 17006 /// static data member. 17007 static bool isNonlocalVariable(const Decl *D) { 17008 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17009 return Var->hasGlobalStorage(); 17010 17011 return false; 17012 } 17013 17014 /// Invoked when we are about to parse an initializer for the declaration 17015 /// 'Dcl'. 17016 /// 17017 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17018 /// static data member of class X, names should be looked up in the scope of 17019 /// class X. If the declaration had a scope specifier, a scope will have 17020 /// been created and passed in for this purpose. Otherwise, S will be null. 17021 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17022 // If there is no declaration, there was an error parsing it. 17023 if (!D || D->isInvalidDecl()) 17024 return; 17025 17026 // We will always have a nested name specifier here, but this declaration 17027 // might not be out of line if the specifier names the current namespace: 17028 // extern int n; 17029 // int ::n = 0; 17030 if (S && D->isOutOfLine()) 17031 EnterDeclaratorContext(S, D->getDeclContext()); 17032 17033 // If we are parsing the initializer for a static data member, push a 17034 // new expression evaluation context that is associated with this static 17035 // data member. 17036 if (isNonlocalVariable(D)) 17037 PushExpressionEvaluationContext( 17038 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17039 } 17040 17041 /// Invoked after we are finished parsing an initializer for the declaration D. 17042 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17043 // If there is no declaration, there was an error parsing it. 17044 if (!D || D->isInvalidDecl()) 17045 return; 17046 17047 if (isNonlocalVariable(D)) 17048 PopExpressionEvaluationContext(); 17049 17050 if (S && D->isOutOfLine()) 17051 ExitDeclaratorContext(S); 17052 } 17053 17054 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17055 /// C++ if/switch/while/for statement. 17056 /// e.g: "if (int x = f()) {...}" 17057 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17058 // C++ 6.4p2: 17059 // The declarator shall not specify a function or an array. 17060 // The type-specifier-seq shall not contain typedef and shall not declare a 17061 // new class or enumeration. 17062 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17063 "Parser allowed 'typedef' as storage class of condition decl."); 17064 17065 Decl *Dcl = ActOnDeclarator(S, D); 17066 if (!Dcl) 17067 return true; 17068 17069 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17070 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17071 << D.getSourceRange(); 17072 return true; 17073 } 17074 17075 return Dcl; 17076 } 17077 17078 void Sema::LoadExternalVTableUses() { 17079 if (!ExternalSource) 17080 return; 17081 17082 SmallVector<ExternalVTableUse, 4> VTables; 17083 ExternalSource->ReadUsedVTables(VTables); 17084 SmallVector<VTableUse, 4> NewUses; 17085 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17086 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17087 = VTablesUsed.find(VTables[I].Record); 17088 // Even if a definition wasn't required before, it may be required now. 17089 if (Pos != VTablesUsed.end()) { 17090 if (!Pos->second && VTables[I].DefinitionRequired) 17091 Pos->second = true; 17092 continue; 17093 } 17094 17095 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17096 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17097 } 17098 17099 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17100 } 17101 17102 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17103 bool DefinitionRequired) { 17104 // Ignore any vtable uses in unevaluated operands or for classes that do 17105 // not have a vtable. 17106 if (!Class->isDynamicClass() || Class->isDependentContext() || 17107 CurContext->isDependentContext() || isUnevaluatedContext()) 17108 return; 17109 // Do not mark as used if compiling for the device outside of the target 17110 // region. 17111 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17112 !isInOpenMPDeclareTargetContext() && 17113 !isInOpenMPTargetExecutionDirective()) { 17114 if (!DefinitionRequired) 17115 MarkVirtualMembersReferenced(Loc, Class); 17116 return; 17117 } 17118 17119 // Try to insert this class into the map. 17120 LoadExternalVTableUses(); 17121 Class = Class->getCanonicalDecl(); 17122 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17123 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17124 if (!Pos.second) { 17125 // If we already had an entry, check to see if we are promoting this vtable 17126 // to require a definition. If so, we need to reappend to the VTableUses 17127 // list, since we may have already processed the first entry. 17128 if (DefinitionRequired && !Pos.first->second) { 17129 Pos.first->second = true; 17130 } else { 17131 // Otherwise, we can early exit. 17132 return; 17133 } 17134 } else { 17135 // The Microsoft ABI requires that we perform the destructor body 17136 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17137 // the deleting destructor is emitted with the vtable, not with the 17138 // destructor definition as in the Itanium ABI. 17139 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17140 CXXDestructorDecl *DD = Class->getDestructor(); 17141 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17142 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17143 // If this is an out-of-line declaration, marking it referenced will 17144 // not do anything. Manually call CheckDestructor to look up operator 17145 // delete(). 17146 ContextRAII SavedContext(*this, DD); 17147 CheckDestructor(DD); 17148 } else { 17149 MarkFunctionReferenced(Loc, Class->getDestructor()); 17150 } 17151 } 17152 } 17153 } 17154 17155 // Local classes need to have their virtual members marked 17156 // immediately. For all other classes, we mark their virtual members 17157 // at the end of the translation unit. 17158 if (Class->isLocalClass()) 17159 MarkVirtualMembersReferenced(Loc, Class); 17160 else 17161 VTableUses.push_back(std::make_pair(Class, Loc)); 17162 } 17163 17164 bool Sema::DefineUsedVTables() { 17165 LoadExternalVTableUses(); 17166 if (VTableUses.empty()) 17167 return false; 17168 17169 // Note: The VTableUses vector could grow as a result of marking 17170 // the members of a class as "used", so we check the size each 17171 // time through the loop and prefer indices (which are stable) to 17172 // iterators (which are not). 17173 bool DefinedAnything = false; 17174 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17175 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17176 if (!Class) 17177 continue; 17178 TemplateSpecializationKind ClassTSK = 17179 Class->getTemplateSpecializationKind(); 17180 17181 SourceLocation Loc = VTableUses[I].second; 17182 17183 bool DefineVTable = true; 17184 17185 // If this class has a key function, but that key function is 17186 // defined in another translation unit, we don't need to emit the 17187 // vtable even though we're using it. 17188 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17189 if (KeyFunction && !KeyFunction->hasBody()) { 17190 // The key function is in another translation unit. 17191 DefineVTable = false; 17192 TemplateSpecializationKind TSK = 17193 KeyFunction->getTemplateSpecializationKind(); 17194 assert(TSK != TSK_ExplicitInstantiationDefinition && 17195 TSK != TSK_ImplicitInstantiation && 17196 "Instantiations don't have key functions"); 17197 (void)TSK; 17198 } else if (!KeyFunction) { 17199 // If we have a class with no key function that is the subject 17200 // of an explicit instantiation declaration, suppress the 17201 // vtable; it will live with the explicit instantiation 17202 // definition. 17203 bool IsExplicitInstantiationDeclaration = 17204 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17205 for (auto R : Class->redecls()) { 17206 TemplateSpecializationKind TSK 17207 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17208 if (TSK == TSK_ExplicitInstantiationDeclaration) 17209 IsExplicitInstantiationDeclaration = true; 17210 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17211 IsExplicitInstantiationDeclaration = false; 17212 break; 17213 } 17214 } 17215 17216 if (IsExplicitInstantiationDeclaration) 17217 DefineVTable = false; 17218 } 17219 17220 // The exception specifications for all virtual members may be needed even 17221 // if we are not providing an authoritative form of the vtable in this TU. 17222 // We may choose to emit it available_externally anyway. 17223 if (!DefineVTable) { 17224 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17225 continue; 17226 } 17227 17228 // Mark all of the virtual members of this class as referenced, so 17229 // that we can build a vtable. Then, tell the AST consumer that a 17230 // vtable for this class is required. 17231 DefinedAnything = true; 17232 MarkVirtualMembersReferenced(Loc, Class); 17233 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17234 if (VTablesUsed[Canonical]) 17235 Consumer.HandleVTable(Class); 17236 17237 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17238 // no key function or the key function is inlined. Don't warn in C++ ABIs 17239 // that lack key functions, since the user won't be able to make one. 17240 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17241 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17242 const FunctionDecl *KeyFunctionDef = nullptr; 17243 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17244 KeyFunctionDef->isInlined())) { 17245 Diag(Class->getLocation(), 17246 ClassTSK == TSK_ExplicitInstantiationDefinition 17247 ? diag::warn_weak_template_vtable 17248 : diag::warn_weak_vtable) 17249 << Class; 17250 } 17251 } 17252 } 17253 VTableUses.clear(); 17254 17255 return DefinedAnything; 17256 } 17257 17258 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17259 const CXXRecordDecl *RD) { 17260 for (const auto *I : RD->methods()) 17261 if (I->isVirtual() && !I->isPure()) 17262 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17263 } 17264 17265 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17266 const CXXRecordDecl *RD, 17267 bool ConstexprOnly) { 17268 // Mark all functions which will appear in RD's vtable as used. 17269 CXXFinalOverriderMap FinalOverriders; 17270 RD->getFinalOverriders(FinalOverriders); 17271 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17272 E = FinalOverriders.end(); 17273 I != E; ++I) { 17274 for (OverridingMethods::const_iterator OI = I->second.begin(), 17275 OE = I->second.end(); 17276 OI != OE; ++OI) { 17277 assert(OI->second.size() > 0 && "no final overrider"); 17278 CXXMethodDecl *Overrider = OI->second.front().Method; 17279 17280 // C++ [basic.def.odr]p2: 17281 // [...] A virtual member function is used if it is not pure. [...] 17282 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17283 MarkFunctionReferenced(Loc, Overrider); 17284 } 17285 } 17286 17287 // Only classes that have virtual bases need a VTT. 17288 if (RD->getNumVBases() == 0) 17289 return; 17290 17291 for (const auto &I : RD->bases()) { 17292 const auto *Base = 17293 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17294 if (Base->getNumVBases() == 0) 17295 continue; 17296 MarkVirtualMembersReferenced(Loc, Base); 17297 } 17298 } 17299 17300 /// SetIvarInitializers - This routine builds initialization ASTs for the 17301 /// Objective-C implementation whose ivars need be initialized. 17302 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17303 if (!getLangOpts().CPlusPlus) 17304 return; 17305 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17306 SmallVector<ObjCIvarDecl*, 8> ivars; 17307 CollectIvarsToConstructOrDestruct(OID, ivars); 17308 if (ivars.empty()) 17309 return; 17310 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17311 for (unsigned i = 0; i < ivars.size(); i++) { 17312 FieldDecl *Field = ivars[i]; 17313 if (Field->isInvalidDecl()) 17314 continue; 17315 17316 CXXCtorInitializer *Member; 17317 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17318 InitializationKind InitKind = 17319 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17320 17321 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17322 ExprResult MemberInit = 17323 InitSeq.Perform(*this, InitEntity, InitKind, None); 17324 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17325 // Note, MemberInit could actually come back empty if no initialization 17326 // is required (e.g., because it would call a trivial default constructor) 17327 if (!MemberInit.get() || MemberInit.isInvalid()) 17328 continue; 17329 17330 Member = 17331 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17332 SourceLocation(), 17333 MemberInit.getAs<Expr>(), 17334 SourceLocation()); 17335 AllToInit.push_back(Member); 17336 17337 // Be sure that the destructor is accessible and is marked as referenced. 17338 if (const RecordType *RecordTy = 17339 Context.getBaseElementType(Field->getType()) 17340 ->getAs<RecordType>()) { 17341 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17342 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17343 MarkFunctionReferenced(Field->getLocation(), Destructor); 17344 CheckDestructorAccess(Field->getLocation(), Destructor, 17345 PDiag(diag::err_access_dtor_ivar) 17346 << Context.getBaseElementType(Field->getType())); 17347 } 17348 } 17349 } 17350 ObjCImplementation->setIvarInitializers(Context, 17351 AllToInit.data(), AllToInit.size()); 17352 } 17353 } 17354 17355 static 17356 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17357 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17358 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17359 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17360 Sema &S) { 17361 if (Ctor->isInvalidDecl()) 17362 return; 17363 17364 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17365 17366 // Target may not be determinable yet, for instance if this is a dependent 17367 // call in an uninstantiated template. 17368 if (Target) { 17369 const FunctionDecl *FNTarget = nullptr; 17370 (void)Target->hasBody(FNTarget); 17371 Target = const_cast<CXXConstructorDecl*>( 17372 cast_or_null<CXXConstructorDecl>(FNTarget)); 17373 } 17374 17375 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17376 // Avoid dereferencing a null pointer here. 17377 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17378 17379 if (!Current.insert(Canonical).second) 17380 return; 17381 17382 // We know that beyond here, we aren't chaining into a cycle. 17383 if (!Target || !Target->isDelegatingConstructor() || 17384 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17385 Valid.insert(Current.begin(), Current.end()); 17386 Current.clear(); 17387 // We've hit a cycle. 17388 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17389 Current.count(TCanonical)) { 17390 // If we haven't diagnosed this cycle yet, do so now. 17391 if (!Invalid.count(TCanonical)) { 17392 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17393 diag::warn_delegating_ctor_cycle) 17394 << Ctor; 17395 17396 // Don't add a note for a function delegating directly to itself. 17397 if (TCanonical != Canonical) 17398 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17399 17400 CXXConstructorDecl *C = Target; 17401 while (C->getCanonicalDecl() != Canonical) { 17402 const FunctionDecl *FNTarget = nullptr; 17403 (void)C->getTargetConstructor()->hasBody(FNTarget); 17404 assert(FNTarget && "Ctor cycle through bodiless function"); 17405 17406 C = const_cast<CXXConstructorDecl*>( 17407 cast<CXXConstructorDecl>(FNTarget)); 17408 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17409 } 17410 } 17411 17412 Invalid.insert(Current.begin(), Current.end()); 17413 Current.clear(); 17414 } else { 17415 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17416 } 17417 } 17418 17419 17420 void Sema::CheckDelegatingCtorCycles() { 17421 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17422 17423 for (DelegatingCtorDeclsType::iterator 17424 I = DelegatingCtorDecls.begin(ExternalSource), 17425 E = DelegatingCtorDecls.end(); 17426 I != E; ++I) 17427 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17428 17429 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17430 (*CI)->setInvalidDecl(); 17431 } 17432 17433 namespace { 17434 /// AST visitor that finds references to the 'this' expression. 17435 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17436 Sema &S; 17437 17438 public: 17439 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17440 17441 bool VisitCXXThisExpr(CXXThisExpr *E) { 17442 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17443 << E->isImplicit(); 17444 return false; 17445 } 17446 }; 17447 } 17448 17449 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17450 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17451 if (!TSInfo) 17452 return false; 17453 17454 TypeLoc TL = TSInfo->getTypeLoc(); 17455 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17456 if (!ProtoTL) 17457 return false; 17458 17459 // C++11 [expr.prim.general]p3: 17460 // [The expression this] shall not appear before the optional 17461 // cv-qualifier-seq and it shall not appear within the declaration of a 17462 // static member function (although its type and value category are defined 17463 // within a static member function as they are within a non-static member 17464 // function). [ Note: this is because declaration matching does not occur 17465 // until the complete declarator is known. - end note ] 17466 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17467 FindCXXThisExpr Finder(*this); 17468 17469 // If the return type came after the cv-qualifier-seq, check it now. 17470 if (Proto->hasTrailingReturn() && 17471 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17472 return true; 17473 17474 // Check the exception specification. 17475 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17476 return true; 17477 17478 // Check the trailing requires clause 17479 if (Expr *E = Method->getTrailingRequiresClause()) 17480 if (!Finder.TraverseStmt(E)) 17481 return true; 17482 17483 return checkThisInStaticMemberFunctionAttributes(Method); 17484 } 17485 17486 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17487 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17488 if (!TSInfo) 17489 return false; 17490 17491 TypeLoc TL = TSInfo->getTypeLoc(); 17492 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17493 if (!ProtoTL) 17494 return false; 17495 17496 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17497 FindCXXThisExpr Finder(*this); 17498 17499 switch (Proto->getExceptionSpecType()) { 17500 case EST_Unparsed: 17501 case EST_Uninstantiated: 17502 case EST_Unevaluated: 17503 case EST_BasicNoexcept: 17504 case EST_NoThrow: 17505 case EST_DynamicNone: 17506 case EST_MSAny: 17507 case EST_None: 17508 break; 17509 17510 case EST_DependentNoexcept: 17511 case EST_NoexceptFalse: 17512 case EST_NoexceptTrue: 17513 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17514 return true; 17515 LLVM_FALLTHROUGH; 17516 17517 case EST_Dynamic: 17518 for (const auto &E : Proto->exceptions()) { 17519 if (!Finder.TraverseType(E)) 17520 return true; 17521 } 17522 break; 17523 } 17524 17525 return false; 17526 } 17527 17528 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17529 FindCXXThisExpr Finder(*this); 17530 17531 // Check attributes. 17532 for (const auto *A : Method->attrs()) { 17533 // FIXME: This should be emitted by tblgen. 17534 Expr *Arg = nullptr; 17535 ArrayRef<Expr *> Args; 17536 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17537 Arg = G->getArg(); 17538 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17539 Arg = G->getArg(); 17540 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17541 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17542 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17543 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17544 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17545 Arg = ETLF->getSuccessValue(); 17546 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17547 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17548 Arg = STLF->getSuccessValue(); 17549 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17550 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17551 Arg = LR->getArg(); 17552 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17553 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17554 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17555 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17556 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17557 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17558 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17559 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17560 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17561 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17562 17563 if (Arg && !Finder.TraverseStmt(Arg)) 17564 return true; 17565 17566 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17567 if (!Finder.TraverseStmt(Args[I])) 17568 return true; 17569 } 17570 } 17571 17572 return false; 17573 } 17574 17575 void Sema::checkExceptionSpecification( 17576 bool IsTopLevel, ExceptionSpecificationType EST, 17577 ArrayRef<ParsedType> DynamicExceptions, 17578 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17579 SmallVectorImpl<QualType> &Exceptions, 17580 FunctionProtoType::ExceptionSpecInfo &ESI) { 17581 Exceptions.clear(); 17582 ESI.Type = EST; 17583 if (EST == EST_Dynamic) { 17584 Exceptions.reserve(DynamicExceptions.size()); 17585 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17586 // FIXME: Preserve type source info. 17587 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17588 17589 if (IsTopLevel) { 17590 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17591 collectUnexpandedParameterPacks(ET, Unexpanded); 17592 if (!Unexpanded.empty()) { 17593 DiagnoseUnexpandedParameterPacks( 17594 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17595 Unexpanded); 17596 continue; 17597 } 17598 } 17599 17600 // Check that the type is valid for an exception spec, and 17601 // drop it if not. 17602 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17603 Exceptions.push_back(ET); 17604 } 17605 ESI.Exceptions = Exceptions; 17606 return; 17607 } 17608 17609 if (isComputedNoexcept(EST)) { 17610 assert((NoexceptExpr->isTypeDependent() || 17611 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17612 Context.BoolTy) && 17613 "Parser should have made sure that the expression is boolean"); 17614 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17615 ESI.Type = EST_BasicNoexcept; 17616 return; 17617 } 17618 17619 ESI.NoexceptExpr = NoexceptExpr; 17620 return; 17621 } 17622 } 17623 17624 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17625 ExceptionSpecificationType EST, 17626 SourceRange SpecificationRange, 17627 ArrayRef<ParsedType> DynamicExceptions, 17628 ArrayRef<SourceRange> DynamicExceptionRanges, 17629 Expr *NoexceptExpr) { 17630 if (!MethodD) 17631 return; 17632 17633 // Dig out the method we're referring to. 17634 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17635 MethodD = FunTmpl->getTemplatedDecl(); 17636 17637 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17638 if (!Method) 17639 return; 17640 17641 // Check the exception specification. 17642 llvm::SmallVector<QualType, 4> Exceptions; 17643 FunctionProtoType::ExceptionSpecInfo ESI; 17644 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17645 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17646 ESI); 17647 17648 // Update the exception specification on the function type. 17649 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17650 17651 if (Method->isStatic()) 17652 checkThisInStaticMemberFunctionExceptionSpec(Method); 17653 17654 if (Method->isVirtual()) { 17655 // Check overrides, which we previously had to delay. 17656 for (const CXXMethodDecl *O : Method->overridden_methods()) 17657 CheckOverridingFunctionExceptionSpec(Method, O); 17658 } 17659 } 17660 17661 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17662 /// 17663 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17664 SourceLocation DeclStart, Declarator &D, 17665 Expr *BitWidth, 17666 InClassInitStyle InitStyle, 17667 AccessSpecifier AS, 17668 const ParsedAttr &MSPropertyAttr) { 17669 IdentifierInfo *II = D.getIdentifier(); 17670 if (!II) { 17671 Diag(DeclStart, diag::err_anonymous_property); 17672 return nullptr; 17673 } 17674 SourceLocation Loc = D.getIdentifierLoc(); 17675 17676 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17677 QualType T = TInfo->getType(); 17678 if (getLangOpts().CPlusPlus) { 17679 CheckExtraCXXDefaultArguments(D); 17680 17681 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17682 UPPC_DataMemberType)) { 17683 D.setInvalidType(); 17684 T = Context.IntTy; 17685 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17686 } 17687 } 17688 17689 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17690 17691 if (D.getDeclSpec().isInlineSpecified()) 17692 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17693 << getLangOpts().CPlusPlus17; 17694 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17695 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17696 diag::err_invalid_thread) 17697 << DeclSpec::getSpecifierName(TSCS); 17698 17699 // Check to see if this name was declared as a member previously 17700 NamedDecl *PrevDecl = nullptr; 17701 LookupResult Previous(*this, II, Loc, LookupMemberName, 17702 ForVisibleRedeclaration); 17703 LookupName(Previous, S); 17704 switch (Previous.getResultKind()) { 17705 case LookupResult::Found: 17706 case LookupResult::FoundUnresolvedValue: 17707 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17708 break; 17709 17710 case LookupResult::FoundOverloaded: 17711 PrevDecl = Previous.getRepresentativeDecl(); 17712 break; 17713 17714 case LookupResult::NotFound: 17715 case LookupResult::NotFoundInCurrentInstantiation: 17716 case LookupResult::Ambiguous: 17717 break; 17718 } 17719 17720 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17721 // Maybe we will complain about the shadowed template parameter. 17722 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17723 // Just pretend that we didn't see the previous declaration. 17724 PrevDecl = nullptr; 17725 } 17726 17727 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17728 PrevDecl = nullptr; 17729 17730 SourceLocation TSSL = D.getBeginLoc(); 17731 MSPropertyDecl *NewPD = 17732 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17733 MSPropertyAttr.getPropertyDataGetter(), 17734 MSPropertyAttr.getPropertyDataSetter()); 17735 ProcessDeclAttributes(TUScope, NewPD, D); 17736 NewPD->setAccess(AS); 17737 17738 if (NewPD->isInvalidDecl()) 17739 Record->setInvalidDecl(); 17740 17741 if (D.getDeclSpec().isModulePrivateSpecified()) 17742 NewPD->setModulePrivate(); 17743 17744 if (NewPD->isInvalidDecl() && PrevDecl) { 17745 // Don't introduce NewFD into scope; there's already something 17746 // with the same name in the same scope. 17747 } else if (II) { 17748 PushOnScopeChains(NewPD, S); 17749 } else 17750 Record->addDecl(NewPD); 17751 17752 return NewPD; 17753 } 17754 17755 void Sema::ActOnStartFunctionDeclarationDeclarator( 17756 Declarator &Declarator, unsigned TemplateParameterDepth) { 17757 auto &Info = InventedParameterInfos.emplace_back(); 17758 TemplateParameterList *ExplicitParams = nullptr; 17759 ArrayRef<TemplateParameterList *> ExplicitLists = 17760 Declarator.getTemplateParameterLists(); 17761 if (!ExplicitLists.empty()) { 17762 bool IsMemberSpecialization, IsInvalid; 17763 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17764 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17765 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17766 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17767 /*SuppressDiagnostic=*/true); 17768 } 17769 if (ExplicitParams) { 17770 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17771 for (NamedDecl *Param : *ExplicitParams) 17772 Info.TemplateParams.push_back(Param); 17773 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17774 } else { 17775 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17776 Info.NumExplicitTemplateParams = 0; 17777 } 17778 } 17779 17780 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17781 auto &FSI = InventedParameterInfos.back(); 17782 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17783 if (FSI.NumExplicitTemplateParams != 0) { 17784 TemplateParameterList *ExplicitParams = 17785 Declarator.getTemplateParameterLists().back(); 17786 Declarator.setInventedTemplateParameterList( 17787 TemplateParameterList::Create( 17788 Context, ExplicitParams->getTemplateLoc(), 17789 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17790 ExplicitParams->getRAngleLoc(), 17791 ExplicitParams->getRequiresClause())); 17792 } else { 17793 Declarator.setInventedTemplateParameterList( 17794 TemplateParameterList::Create( 17795 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17796 SourceLocation(), /*RequiresClause=*/nullptr)); 17797 } 17798 } 17799 InventedParameterInfos.pop_back(); 17800 } 17801