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/STLExtras.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/StringExtras.h" 44 #include <map> 45 #include <set> 46 47 using namespace clang; 48 49 //===----------------------------------------------------------------------===// 50 // CheckDefaultArgumentVisitor 51 //===----------------------------------------------------------------------===// 52 53 namespace { 54 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 55 /// the default argument of a parameter to determine whether it 56 /// contains any ill-formed subexpressions. For example, this will 57 /// diagnose the use of local variables or parameters within the 58 /// default argument expression. 59 class CheckDefaultArgumentVisitor 60 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 61 Expr *DefaultArg; 62 Sema *S; 63 64 public: 65 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 66 : DefaultArg(defarg), S(s) {} 67 68 bool VisitExpr(Expr *Node); 69 bool VisitDeclRefExpr(DeclRefExpr *DRE); 70 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 71 bool VisitLambdaExpr(LambdaExpr *Lambda); 72 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 73 }; 74 75 /// VisitExpr - Visit all of the children of this expression. 76 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 77 bool IsInvalid = false; 78 for (Stmt *SubStmt : Node->children()) 79 IsInvalid |= Visit(SubStmt); 80 return IsInvalid; 81 } 82 83 /// VisitDeclRefExpr - Visit a reference to a declaration, to 84 /// determine whether this declaration can be used in the default 85 /// argument expression. 86 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 87 NamedDecl *Decl = DRE->getDecl(); 88 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 89 // C++ [dcl.fct.default]p9 90 // Default arguments are evaluated each time the function is 91 // called. The order of evaluation of function arguments is 92 // unspecified. Consequently, parameters of a function shall not 93 // be used in default argument expressions, even if they are not 94 // evaluated. Parameters of a function declared before a default 95 // argument expression are in scope and can hide namespace and 96 // class member names. 97 return S->Diag(DRE->getBeginLoc(), 98 diag::err_param_default_argument_references_param) 99 << Param->getDeclName() << DefaultArg->getSourceRange(); 100 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 101 // C++ [dcl.fct.default]p7 102 // Local variables shall not be used in default argument 103 // expressions. 104 if (VDecl->isLocalVarDecl()) 105 return S->Diag(DRE->getBeginLoc(), 106 diag::err_param_default_argument_references_local) 107 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 108 } 109 110 return false; 111 } 112 113 /// VisitCXXThisExpr - Visit a C++ "this" expression. 114 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 115 // C++ [dcl.fct.default]p8: 116 // The keyword this shall not be used in a default argument of a 117 // member function. 118 return S->Diag(ThisE->getBeginLoc(), 119 diag::err_param_default_argument_references_this) 120 << ThisE->getSourceRange(); 121 } 122 123 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 124 bool Invalid = false; 125 for (PseudoObjectExpr::semantics_iterator 126 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 127 Expr *E = *i; 128 129 // Look through bindings. 130 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 131 E = OVE->getSourceExpr(); 132 assert(E && "pseudo-object binding without source expression?"); 133 } 134 135 Invalid |= Visit(E); 136 } 137 return Invalid; 138 } 139 140 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 141 // C++11 [expr.lambda.prim]p13: 142 // A lambda-expression appearing in a default argument shall not 143 // implicitly or explicitly capture any entity. 144 if (Lambda->capture_begin() == Lambda->capture_end()) 145 return false; 146 147 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 148 } 149 } 150 151 void 152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 153 const CXXMethodDecl *Method) { 154 // If we have an MSAny spec already, don't bother. 155 if (!Method || ComputedEST == EST_MSAny) 156 return; 157 158 const FunctionProtoType *Proto 159 = Method->getType()->getAs<FunctionProtoType>(); 160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 161 if (!Proto) 162 return; 163 164 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 165 166 // If we have a throw-all spec at this point, ignore the function. 167 if (ComputedEST == EST_None) 168 return; 169 170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 171 EST = EST_BasicNoexcept; 172 173 switch (EST) { 174 case EST_Unparsed: 175 case EST_Uninstantiated: 176 case EST_Unevaluated: 177 llvm_unreachable("should not see unresolved exception specs here"); 178 179 // If this function can throw any exceptions, make a note of that. 180 case EST_MSAny: 181 case EST_None: 182 // FIXME: Whichever we see last of MSAny and None determines our result. 183 // We should make a consistent, order-independent choice here. 184 ClearExceptions(); 185 ComputedEST = EST; 186 return; 187 case EST_NoexceptFalse: 188 ClearExceptions(); 189 ComputedEST = EST_None; 190 return; 191 // FIXME: If the call to this decl is using any of its default arguments, we 192 // need to search them for potentially-throwing calls. 193 // If this function has a basic noexcept, it doesn't affect the outcome. 194 case EST_BasicNoexcept: 195 case EST_NoexceptTrue: 196 case EST_NoThrow: 197 return; 198 // If we're still at noexcept(true) and there's a throw() callee, 199 // change to that specification. 200 case EST_DynamicNone: 201 if (ComputedEST == EST_BasicNoexcept) 202 ComputedEST = EST_DynamicNone; 203 return; 204 case EST_DependentNoexcept: 205 llvm_unreachable( 206 "should not generate implicit declarations for dependent cases"); 207 case EST_Dynamic: 208 break; 209 } 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 221 if (!S || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(S)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.getAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // C++11 [dcl.fct.default]p3 322 // A default argument expression [...] shall not be specified for a 323 // parameter pack. 324 if (Param->isParameterPack()) { 325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 326 << DefaultArg->getSourceRange(); 327 return; 328 } 329 330 // Check that the default argument is well-formed 331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 332 if (DefaultArgChecker.Visit(DefaultArg)) { 333 Param->setInvalidDecl(); 334 return; 335 } 336 337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 338 } 339 340 /// ActOnParamUnparsedDefaultArgument - We've seen a default 341 /// argument for a function parameter, but we can't parse it yet 342 /// because we're inside a class definition. Note that this default 343 /// argument will be parsed later. 344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 345 SourceLocation EqualLoc, 346 SourceLocation ArgLoc) { 347 if (!param) 348 return; 349 350 ParmVarDecl *Param = cast<ParmVarDecl>(param); 351 Param->setUnparsedDefaultArg(); 352 UnparsedDefaultArgLocs[Param] = ArgLoc; 353 } 354 355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 356 /// the default argument for the parameter param failed. 357 void Sema::ActOnParamDefaultArgumentError(Decl *param, 358 SourceLocation EqualLoc) { 359 if (!param) 360 return; 361 362 ParmVarDecl *Param = cast<ParmVarDecl>(param); 363 Param->setInvalidDecl(); 364 UnparsedDefaultArgLocs.erase(Param); 365 Param->setDefaultArg(new(Context) 366 OpaqueValueExpr(EqualLoc, 367 Param->getType().getNonReferenceType(), 368 VK_RValue)); 369 } 370 371 /// CheckExtraCXXDefaultArguments - Check for any extra default 372 /// arguments in the declarator, which is not a function declaration 373 /// or definition and therefore is not permitted to have default 374 /// arguments. This routine should be invoked for every declarator 375 /// that is not a function declaration or definition. 376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 377 // C++ [dcl.fct.default]p3 378 // A default argument expression shall be specified only in the 379 // parameter-declaration-clause of a function declaration or in a 380 // template-parameter (14.1). It shall not be specified for a 381 // parameter pack. If it is specified in a 382 // parameter-declaration-clause, it shall not occur within a 383 // declarator or abstract-declarator of a parameter-declaration. 384 bool MightBeFunction = D.isFunctionDeclarationContext(); 385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 386 DeclaratorChunk &chunk = D.getTypeObject(i); 387 if (chunk.Kind == DeclaratorChunk::Function) { 388 if (MightBeFunction) { 389 // This is a function declaration. It can have default arguments, but 390 // keep looking in case its return type is a function type with default 391 // arguments. 392 MightBeFunction = false; 393 continue; 394 } 395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 396 ++argIdx) { 397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 398 if (Param->hasUnparsedDefaultArg()) { 399 std::unique_ptr<CachedTokens> Toks = 400 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 401 SourceRange SR; 402 if (Toks->size() > 1) 403 SR = SourceRange((*Toks)[1].getLocation(), 404 Toks->back().getLocation()); 405 else 406 SR = UnparsedDefaultArgLocs[Param]; 407 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 408 << SR; 409 } else if (Param->getDefaultArg()) { 410 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 411 << Param->getDefaultArg()->getSourceRange(); 412 Param->setDefaultArg(nullptr); 413 } 414 } 415 } else if (chunk.Kind != DeclaratorChunk::Paren) { 416 MightBeFunction = false; 417 } 418 } 419 } 420 421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 422 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 423 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 424 if (!PVD->hasDefaultArg()) 425 return false; 426 if (!PVD->hasInheritedDefaultArg()) 427 return true; 428 } 429 return false; 430 } 431 432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 433 /// function, once we already know that they have the same 434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 435 /// error, false otherwise. 436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 437 Scope *S) { 438 bool Invalid = false; 439 440 // The declaration context corresponding to the scope is the semantic 441 // parent, unless this is a local function declaration, in which case 442 // it is that surrounding function. 443 DeclContext *ScopeDC = New->isLocalExternDecl() 444 ? New->getLexicalDeclContext() 445 : New->getDeclContext(); 446 447 // Find the previous declaration for the purpose of default arguments. 448 FunctionDecl *PrevForDefaultArgs = Old; 449 for (/**/; PrevForDefaultArgs; 450 // Don't bother looking back past the latest decl if this is a local 451 // extern declaration; nothing else could work. 452 PrevForDefaultArgs = New->isLocalExternDecl() 453 ? nullptr 454 : PrevForDefaultArgs->getPreviousDecl()) { 455 // Ignore hidden declarations. 456 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 457 continue; 458 459 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 460 !New->isCXXClassMember()) { 461 // Ignore default arguments of old decl if they are not in 462 // the same scope and this is not an out-of-line definition of 463 // a member function. 464 continue; 465 } 466 467 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 468 // If only one of these is a local function declaration, then they are 469 // declared in different scopes, even though isDeclInScope may think 470 // they're in the same scope. (If both are local, the scope check is 471 // sufficient, and if neither is local, then they are in the same scope.) 472 continue; 473 } 474 475 // We found the right previous declaration. 476 break; 477 } 478 479 // C++ [dcl.fct.default]p4: 480 // For non-template functions, default arguments can be added in 481 // later declarations of a function in the same 482 // scope. Declarations in different scopes have completely 483 // distinct sets of default arguments. That is, declarations in 484 // inner scopes do not acquire default arguments from 485 // declarations in outer scopes, and vice versa. In a given 486 // function declaration, all parameters subsequent to a 487 // parameter with a default argument shall have default 488 // arguments supplied in this or previous declarations. A 489 // default argument shall not be redefined by a later 490 // declaration (not even to the same value). 491 // 492 // C++ [dcl.fct.default]p6: 493 // Except for member functions of class templates, the default arguments 494 // in a member function definition that appears outside of the class 495 // definition are added to the set of default arguments provided by the 496 // member function declaration in the class definition. 497 for (unsigned p = 0, NumParams = PrevForDefaultArgs 498 ? PrevForDefaultArgs->getNumParams() 499 : 0; 500 p < NumParams; ++p) { 501 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 502 ParmVarDecl *NewParam = New->getParamDecl(p); 503 504 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 505 bool NewParamHasDfl = NewParam->hasDefaultArg(); 506 507 if (OldParamHasDfl && NewParamHasDfl) { 508 unsigned DiagDefaultParamID = 509 diag::err_param_default_argument_redefinition; 510 511 // MSVC accepts that default parameters be redefined for member functions 512 // of template class. The new default parameter's value is ignored. 513 Invalid = true; 514 if (getLangOpts().MicrosoftExt) { 515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 516 if (MD && MD->getParent()->getDescribedClassTemplate()) { 517 // Merge the old default argument into the new parameter. 518 NewParam->setHasInheritedDefaultArg(); 519 if (OldParam->hasUninstantiatedDefaultArg()) 520 NewParam->setUninstantiatedDefaultArg( 521 OldParam->getUninstantiatedDefaultArg()); 522 else 523 NewParam->setDefaultArg(OldParam->getInit()); 524 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 525 Invalid = false; 526 } 527 } 528 529 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 530 // hint here. Alternatively, we could walk the type-source information 531 // for NewParam to find the last source location in the type... but it 532 // isn't worth the effort right now. This is the kind of test case that 533 // is hard to get right: 534 // int f(int); 535 // void g(int (*fp)(int) = f); 536 // void g(int (*fp)(int) = &f); 537 Diag(NewParam->getLocation(), DiagDefaultParamID) 538 << NewParam->getDefaultArgRange(); 539 540 // Look for the function declaration where the default argument was 541 // actually written, which may be a declaration prior to Old. 542 for (auto Older = PrevForDefaultArgs; 543 OldParam->hasInheritedDefaultArg(); /**/) { 544 Older = Older->getPreviousDecl(); 545 OldParam = Older->getParamDecl(p); 546 } 547 548 Diag(OldParam->getLocation(), diag::note_previous_definition) 549 << OldParam->getDefaultArgRange(); 550 } else if (OldParamHasDfl) { 551 // Merge the old default argument into the new parameter unless the new 552 // function is a friend declaration in a template class. In the latter 553 // case the default arguments will be inherited when the friend 554 // declaration will be instantiated. 555 if (New->getFriendObjectKind() == Decl::FOK_None || 556 !New->getLexicalDeclContext()->isDependentContext()) { 557 // It's important to use getInit() here; getDefaultArg() 558 // strips off any top-level ExprWithCleanups. 559 NewParam->setHasInheritedDefaultArg(); 560 if (OldParam->hasUnparsedDefaultArg()) 561 NewParam->setUnparsedDefaultArg(); 562 else if (OldParam->hasUninstantiatedDefaultArg()) 563 NewParam->setUninstantiatedDefaultArg( 564 OldParam->getUninstantiatedDefaultArg()); 565 else 566 NewParam->setDefaultArg(OldParam->getInit()); 567 } 568 } else if (NewParamHasDfl) { 569 if (New->getDescribedFunctionTemplate()) { 570 // Paragraph 4, quoted above, only applies to non-template functions. 571 Diag(NewParam->getLocation(), 572 diag::err_param_default_argument_template_redecl) 573 << NewParam->getDefaultArgRange(); 574 Diag(PrevForDefaultArgs->getLocation(), 575 diag::note_template_prev_declaration) 576 << false; 577 } else if (New->getTemplateSpecializationKind() 578 != TSK_ImplicitInstantiation && 579 New->getTemplateSpecializationKind() != TSK_Undeclared) { 580 // C++ [temp.expr.spec]p21: 581 // Default function arguments shall not be specified in a declaration 582 // or a definition for one of the following explicit specializations: 583 // - the explicit specialization of a function template; 584 // - the explicit specialization of a member function template; 585 // - the explicit specialization of a member function of a class 586 // template where the class template specialization to which the 587 // member function specialization belongs is implicitly 588 // instantiated. 589 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 590 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 591 << New->getDeclName() 592 << NewParam->getDefaultArgRange(); 593 } else if (New->getDeclContext()->isDependentContext()) { 594 // C++ [dcl.fct.default]p6 (DR217): 595 // Default arguments for a member function of a class template shall 596 // be specified on the initial declaration of the member function 597 // within the class template. 598 // 599 // Reading the tea leaves a bit in DR217 and its reference to DR205 600 // leads me to the conclusion that one cannot add default function 601 // arguments for an out-of-line definition of a member function of a 602 // dependent type. 603 int WhichKind = 2; 604 if (CXXRecordDecl *Record 605 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 606 if (Record->getDescribedClassTemplate()) 607 WhichKind = 0; 608 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 609 WhichKind = 1; 610 else 611 WhichKind = 2; 612 } 613 614 Diag(NewParam->getLocation(), 615 diag::err_param_default_argument_member_template_redecl) 616 << WhichKind 617 << NewParam->getDefaultArgRange(); 618 } 619 } 620 } 621 622 // DR1344: If a default argument is added outside a class definition and that 623 // default argument makes the function a special member function, the program 624 // is ill-formed. This can only happen for constructors. 625 if (isa<CXXConstructorDecl>(New) && 626 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 627 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 628 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 629 if (NewSM != OldSM) { 630 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 631 assert(NewParam->hasDefaultArg()); 632 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 633 << NewParam->getDefaultArgRange() << NewSM; 634 Diag(Old->getLocation(), diag::note_previous_declaration); 635 } 636 } 637 638 const FunctionDecl *Def; 639 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 640 // template has a constexpr specifier then all its declarations shall 641 // contain the constexpr specifier. 642 if (New->getConstexprKind() != Old->getConstexprKind()) { 643 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 644 << New << New->getConstexprKind() << Old->getConstexprKind(); 645 Diag(Old->getLocation(), diag::note_previous_declaration); 646 Invalid = true; 647 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 648 Old->isDefined(Def) && 649 // If a friend function is inlined but does not have 'inline' 650 // specifier, it is a definition. Do not report attribute conflict 651 // in this case, redefinition will be diagnosed later. 652 (New->isInlineSpecified() || 653 New->getFriendObjectKind() == Decl::FOK_None)) { 654 // C++11 [dcl.fcn.spec]p4: 655 // If the definition of a function appears in a translation unit before its 656 // first declaration as inline, the program is ill-formed. 657 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 658 Diag(Def->getLocation(), diag::note_previous_definition); 659 Invalid = true; 660 } 661 662 // C++17 [temp.deduct.guide]p3: 663 // Two deduction guide declarations in the same translation unit 664 // for the same class template shall not have equivalent 665 // parameter-declaration-clauses. 666 if (isa<CXXDeductionGuideDecl>(New) && 667 !New->isFunctionTemplateSpecialization()) { 668 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 669 Diag(Old->getLocation(), diag::note_previous_declaration); 670 } 671 672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 673 // argument expression, that declaration shall be a definition and shall be 674 // the only declaration of the function or function template in the 675 // translation unit. 676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 677 functionDeclHasDefaultArgument(Old)) { 678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 679 Diag(Old->getLocation(), diag::note_previous_declaration); 680 Invalid = true; 681 } 682 683 return Invalid; 684 } 685 686 NamedDecl * 687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 688 MultiTemplateParamsArg TemplateParamLists) { 689 assert(D.isDecompositionDeclarator()); 690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 691 692 // The syntax only allows a decomposition declarator as a simple-declaration, 693 // a for-range-declaration, or a condition in Clang, but we parse it in more 694 // cases than that. 695 if (!D.mayHaveDecompositionDeclarator()) { 696 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 697 << Decomp.getSourceRange(); 698 return nullptr; 699 } 700 701 if (!TemplateParamLists.empty()) { 702 // FIXME: There's no rule against this, but there are also no rules that 703 // would actually make it usable, so we reject it for now. 704 Diag(TemplateParamLists.front()->getTemplateLoc(), 705 diag::err_decomp_decl_template); 706 return nullptr; 707 } 708 709 Diag(Decomp.getLSquareLoc(), 710 !getLangOpts().CPlusPlus17 711 ? diag::ext_decomp_decl 712 : D.getContext() == DeclaratorContext::ConditionContext 713 ? diag::ext_decomp_decl_cond 714 : diag::warn_cxx14_compat_decomp_decl) 715 << Decomp.getSourceRange(); 716 717 // The semantic context is always just the current context. 718 DeclContext *const DC = CurContext; 719 720 // C++17 [dcl.dcl]/8: 721 // The decl-specifier-seq shall contain only the type-specifier auto 722 // and cv-qualifiers. 723 // C++2a [dcl.dcl]/8: 724 // If decl-specifier-seq contains any decl-specifier other than static, 725 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 726 auto &DS = D.getDeclSpec(); 727 { 728 SmallVector<StringRef, 8> BadSpecifiers; 729 SmallVector<SourceLocation, 8> BadSpecifierLocs; 730 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 731 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 732 if (auto SCS = DS.getStorageClassSpec()) { 733 if (SCS == DeclSpec::SCS_static) { 734 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 735 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 736 } else { 737 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 738 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 739 } 740 } 741 if (auto TSCS = DS.getThreadStorageClassSpec()) { 742 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 743 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 744 } 745 if (DS.hasConstexprSpecifier()) { 746 BadSpecifiers.push_back( 747 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 748 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 749 } 750 if (DS.isInlineSpecified()) { 751 BadSpecifiers.push_back("inline"); 752 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 753 } 754 if (!BadSpecifiers.empty()) { 755 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 756 Err << (int)BadSpecifiers.size() 757 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 758 // Don't add FixItHints to remove the specifiers; we do still respect 759 // them when building the underlying variable. 760 for (auto Loc : BadSpecifierLocs) 761 Err << SourceRange(Loc, Loc); 762 } else if (!CPlusPlus20Specifiers.empty()) { 763 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 764 getLangOpts().CPlusPlus2a 765 ? diag::warn_cxx17_compat_decomp_decl_spec 766 : diag::ext_decomp_decl_spec); 767 Warn << (int)CPlusPlus20Specifiers.size() 768 << llvm::join(CPlusPlus20Specifiers.begin(), 769 CPlusPlus20Specifiers.end(), " "); 770 for (auto Loc : CPlusPlus20SpecifierLocs) 771 Warn << SourceRange(Loc, Loc); 772 } 773 // We can't recover from it being declared as a typedef. 774 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 775 return nullptr; 776 } 777 778 // C++2a [dcl.struct.bind]p1: 779 // A cv that includes volatile is deprecated 780 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 781 getLangOpts().CPlusPlus2a) 782 Diag(DS.getVolatileSpecLoc(), 783 diag::warn_deprecated_volatile_structured_binding); 784 785 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 786 QualType R = TInfo->getType(); 787 788 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 789 UPPC_DeclarationType)) 790 D.setInvalidType(); 791 792 // The syntax only allows a single ref-qualifier prior to the decomposition 793 // declarator. No other declarator chunks are permitted. Also check the type 794 // specifier here. 795 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 796 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 797 (D.getNumTypeObjects() == 1 && 798 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 799 Diag(Decomp.getLSquareLoc(), 800 (D.hasGroupingParens() || 801 (D.getNumTypeObjects() && 802 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 803 ? diag::err_decomp_decl_parens 804 : diag::err_decomp_decl_type) 805 << R; 806 807 // In most cases, there's no actual problem with an explicitly-specified 808 // type, but a function type won't work here, and ActOnVariableDeclarator 809 // shouldn't be called for such a type. 810 if (R->isFunctionType()) 811 D.setInvalidType(); 812 } 813 814 // Build the BindingDecls. 815 SmallVector<BindingDecl*, 8> Bindings; 816 817 // Build the BindingDecls. 818 for (auto &B : D.getDecompositionDeclarator().bindings()) { 819 // Check for name conflicts. 820 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 821 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 822 ForVisibleRedeclaration); 823 LookupName(Previous, S, 824 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 825 826 // It's not permitted to shadow a template parameter name. 827 if (Previous.isSingleResult() && 828 Previous.getFoundDecl()->isTemplateParameter()) { 829 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 830 Previous.getFoundDecl()); 831 Previous.clear(); 832 } 833 834 bool ConsiderLinkage = DC->isFunctionOrMethod() && 835 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 836 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 837 /*AllowInlineNamespace*/false); 838 if (!Previous.empty()) { 839 auto *Old = Previous.getRepresentativeDecl(); 840 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 841 Diag(Old->getLocation(), diag::note_previous_definition); 842 } 843 844 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 845 PushOnScopeChains(BD, S, true); 846 Bindings.push_back(BD); 847 ParsingInitForAutoVars.insert(BD); 848 } 849 850 // There are no prior lookup results for the variable itself, because it 851 // is unnamed. 852 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 853 Decomp.getLSquareLoc()); 854 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 855 ForVisibleRedeclaration); 856 857 // Build the variable that holds the non-decomposed object. 858 bool AddToScope = true; 859 NamedDecl *New = 860 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 861 MultiTemplateParamsArg(), AddToScope, Bindings); 862 if (AddToScope) { 863 S->AddDecl(New); 864 CurContext->addHiddenDecl(New); 865 } 866 867 if (isInOpenMPDeclareTargetContext()) 868 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 869 870 return New; 871 } 872 873 static bool checkSimpleDecomposition( 874 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 875 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 876 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 877 if ((int64_t)Bindings.size() != NumElems) { 878 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 879 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 880 << (NumElems < Bindings.size()); 881 return true; 882 } 883 884 unsigned I = 0; 885 for (auto *B : Bindings) { 886 SourceLocation Loc = B->getLocation(); 887 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 888 if (E.isInvalid()) 889 return true; 890 E = GetInit(Loc, E.get(), I++); 891 if (E.isInvalid()) 892 return true; 893 B->setBinding(ElemType, E.get()); 894 } 895 896 return false; 897 } 898 899 static bool checkArrayLikeDecomposition(Sema &S, 900 ArrayRef<BindingDecl *> Bindings, 901 ValueDecl *Src, QualType DecompType, 902 const llvm::APSInt &NumElems, 903 QualType ElemType) { 904 return checkSimpleDecomposition( 905 S, Bindings, Src, DecompType, NumElems, ElemType, 906 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 907 ExprResult E = S.ActOnIntegerConstant(Loc, I); 908 if (E.isInvalid()) 909 return ExprError(); 910 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 911 }); 912 } 913 914 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 915 ValueDecl *Src, QualType DecompType, 916 const ConstantArrayType *CAT) { 917 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 918 llvm::APSInt(CAT->getSize()), 919 CAT->getElementType()); 920 } 921 922 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 923 ValueDecl *Src, QualType DecompType, 924 const VectorType *VT) { 925 return checkArrayLikeDecomposition( 926 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 927 S.Context.getQualifiedType(VT->getElementType(), 928 DecompType.getQualifiers())); 929 } 930 931 static bool checkComplexDecomposition(Sema &S, 932 ArrayRef<BindingDecl *> Bindings, 933 ValueDecl *Src, QualType DecompType, 934 const ComplexType *CT) { 935 return checkSimpleDecomposition( 936 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 937 S.Context.getQualifiedType(CT->getElementType(), 938 DecompType.getQualifiers()), 939 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 940 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 941 }); 942 } 943 944 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 945 TemplateArgumentListInfo &Args) { 946 SmallString<128> SS; 947 llvm::raw_svector_ostream OS(SS); 948 bool First = true; 949 for (auto &Arg : Args.arguments()) { 950 if (!First) 951 OS << ", "; 952 Arg.getArgument().print(PrintingPolicy, OS); 953 First = false; 954 } 955 return std::string(OS.str()); 956 } 957 958 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 959 SourceLocation Loc, StringRef Trait, 960 TemplateArgumentListInfo &Args, 961 unsigned DiagID) { 962 auto DiagnoseMissing = [&] { 963 if (DiagID) 964 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 965 Args); 966 return true; 967 }; 968 969 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 970 NamespaceDecl *Std = S.getStdNamespace(); 971 if (!Std) 972 return DiagnoseMissing(); 973 974 // Look up the trait itself, within namespace std. We can diagnose various 975 // problems with this lookup even if we've been asked to not diagnose a 976 // missing specialization, because this can only fail if the user has been 977 // declaring their own names in namespace std or we don't support the 978 // standard library implementation in use. 979 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 980 Loc, Sema::LookupOrdinaryName); 981 if (!S.LookupQualifiedName(Result, Std)) 982 return DiagnoseMissing(); 983 if (Result.isAmbiguous()) 984 return true; 985 986 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 987 if (!TraitTD) { 988 Result.suppressDiagnostics(); 989 NamedDecl *Found = *Result.begin(); 990 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 991 S.Diag(Found->getLocation(), diag::note_declared_at); 992 return true; 993 } 994 995 // Build the template-id. 996 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 997 if (TraitTy.isNull()) 998 return true; 999 if (!S.isCompleteType(Loc, TraitTy)) { 1000 if (DiagID) 1001 S.RequireCompleteType( 1002 Loc, TraitTy, DiagID, 1003 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1004 return true; 1005 } 1006 1007 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1008 assert(RD && "specialization of class template is not a class?"); 1009 1010 // Look up the member of the trait type. 1011 S.LookupQualifiedName(TraitMemberLookup, RD); 1012 return TraitMemberLookup.isAmbiguous(); 1013 } 1014 1015 static TemplateArgumentLoc 1016 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1017 uint64_t I) { 1018 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1019 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1020 } 1021 1022 static TemplateArgumentLoc 1023 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1024 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1025 } 1026 1027 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1028 1029 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1030 llvm::APSInt &Size) { 1031 EnterExpressionEvaluationContext ContextRAII( 1032 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1033 1034 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1035 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1036 1037 // Form template argument list for tuple_size<T>. 1038 TemplateArgumentListInfo Args(Loc, Loc); 1039 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1040 1041 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1042 // it's not tuple-like. 1043 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1044 R.empty()) 1045 return IsTupleLike::NotTupleLike; 1046 1047 // If we get this far, we've committed to the tuple interpretation, but 1048 // we can still fail if there actually isn't a usable ::value. 1049 1050 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1051 LookupResult &R; 1052 TemplateArgumentListInfo &Args; 1053 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1054 : R(R), Args(Args) {} 1055 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1056 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1057 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1058 } 1059 } Diagnoser(R, Args); 1060 1061 ExprResult E = 1062 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1063 if (E.isInvalid()) 1064 return IsTupleLike::Error; 1065 1066 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1067 if (E.isInvalid()) 1068 return IsTupleLike::Error; 1069 1070 return IsTupleLike::TupleLike; 1071 } 1072 1073 /// \return std::tuple_element<I, T>::type. 1074 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1075 unsigned I, QualType T) { 1076 // Form template argument list for tuple_element<I, T>. 1077 TemplateArgumentListInfo Args(Loc, Loc); 1078 Args.addArgument( 1079 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1080 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1081 1082 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1083 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1084 if (lookupStdTypeTraitMember( 1085 S, R, Loc, "tuple_element", Args, 1086 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1087 return QualType(); 1088 1089 auto *TD = R.getAsSingle<TypeDecl>(); 1090 if (!TD) { 1091 R.suppressDiagnostics(); 1092 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1093 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1094 if (!R.empty()) 1095 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1096 return QualType(); 1097 } 1098 1099 return S.Context.getTypeDeclType(TD); 1100 } 1101 1102 namespace { 1103 struct BindingDiagnosticTrap { 1104 Sema &S; 1105 DiagnosticErrorTrap Trap; 1106 BindingDecl *BD; 1107 1108 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1109 : S(S), Trap(S.Diags), BD(BD) {} 1110 ~BindingDiagnosticTrap() { 1111 if (Trap.hasErrorOccurred()) 1112 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1113 } 1114 }; 1115 } 1116 1117 static bool checkTupleLikeDecomposition(Sema &S, 1118 ArrayRef<BindingDecl *> Bindings, 1119 VarDecl *Src, QualType DecompType, 1120 const llvm::APSInt &TupleSize) { 1121 if ((int64_t)Bindings.size() != TupleSize) { 1122 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1123 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1124 << (TupleSize < Bindings.size()); 1125 return true; 1126 } 1127 1128 if (Bindings.empty()) 1129 return false; 1130 1131 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1132 1133 // [dcl.decomp]p3: 1134 // The unqualified-id get is looked up in the scope of E by class member 1135 // access lookup ... 1136 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1137 bool UseMemberGet = false; 1138 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1139 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1140 S.LookupQualifiedName(MemberGet, RD); 1141 if (MemberGet.isAmbiguous()) 1142 return true; 1143 // ... and if that finds at least one declaration that is a function 1144 // template whose first template parameter is a non-type parameter ... 1145 for (NamedDecl *D : MemberGet) { 1146 if (FunctionTemplateDecl *FTD = 1147 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1148 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1149 if (TPL->size() != 0 && 1150 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1151 // ... the initializer is e.get<i>(). 1152 UseMemberGet = true; 1153 break; 1154 } 1155 } 1156 } 1157 } 1158 1159 unsigned I = 0; 1160 for (auto *B : Bindings) { 1161 BindingDiagnosticTrap Trap(S, B); 1162 SourceLocation Loc = B->getLocation(); 1163 1164 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1165 if (E.isInvalid()) 1166 return true; 1167 1168 // e is an lvalue if the type of the entity is an lvalue reference and 1169 // an xvalue otherwise 1170 if (!Src->getType()->isLValueReferenceType()) 1171 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1172 E.get(), nullptr, VK_XValue); 1173 1174 TemplateArgumentListInfo Args(Loc, Loc); 1175 Args.addArgument( 1176 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1177 1178 if (UseMemberGet) { 1179 // if [lookup of member get] finds at least one declaration, the 1180 // initializer is e.get<i-1>(). 1181 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1182 CXXScopeSpec(), SourceLocation(), nullptr, 1183 MemberGet, &Args, nullptr); 1184 if (E.isInvalid()) 1185 return true; 1186 1187 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1188 } else { 1189 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1190 // in the associated namespaces. 1191 Expr *Get = UnresolvedLookupExpr::Create( 1192 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1193 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1194 UnresolvedSetIterator(), UnresolvedSetIterator()); 1195 1196 Expr *Arg = E.get(); 1197 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1198 } 1199 if (E.isInvalid()) 1200 return true; 1201 Expr *Init = E.get(); 1202 1203 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1204 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1205 if (T.isNull()) 1206 return true; 1207 1208 // each vi is a variable of type "reference to T" initialized with the 1209 // initializer, where the reference is an lvalue reference if the 1210 // initializer is an lvalue and an rvalue reference otherwise 1211 QualType RefType = 1212 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1213 if (RefType.isNull()) 1214 return true; 1215 auto *RefVD = VarDecl::Create( 1216 S.Context, Src->getDeclContext(), Loc, Loc, 1217 B->getDeclName().getAsIdentifierInfo(), RefType, 1218 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1219 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1220 RefVD->setTSCSpec(Src->getTSCSpec()); 1221 RefVD->setImplicit(); 1222 if (Src->isInlineSpecified()) 1223 RefVD->setInlineSpecified(); 1224 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1225 1226 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1227 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1228 InitializationSequence Seq(S, Entity, Kind, Init); 1229 E = Seq.Perform(S, Entity, Kind, Init); 1230 if (E.isInvalid()) 1231 return true; 1232 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1233 if (E.isInvalid()) 1234 return true; 1235 RefVD->setInit(E.get()); 1236 if (!E.get()->isValueDependent()) 1237 RefVD->checkInitIsICE(); 1238 1239 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1240 DeclarationNameInfo(B->getDeclName(), Loc), 1241 RefVD); 1242 if (E.isInvalid()) 1243 return true; 1244 1245 B->setBinding(T, E.get()); 1246 I++; 1247 } 1248 1249 return false; 1250 } 1251 1252 /// Find the base class to decompose in a built-in decomposition of a class type. 1253 /// This base class search is, unfortunately, not quite like any other that we 1254 /// perform anywhere else in C++. 1255 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1256 const CXXRecordDecl *RD, 1257 CXXCastPath &BasePath) { 1258 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1259 CXXBasePath &Path) { 1260 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1261 }; 1262 1263 const CXXRecordDecl *ClassWithFields = nullptr; 1264 AccessSpecifier AS = AS_public; 1265 if (RD->hasDirectFields()) 1266 // [dcl.decomp]p4: 1267 // Otherwise, all of E's non-static data members shall be public direct 1268 // members of E ... 1269 ClassWithFields = RD; 1270 else { 1271 // ... or of ... 1272 CXXBasePaths Paths; 1273 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1274 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1275 // If no classes have fields, just decompose RD itself. (This will work 1276 // if and only if zero bindings were provided.) 1277 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1278 } 1279 1280 CXXBasePath *BestPath = nullptr; 1281 for (auto &P : Paths) { 1282 if (!BestPath) 1283 BestPath = &P; 1284 else if (!S.Context.hasSameType(P.back().Base->getType(), 1285 BestPath->back().Base->getType())) { 1286 // ... the same ... 1287 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1288 << false << RD << BestPath->back().Base->getType() 1289 << P.back().Base->getType(); 1290 return DeclAccessPair(); 1291 } else if (P.Access < BestPath->Access) { 1292 BestPath = &P; 1293 } 1294 } 1295 1296 // ... unambiguous ... 1297 QualType BaseType = BestPath->back().Base->getType(); 1298 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1299 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1300 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1301 return DeclAccessPair(); 1302 } 1303 1304 // ... [accessible, implied by other rules] base class of E. 1305 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1306 *BestPath, diag::err_decomp_decl_inaccessible_base); 1307 AS = BestPath->Access; 1308 1309 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1310 S.BuildBasePathArray(Paths, BasePath); 1311 } 1312 1313 // The above search did not check whether the selected class itself has base 1314 // classes with fields, so check that now. 1315 CXXBasePaths Paths; 1316 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1317 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1318 << (ClassWithFields == RD) << RD << ClassWithFields 1319 << Paths.front().back().Base->getType(); 1320 return DeclAccessPair(); 1321 } 1322 1323 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1324 } 1325 1326 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1327 ValueDecl *Src, QualType DecompType, 1328 const CXXRecordDecl *OrigRD) { 1329 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1330 diag::err_incomplete_type)) 1331 return true; 1332 1333 CXXCastPath BasePath; 1334 DeclAccessPair BasePair = 1335 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1336 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1337 if (!RD) 1338 return true; 1339 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1340 DecompType.getQualifiers()); 1341 1342 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1343 unsigned NumFields = 1344 std::count_if(RD->field_begin(), RD->field_end(), 1345 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1346 assert(Bindings.size() != NumFields); 1347 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1348 << DecompType << (unsigned)Bindings.size() << NumFields 1349 << (NumFields < Bindings.size()); 1350 return true; 1351 }; 1352 1353 // all of E's non-static data members shall be [...] well-formed 1354 // when named as e.name in the context of the structured binding, 1355 // E shall not have an anonymous union member, ... 1356 unsigned I = 0; 1357 for (auto *FD : RD->fields()) { 1358 if (FD->isUnnamedBitfield()) 1359 continue; 1360 1361 if (FD->isAnonymousStructOrUnion()) { 1362 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1363 << DecompType << FD->getType()->isUnionType(); 1364 S.Diag(FD->getLocation(), diag::note_declared_at); 1365 return true; 1366 } 1367 1368 // We have a real field to bind. 1369 if (I >= Bindings.size()) 1370 return DiagnoseBadNumberOfBindings(); 1371 auto *B = Bindings[I++]; 1372 SourceLocation Loc = B->getLocation(); 1373 1374 // The field must be accessible in the context of the structured binding. 1375 // We already checked that the base class is accessible. 1376 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1377 // const_cast here. 1378 S.CheckStructuredBindingMemberAccess( 1379 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1380 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1381 BasePair.getAccess(), FD->getAccess()))); 1382 1383 // Initialize the binding to Src.FD. 1384 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1385 if (E.isInvalid()) 1386 return true; 1387 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1388 VK_LValue, &BasePath); 1389 if (E.isInvalid()) 1390 return true; 1391 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1392 CXXScopeSpec(), FD, 1393 DeclAccessPair::make(FD, FD->getAccess()), 1394 DeclarationNameInfo(FD->getDeclName(), Loc)); 1395 if (E.isInvalid()) 1396 return true; 1397 1398 // If the type of the member is T, the referenced type is cv T, where cv is 1399 // the cv-qualification of the decomposition expression. 1400 // 1401 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1402 // 'const' to the type of the field. 1403 Qualifiers Q = DecompType.getQualifiers(); 1404 if (FD->isMutable()) 1405 Q.removeConst(); 1406 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1407 } 1408 1409 if (I != Bindings.size()) 1410 return DiagnoseBadNumberOfBindings(); 1411 1412 return false; 1413 } 1414 1415 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1416 QualType DecompType = DD->getType(); 1417 1418 // If the type of the decomposition is dependent, then so is the type of 1419 // each binding. 1420 if (DecompType->isDependentType()) { 1421 for (auto *B : DD->bindings()) 1422 B->setType(Context.DependentTy); 1423 return; 1424 } 1425 1426 DecompType = DecompType.getNonReferenceType(); 1427 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1428 1429 // C++1z [dcl.decomp]/2: 1430 // If E is an array type [...] 1431 // As an extension, we also support decomposition of built-in complex and 1432 // vector types. 1433 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1434 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1435 DD->setInvalidDecl(); 1436 return; 1437 } 1438 if (auto *VT = DecompType->getAs<VectorType>()) { 1439 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1440 DD->setInvalidDecl(); 1441 return; 1442 } 1443 if (auto *CT = DecompType->getAs<ComplexType>()) { 1444 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1445 DD->setInvalidDecl(); 1446 return; 1447 } 1448 1449 // C++1z [dcl.decomp]/3: 1450 // if the expression std::tuple_size<E>::value is a well-formed integral 1451 // constant expression, [...] 1452 llvm::APSInt TupleSize(32); 1453 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1454 case IsTupleLike::Error: 1455 DD->setInvalidDecl(); 1456 return; 1457 1458 case IsTupleLike::TupleLike: 1459 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1460 DD->setInvalidDecl(); 1461 return; 1462 1463 case IsTupleLike::NotTupleLike: 1464 break; 1465 } 1466 1467 // C++1z [dcl.dcl]/8: 1468 // [E shall be of array or non-union class type] 1469 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1470 if (!RD || RD->isUnion()) { 1471 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1472 << DD << !RD << DecompType; 1473 DD->setInvalidDecl(); 1474 return; 1475 } 1476 1477 // C++1z [dcl.decomp]/4: 1478 // all of E's non-static data members shall be [...] direct members of 1479 // E or of the same unambiguous public base class of E, ... 1480 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1481 DD->setInvalidDecl(); 1482 } 1483 1484 /// Merge the exception specifications of two variable declarations. 1485 /// 1486 /// This is called when there's a redeclaration of a VarDecl. The function 1487 /// checks if the redeclaration might have an exception specification and 1488 /// validates compatibility and merges the specs if necessary. 1489 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1490 // Shortcut if exceptions are disabled. 1491 if (!getLangOpts().CXXExceptions) 1492 return; 1493 1494 assert(Context.hasSameType(New->getType(), Old->getType()) && 1495 "Should only be called if types are otherwise the same."); 1496 1497 QualType NewType = New->getType(); 1498 QualType OldType = Old->getType(); 1499 1500 // We're only interested in pointers and references to functions, as well 1501 // as pointers to member functions. 1502 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1503 NewType = R->getPointeeType(); 1504 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1505 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1506 NewType = P->getPointeeType(); 1507 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1508 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1509 NewType = M->getPointeeType(); 1510 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1511 } 1512 1513 if (!NewType->isFunctionProtoType()) 1514 return; 1515 1516 // There's lots of special cases for functions. For function pointers, system 1517 // libraries are hopefully not as broken so that we don't need these 1518 // workarounds. 1519 if (CheckEquivalentExceptionSpec( 1520 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1521 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1522 New->setInvalidDecl(); 1523 } 1524 } 1525 1526 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1527 /// function declaration are well-formed according to C++ 1528 /// [dcl.fct.default]. 1529 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1530 unsigned NumParams = FD->getNumParams(); 1531 unsigned p; 1532 1533 // Find first parameter with a default argument 1534 for (p = 0; p < NumParams; ++p) { 1535 ParmVarDecl *Param = FD->getParamDecl(p); 1536 if (Param->hasDefaultArg()) 1537 break; 1538 } 1539 1540 // C++11 [dcl.fct.default]p4: 1541 // In a given function declaration, each parameter subsequent to a parameter 1542 // with a default argument shall have a default argument supplied in this or 1543 // a previous declaration or shall be a function parameter pack. A default 1544 // argument shall not be redefined by a later declaration (not even to the 1545 // same value). 1546 unsigned LastMissingDefaultArg = 0; 1547 for (; p < NumParams; ++p) { 1548 ParmVarDecl *Param = FD->getParamDecl(p); 1549 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1550 if (Param->isInvalidDecl()) 1551 /* We already complained about this parameter. */; 1552 else if (Param->getIdentifier()) 1553 Diag(Param->getLocation(), 1554 diag::err_param_default_argument_missing_name) 1555 << Param->getIdentifier(); 1556 else 1557 Diag(Param->getLocation(), 1558 diag::err_param_default_argument_missing); 1559 1560 LastMissingDefaultArg = p; 1561 } 1562 } 1563 1564 if (LastMissingDefaultArg > 0) { 1565 // Some default arguments were missing. Clear out all of the 1566 // default arguments up to (and including) the last missing 1567 // default argument, so that we leave the function parameters 1568 // in a semantically valid state. 1569 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1570 ParmVarDecl *Param = FD->getParamDecl(p); 1571 if (Param->hasDefaultArg()) { 1572 Param->setDefaultArg(nullptr); 1573 } 1574 } 1575 } 1576 } 1577 1578 /// Check that the given type is a literal type. Issue a diagnostic if not, 1579 /// if Kind is Diagnose. 1580 /// \return \c true if a problem has been found (and optionally diagnosed). 1581 template <typename... Ts> 1582 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1583 SourceLocation Loc, QualType T, unsigned DiagID, 1584 Ts &&...DiagArgs) { 1585 if (T->isDependentType()) 1586 return false; 1587 1588 switch (Kind) { 1589 case Sema::CheckConstexprKind::Diagnose: 1590 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1591 std::forward<Ts>(DiagArgs)...); 1592 1593 case Sema::CheckConstexprKind::CheckValid: 1594 return !T->isLiteralType(SemaRef.Context); 1595 } 1596 1597 llvm_unreachable("unknown CheckConstexprKind"); 1598 } 1599 1600 /// Determine whether a destructor cannot be constexpr due to 1601 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1602 const CXXDestructorDecl *DD, 1603 Sema::CheckConstexprKind Kind) { 1604 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1605 const CXXRecordDecl *RD = 1606 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1607 if (!RD || RD->hasConstexprDestructor()) 1608 return true; 1609 1610 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1611 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1612 << DD->getConstexprKind() << !FD 1613 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1614 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1615 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1616 } 1617 return false; 1618 }; 1619 1620 const CXXRecordDecl *RD = DD->getParent(); 1621 for (const CXXBaseSpecifier &B : RD->bases()) 1622 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1623 return false; 1624 for (const FieldDecl *FD : RD->fields()) 1625 if (!Check(FD->getLocation(), FD->getType(), FD)) 1626 return false; 1627 return true; 1628 } 1629 1630 /// Check whether a function's parameter types are all literal types. If so, 1631 /// return true. If not, produce a suitable diagnostic and return false. 1632 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1633 const FunctionDecl *FD, 1634 Sema::CheckConstexprKind Kind) { 1635 unsigned ArgIndex = 0; 1636 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1637 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1638 e = FT->param_type_end(); 1639 i != e; ++i, ++ArgIndex) { 1640 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1641 SourceLocation ParamLoc = PD->getLocation(); 1642 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1643 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1644 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1645 FD->isConsteval())) 1646 return false; 1647 } 1648 return true; 1649 } 1650 1651 /// Check whether a function's return type is a literal type. If so, return 1652 /// true. If not, produce a suitable diagnostic and return false. 1653 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1654 Sema::CheckConstexprKind Kind) { 1655 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1656 diag::err_constexpr_non_literal_return, 1657 FD->isConsteval())) 1658 return false; 1659 return true; 1660 } 1661 1662 /// Get diagnostic %select index for tag kind for 1663 /// record diagnostic message. 1664 /// WARNING: Indexes apply to particular diagnostics only! 1665 /// 1666 /// \returns diagnostic %select index. 1667 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1668 switch (Tag) { 1669 case TTK_Struct: return 0; 1670 case TTK_Interface: return 1; 1671 case TTK_Class: return 2; 1672 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1673 } 1674 } 1675 1676 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1677 Stmt *Body, 1678 Sema::CheckConstexprKind Kind); 1679 1680 // Check whether a function declaration satisfies the requirements of a 1681 // constexpr function definition or a constexpr constructor definition. If so, 1682 // return true. If not, produce appropriate diagnostics (unless asked not to by 1683 // Kind) and return false. 1684 // 1685 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1686 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1687 CheckConstexprKind Kind) { 1688 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1689 if (MD && MD->isInstance()) { 1690 // C++11 [dcl.constexpr]p4: 1691 // The definition of a constexpr constructor shall satisfy the following 1692 // constraints: 1693 // - the class shall not have any virtual base classes; 1694 // 1695 // FIXME: This only applies to constructors and destructors, not arbitrary 1696 // member functions. 1697 const CXXRecordDecl *RD = MD->getParent(); 1698 if (RD->getNumVBases()) { 1699 if (Kind == CheckConstexprKind::CheckValid) 1700 return false; 1701 1702 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1703 << isa<CXXConstructorDecl>(NewFD) 1704 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1705 for (const auto &I : RD->vbases()) 1706 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1707 << I.getSourceRange(); 1708 return false; 1709 } 1710 } 1711 1712 if (!isa<CXXConstructorDecl>(NewFD)) { 1713 // C++11 [dcl.constexpr]p3: 1714 // The definition of a constexpr function shall satisfy the following 1715 // constraints: 1716 // - it shall not be virtual; (removed in C++20) 1717 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1718 if (Method && Method->isVirtual()) { 1719 if (getLangOpts().CPlusPlus2a) { 1720 if (Kind == CheckConstexprKind::Diagnose) 1721 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1722 } else { 1723 if (Kind == CheckConstexprKind::CheckValid) 1724 return false; 1725 1726 Method = Method->getCanonicalDecl(); 1727 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1728 1729 // If it's not obvious why this function is virtual, find an overridden 1730 // function which uses the 'virtual' keyword. 1731 const CXXMethodDecl *WrittenVirtual = Method; 1732 while (!WrittenVirtual->isVirtualAsWritten()) 1733 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1734 if (WrittenVirtual != Method) 1735 Diag(WrittenVirtual->getLocation(), 1736 diag::note_overridden_virtual_function); 1737 return false; 1738 } 1739 } 1740 1741 // - its return type shall be a literal type; 1742 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1743 return false; 1744 } 1745 1746 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1747 // A destructor can be constexpr only if the defaulted destructor could be; 1748 // we don't need to check the members and bases if we already know they all 1749 // have constexpr destructors. 1750 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1751 if (Kind == CheckConstexprKind::CheckValid) 1752 return false; 1753 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1754 return false; 1755 } 1756 } 1757 1758 // - each of its parameter types shall be a literal type; 1759 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1760 return false; 1761 1762 Stmt *Body = NewFD->getBody(); 1763 assert(Body && 1764 "CheckConstexprFunctionDefinition called on function with no body"); 1765 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1766 } 1767 1768 /// Check the given declaration statement is legal within a constexpr function 1769 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1770 /// 1771 /// \return true if the body is OK (maybe only as an extension), false if we 1772 /// have diagnosed a problem. 1773 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1774 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1775 Sema::CheckConstexprKind Kind) { 1776 // C++11 [dcl.constexpr]p3 and p4: 1777 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1778 // contain only 1779 for (const auto *DclIt : DS->decls()) { 1780 switch (DclIt->getKind()) { 1781 case Decl::StaticAssert: 1782 case Decl::Using: 1783 case Decl::UsingShadow: 1784 case Decl::UsingDirective: 1785 case Decl::UnresolvedUsingTypename: 1786 case Decl::UnresolvedUsingValue: 1787 // - static_assert-declarations 1788 // - using-declarations, 1789 // - using-directives, 1790 continue; 1791 1792 case Decl::Typedef: 1793 case Decl::TypeAlias: { 1794 // - typedef declarations and alias-declarations that do not define 1795 // classes or enumerations, 1796 const auto *TN = cast<TypedefNameDecl>(DclIt); 1797 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1798 // Don't allow variably-modified types in constexpr functions. 1799 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1800 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1801 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1802 << TL.getSourceRange() << TL.getType() 1803 << isa<CXXConstructorDecl>(Dcl); 1804 } 1805 return false; 1806 } 1807 continue; 1808 } 1809 1810 case Decl::Enum: 1811 case Decl::CXXRecord: 1812 // C++1y allows types to be defined, not just declared. 1813 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1814 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1815 SemaRef.Diag(DS->getBeginLoc(), 1816 SemaRef.getLangOpts().CPlusPlus14 1817 ? diag::warn_cxx11_compat_constexpr_type_definition 1818 : diag::ext_constexpr_type_definition) 1819 << isa<CXXConstructorDecl>(Dcl); 1820 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1821 return false; 1822 } 1823 } 1824 continue; 1825 1826 case Decl::EnumConstant: 1827 case Decl::IndirectField: 1828 case Decl::ParmVar: 1829 // These can only appear with other declarations which are banned in 1830 // C++11 and permitted in C++1y, so ignore them. 1831 continue; 1832 1833 case Decl::Var: 1834 case Decl::Decomposition: { 1835 // C++1y [dcl.constexpr]p3 allows anything except: 1836 // a definition of a variable of non-literal type or of static or 1837 // thread storage duration or [before C++2a] for which no 1838 // initialization is performed. 1839 const auto *VD = cast<VarDecl>(DclIt); 1840 if (VD->isThisDeclarationADefinition()) { 1841 if (VD->isStaticLocal()) { 1842 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1843 SemaRef.Diag(VD->getLocation(), 1844 diag::err_constexpr_local_var_static) 1845 << isa<CXXConstructorDecl>(Dcl) 1846 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1847 } 1848 return false; 1849 } 1850 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1851 diag::err_constexpr_local_var_non_literal_type, 1852 isa<CXXConstructorDecl>(Dcl))) 1853 return false; 1854 if (!VD->getType()->isDependentType() && 1855 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1856 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1857 SemaRef.Diag( 1858 VD->getLocation(), 1859 SemaRef.getLangOpts().CPlusPlus2a 1860 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1861 : diag::ext_constexpr_local_var_no_init) 1862 << isa<CXXConstructorDecl>(Dcl); 1863 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 1864 return false; 1865 } 1866 continue; 1867 } 1868 } 1869 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1870 SemaRef.Diag(VD->getLocation(), 1871 SemaRef.getLangOpts().CPlusPlus14 1872 ? diag::warn_cxx11_compat_constexpr_local_var 1873 : diag::ext_constexpr_local_var) 1874 << isa<CXXConstructorDecl>(Dcl); 1875 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1876 return false; 1877 } 1878 continue; 1879 } 1880 1881 case Decl::NamespaceAlias: 1882 case Decl::Function: 1883 // These are disallowed in C++11 and permitted in C++1y. Allow them 1884 // everywhere as an extension. 1885 if (!Cxx1yLoc.isValid()) 1886 Cxx1yLoc = DS->getBeginLoc(); 1887 continue; 1888 1889 default: 1890 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1891 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1892 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1893 } 1894 return false; 1895 } 1896 } 1897 1898 return true; 1899 } 1900 1901 /// Check that the given field is initialized within a constexpr constructor. 1902 /// 1903 /// \param Dcl The constexpr constructor being checked. 1904 /// \param Field The field being checked. This may be a member of an anonymous 1905 /// struct or union nested within the class being checked. 1906 /// \param Inits All declarations, including anonymous struct/union members and 1907 /// indirect members, for which any initialization was provided. 1908 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1909 /// multiple notes for different members to the same error. 1910 /// \param Kind Whether we're diagnosing a constructor as written or determining 1911 /// whether the formal requirements are satisfied. 1912 /// \return \c false if we're checking for validity and the constructor does 1913 /// not satisfy the requirements on a constexpr constructor. 1914 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1915 const FunctionDecl *Dcl, 1916 FieldDecl *Field, 1917 llvm::SmallSet<Decl*, 16> &Inits, 1918 bool &Diagnosed, 1919 Sema::CheckConstexprKind Kind) { 1920 // In C++20 onwards, there's nothing to check for validity. 1921 if (Kind == Sema::CheckConstexprKind::CheckValid && 1922 SemaRef.getLangOpts().CPlusPlus2a) 1923 return true; 1924 1925 if (Field->isInvalidDecl()) 1926 return true; 1927 1928 if (Field->isUnnamedBitfield()) 1929 return true; 1930 1931 // Anonymous unions with no variant members and empty anonymous structs do not 1932 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1933 // indirect fields don't need initializing. 1934 if (Field->isAnonymousStructOrUnion() && 1935 (Field->getType()->isUnionType() 1936 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1937 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1938 return true; 1939 1940 if (!Inits.count(Field)) { 1941 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1942 if (!Diagnosed) { 1943 SemaRef.Diag(Dcl->getLocation(), 1944 SemaRef.getLangOpts().CPlusPlus2a 1945 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1946 : diag::ext_constexpr_ctor_missing_init); 1947 Diagnosed = true; 1948 } 1949 SemaRef.Diag(Field->getLocation(), 1950 diag::note_constexpr_ctor_missing_init); 1951 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 1952 return false; 1953 } 1954 } else if (Field->isAnonymousStructOrUnion()) { 1955 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1956 for (auto *I : RD->fields()) 1957 // If an anonymous union contains an anonymous struct of which any member 1958 // is initialized, all members must be initialized. 1959 if (!RD->isUnion() || Inits.count(I)) 1960 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1961 Kind)) 1962 return false; 1963 } 1964 return true; 1965 } 1966 1967 /// Check the provided statement is allowed in a constexpr function 1968 /// definition. 1969 static bool 1970 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1971 SmallVectorImpl<SourceLocation> &ReturnStmts, 1972 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1973 Sema::CheckConstexprKind Kind) { 1974 // - its function-body shall be [...] a compound-statement that contains only 1975 switch (S->getStmtClass()) { 1976 case Stmt::NullStmtClass: 1977 // - null statements, 1978 return true; 1979 1980 case Stmt::DeclStmtClass: 1981 // - static_assert-declarations 1982 // - using-declarations, 1983 // - using-directives, 1984 // - typedef declarations and alias-declarations that do not define 1985 // classes or enumerations, 1986 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1987 return false; 1988 return true; 1989 1990 case Stmt::ReturnStmtClass: 1991 // - and exactly one return statement; 1992 if (isa<CXXConstructorDecl>(Dcl)) { 1993 // C++1y allows return statements in constexpr constructors. 1994 if (!Cxx1yLoc.isValid()) 1995 Cxx1yLoc = S->getBeginLoc(); 1996 return true; 1997 } 1998 1999 ReturnStmts.push_back(S->getBeginLoc()); 2000 return true; 2001 2002 case Stmt::CompoundStmtClass: { 2003 // C++1y allows compound-statements. 2004 if (!Cxx1yLoc.isValid()) 2005 Cxx1yLoc = S->getBeginLoc(); 2006 2007 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2008 for (auto *BodyIt : CompStmt->body()) { 2009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2010 Cxx1yLoc, Cxx2aLoc, Kind)) 2011 return false; 2012 } 2013 return true; 2014 } 2015 2016 case Stmt::AttributedStmtClass: 2017 if (!Cxx1yLoc.isValid()) 2018 Cxx1yLoc = S->getBeginLoc(); 2019 return true; 2020 2021 case Stmt::IfStmtClass: { 2022 // C++1y allows if-statements. 2023 if (!Cxx1yLoc.isValid()) 2024 Cxx1yLoc = S->getBeginLoc(); 2025 2026 IfStmt *If = cast<IfStmt>(S); 2027 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2028 Cxx1yLoc, Cxx2aLoc, Kind)) 2029 return false; 2030 if (If->getElse() && 2031 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2032 Cxx1yLoc, Cxx2aLoc, Kind)) 2033 return false; 2034 return true; 2035 } 2036 2037 case Stmt::WhileStmtClass: 2038 case Stmt::DoStmtClass: 2039 case Stmt::ForStmtClass: 2040 case Stmt::CXXForRangeStmtClass: 2041 case Stmt::ContinueStmtClass: 2042 // C++1y allows all of these. We don't allow them as extensions in C++11, 2043 // because they don't make sense without variable mutation. 2044 if (!SemaRef.getLangOpts().CPlusPlus14) 2045 break; 2046 if (!Cxx1yLoc.isValid()) 2047 Cxx1yLoc = S->getBeginLoc(); 2048 for (Stmt *SubStmt : S->children()) 2049 if (SubStmt && 2050 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2051 Cxx1yLoc, Cxx2aLoc, Kind)) 2052 return false; 2053 return true; 2054 2055 case Stmt::SwitchStmtClass: 2056 case Stmt::CaseStmtClass: 2057 case Stmt::DefaultStmtClass: 2058 case Stmt::BreakStmtClass: 2059 // C++1y allows switch-statements, and since they don't need variable 2060 // mutation, we can reasonably allow them in C++11 as an extension. 2061 if (!Cxx1yLoc.isValid()) 2062 Cxx1yLoc = S->getBeginLoc(); 2063 for (Stmt *SubStmt : S->children()) 2064 if (SubStmt && 2065 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2066 Cxx1yLoc, Cxx2aLoc, Kind)) 2067 return false; 2068 return true; 2069 2070 case Stmt::GCCAsmStmtClass: 2071 case Stmt::MSAsmStmtClass: 2072 // C++2a allows inline assembly statements. 2073 case Stmt::CXXTryStmtClass: 2074 if (Cxx2aLoc.isInvalid()) 2075 Cxx2aLoc = S->getBeginLoc(); 2076 for (Stmt *SubStmt : S->children()) { 2077 if (SubStmt && 2078 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2079 Cxx1yLoc, Cxx2aLoc, Kind)) 2080 return false; 2081 } 2082 return true; 2083 2084 case Stmt::CXXCatchStmtClass: 2085 // Do not bother checking the language mode (already covered by the 2086 // try block check). 2087 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2088 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2089 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2090 return false; 2091 return true; 2092 2093 default: 2094 if (!isa<Expr>(S)) 2095 break; 2096 2097 // C++1y allows expression-statements. 2098 if (!Cxx1yLoc.isValid()) 2099 Cxx1yLoc = S->getBeginLoc(); 2100 return true; 2101 } 2102 2103 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2104 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2105 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2106 } 2107 return false; 2108 } 2109 2110 /// Check the body for the given constexpr function declaration only contains 2111 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2112 /// 2113 /// \return true if the body is OK, false if we have found or diagnosed a 2114 /// problem. 2115 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2116 Stmt *Body, 2117 Sema::CheckConstexprKind Kind) { 2118 SmallVector<SourceLocation, 4> ReturnStmts; 2119 2120 if (isa<CXXTryStmt>(Body)) { 2121 // C++11 [dcl.constexpr]p3: 2122 // The definition of a constexpr function shall satisfy the following 2123 // constraints: [...] 2124 // - its function-body shall be = delete, = default, or a 2125 // compound-statement 2126 // 2127 // C++11 [dcl.constexpr]p4: 2128 // In the definition of a constexpr constructor, [...] 2129 // - its function-body shall not be a function-try-block; 2130 // 2131 // This restriction is lifted in C++2a, as long as inner statements also 2132 // apply the general constexpr rules. 2133 switch (Kind) { 2134 case Sema::CheckConstexprKind::CheckValid: 2135 if (!SemaRef.getLangOpts().CPlusPlus2a) 2136 return false; 2137 break; 2138 2139 case Sema::CheckConstexprKind::Diagnose: 2140 SemaRef.Diag(Body->getBeginLoc(), 2141 !SemaRef.getLangOpts().CPlusPlus2a 2142 ? diag::ext_constexpr_function_try_block_cxx2a 2143 : diag::warn_cxx17_compat_constexpr_function_try_block) 2144 << isa<CXXConstructorDecl>(Dcl); 2145 break; 2146 } 2147 } 2148 2149 // - its function-body shall be [...] a compound-statement that contains only 2150 // [... list of cases ...] 2151 // 2152 // Note that walking the children here is enough to properly check for 2153 // CompoundStmt and CXXTryStmt body. 2154 SourceLocation Cxx1yLoc, Cxx2aLoc; 2155 for (Stmt *SubStmt : Body->children()) { 2156 if (SubStmt && 2157 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2158 Cxx1yLoc, Cxx2aLoc, Kind)) 2159 return false; 2160 } 2161 2162 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2163 // If this is only valid as an extension, report that we don't satisfy the 2164 // constraints of the current language. 2165 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) || 2166 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2167 return false; 2168 } else if (Cxx2aLoc.isValid()) { 2169 SemaRef.Diag(Cxx2aLoc, 2170 SemaRef.getLangOpts().CPlusPlus2a 2171 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2172 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 2173 << isa<CXXConstructorDecl>(Dcl); 2174 } else if (Cxx1yLoc.isValid()) { 2175 SemaRef.Diag(Cxx1yLoc, 2176 SemaRef.getLangOpts().CPlusPlus14 2177 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2178 : diag::ext_constexpr_body_invalid_stmt) 2179 << isa<CXXConstructorDecl>(Dcl); 2180 } 2181 2182 if (const CXXConstructorDecl *Constructor 2183 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2184 const CXXRecordDecl *RD = Constructor->getParent(); 2185 // DR1359: 2186 // - every non-variant non-static data member and base class sub-object 2187 // shall be initialized; 2188 // DR1460: 2189 // - if the class is a union having variant members, exactly one of them 2190 // shall be initialized; 2191 if (RD->isUnion()) { 2192 if (Constructor->getNumCtorInitializers() == 0 && 2193 RD->hasVariantMembers()) { 2194 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2195 SemaRef.Diag( 2196 Dcl->getLocation(), 2197 SemaRef.getLangOpts().CPlusPlus2a 2198 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2199 : diag::ext_constexpr_union_ctor_no_init); 2200 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 2201 return false; 2202 } 2203 } 2204 } else if (!Constructor->isDependentContext() && 2205 !Constructor->isDelegatingConstructor()) { 2206 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2207 2208 // Skip detailed checking if we have enough initializers, and we would 2209 // allow at most one initializer per member. 2210 bool AnyAnonStructUnionMembers = false; 2211 unsigned Fields = 0; 2212 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2213 E = RD->field_end(); I != E; ++I, ++Fields) { 2214 if (I->isAnonymousStructOrUnion()) { 2215 AnyAnonStructUnionMembers = true; 2216 break; 2217 } 2218 } 2219 // DR1460: 2220 // - if the class is a union-like class, but is not a union, for each of 2221 // its anonymous union members having variant members, exactly one of 2222 // them shall be initialized; 2223 if (AnyAnonStructUnionMembers || 2224 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2225 // Check initialization of non-static data members. Base classes are 2226 // always initialized so do not need to be checked. Dependent bases 2227 // might not have initializers in the member initializer list. 2228 llvm::SmallSet<Decl*, 16> Inits; 2229 for (const auto *I: Constructor->inits()) { 2230 if (FieldDecl *FD = I->getMember()) 2231 Inits.insert(FD); 2232 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2233 Inits.insert(ID->chain_begin(), ID->chain_end()); 2234 } 2235 2236 bool Diagnosed = false; 2237 for (auto *I : RD->fields()) 2238 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2239 Kind)) 2240 return false; 2241 } 2242 } 2243 } else { 2244 if (ReturnStmts.empty()) { 2245 // C++1y doesn't require constexpr functions to contain a 'return' 2246 // statement. We still do, unless the return type might be void, because 2247 // otherwise if there's no return statement, the function cannot 2248 // be used in a core constant expression. 2249 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2250 (Dcl->getReturnType()->isVoidType() || 2251 Dcl->getReturnType()->isDependentType()); 2252 switch (Kind) { 2253 case Sema::CheckConstexprKind::Diagnose: 2254 SemaRef.Diag(Dcl->getLocation(), 2255 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2256 : diag::err_constexpr_body_no_return) 2257 << Dcl->isConsteval(); 2258 if (!OK) 2259 return false; 2260 break; 2261 2262 case Sema::CheckConstexprKind::CheckValid: 2263 // The formal requirements don't include this rule in C++14, even 2264 // though the "must be able to produce a constant expression" rules 2265 // still imply it in some cases. 2266 if (!SemaRef.getLangOpts().CPlusPlus14) 2267 return false; 2268 break; 2269 } 2270 } else if (ReturnStmts.size() > 1) { 2271 switch (Kind) { 2272 case Sema::CheckConstexprKind::Diagnose: 2273 SemaRef.Diag( 2274 ReturnStmts.back(), 2275 SemaRef.getLangOpts().CPlusPlus14 2276 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2277 : diag::ext_constexpr_body_multiple_return); 2278 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2279 SemaRef.Diag(ReturnStmts[I], 2280 diag::note_constexpr_body_previous_return); 2281 break; 2282 2283 case Sema::CheckConstexprKind::CheckValid: 2284 if (!SemaRef.getLangOpts().CPlusPlus14) 2285 return false; 2286 break; 2287 } 2288 } 2289 } 2290 2291 // C++11 [dcl.constexpr]p5: 2292 // if no function argument values exist such that the function invocation 2293 // substitution would produce a constant expression, the program is 2294 // ill-formed; no diagnostic required. 2295 // C++11 [dcl.constexpr]p3: 2296 // - every constructor call and implicit conversion used in initializing the 2297 // return value shall be one of those allowed in a constant expression. 2298 // C++11 [dcl.constexpr]p4: 2299 // - every constructor involved in initializing non-static data members and 2300 // base class sub-objects shall be a constexpr constructor. 2301 // 2302 // Note that this rule is distinct from the "requirements for a constexpr 2303 // function", so is not checked in CheckValid mode. 2304 SmallVector<PartialDiagnosticAt, 8> Diags; 2305 if (Kind == Sema::CheckConstexprKind::Diagnose && 2306 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2307 SemaRef.Diag(Dcl->getLocation(), 2308 diag::ext_constexpr_function_never_constant_expr) 2309 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2310 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2311 SemaRef.Diag(Diags[I].first, Diags[I].second); 2312 // Don't return false here: we allow this for compatibility in 2313 // system headers. 2314 } 2315 2316 return true; 2317 } 2318 2319 /// Get the class that is directly named by the current context. This is the 2320 /// class for which an unqualified-id in this scope could name a constructor 2321 /// or destructor. 2322 /// 2323 /// If the scope specifier denotes a class, this will be that class. 2324 /// If the scope specifier is empty, this will be the class whose 2325 /// member-specification we are currently within. Otherwise, there 2326 /// is no such class. 2327 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2328 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2329 2330 if (SS && SS->isInvalid()) 2331 return nullptr; 2332 2333 if (SS && SS->isNotEmpty()) { 2334 DeclContext *DC = computeDeclContext(*SS, true); 2335 return dyn_cast_or_null<CXXRecordDecl>(DC); 2336 } 2337 2338 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2339 } 2340 2341 /// isCurrentClassName - Determine whether the identifier II is the 2342 /// name of the class type currently being defined. In the case of 2343 /// nested classes, this will only return true if II is the name of 2344 /// the innermost class. 2345 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2346 const CXXScopeSpec *SS) { 2347 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2348 return CurDecl && &II == CurDecl->getIdentifier(); 2349 } 2350 2351 /// Determine whether the identifier II is a typo for the name of 2352 /// the class type currently being defined. If so, update it to the identifier 2353 /// that should have been used. 2354 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2355 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2356 2357 if (!getLangOpts().SpellChecking) 2358 return false; 2359 2360 CXXRecordDecl *CurDecl; 2361 if (SS && SS->isSet() && !SS->isInvalid()) { 2362 DeclContext *DC = computeDeclContext(*SS, true); 2363 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2364 } else 2365 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2366 2367 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2368 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2369 < II->getLength()) { 2370 II = CurDecl->getIdentifier(); 2371 return true; 2372 } 2373 2374 return false; 2375 } 2376 2377 /// Determine whether the given class is a base class of the given 2378 /// class, including looking at dependent bases. 2379 static bool findCircularInheritance(const CXXRecordDecl *Class, 2380 const CXXRecordDecl *Current) { 2381 SmallVector<const CXXRecordDecl*, 8> Queue; 2382 2383 Class = Class->getCanonicalDecl(); 2384 while (true) { 2385 for (const auto &I : Current->bases()) { 2386 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2387 if (!Base) 2388 continue; 2389 2390 Base = Base->getDefinition(); 2391 if (!Base) 2392 continue; 2393 2394 if (Base->getCanonicalDecl() == Class) 2395 return true; 2396 2397 Queue.push_back(Base); 2398 } 2399 2400 if (Queue.empty()) 2401 return false; 2402 2403 Current = Queue.pop_back_val(); 2404 } 2405 2406 return false; 2407 } 2408 2409 /// Check the validity of a C++ base class specifier. 2410 /// 2411 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2412 /// and returns NULL otherwise. 2413 CXXBaseSpecifier * 2414 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2415 SourceRange SpecifierRange, 2416 bool Virtual, AccessSpecifier Access, 2417 TypeSourceInfo *TInfo, 2418 SourceLocation EllipsisLoc) { 2419 QualType BaseType = TInfo->getType(); 2420 2421 // C++ [class.union]p1: 2422 // A union shall not have base classes. 2423 if (Class->isUnion()) { 2424 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2425 << SpecifierRange; 2426 return nullptr; 2427 } 2428 2429 if (EllipsisLoc.isValid() && 2430 !TInfo->getType()->containsUnexpandedParameterPack()) { 2431 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2432 << TInfo->getTypeLoc().getSourceRange(); 2433 EllipsisLoc = SourceLocation(); 2434 } 2435 2436 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2437 2438 if (BaseType->isDependentType()) { 2439 // Make sure that we don't have circular inheritance among our dependent 2440 // bases. For non-dependent bases, the check for completeness below handles 2441 // this. 2442 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2443 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2444 ((BaseDecl = BaseDecl->getDefinition()) && 2445 findCircularInheritance(Class, BaseDecl))) { 2446 Diag(BaseLoc, diag::err_circular_inheritance) 2447 << BaseType << Context.getTypeDeclType(Class); 2448 2449 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2450 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2451 << BaseType; 2452 2453 return nullptr; 2454 } 2455 } 2456 2457 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2458 Class->getTagKind() == TTK_Class, 2459 Access, TInfo, EllipsisLoc); 2460 } 2461 2462 // Base specifiers must be record types. 2463 if (!BaseType->isRecordType()) { 2464 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2465 return nullptr; 2466 } 2467 2468 // C++ [class.union]p1: 2469 // A union shall not be used as a base class. 2470 if (BaseType->isUnionType()) { 2471 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2472 return nullptr; 2473 } 2474 2475 // For the MS ABI, propagate DLL attributes to base class templates. 2476 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2477 if (Attr *ClassAttr = getDLLAttr(Class)) { 2478 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2479 BaseType->getAsCXXRecordDecl())) { 2480 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2481 BaseLoc); 2482 } 2483 } 2484 } 2485 2486 // C++ [class.derived]p2: 2487 // The class-name in a base-specifier shall not be an incompletely 2488 // defined class. 2489 if (RequireCompleteType(BaseLoc, BaseType, 2490 diag::err_incomplete_base_class, SpecifierRange)) { 2491 Class->setInvalidDecl(); 2492 return nullptr; 2493 } 2494 2495 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2496 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2497 assert(BaseDecl && "Record type has no declaration"); 2498 BaseDecl = BaseDecl->getDefinition(); 2499 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2500 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2501 assert(CXXBaseDecl && "Base type is not a C++ type"); 2502 2503 // Microsoft docs say: 2504 // "If a base-class has a code_seg attribute, derived classes must have the 2505 // same attribute." 2506 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2507 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2508 if ((DerivedCSA || BaseCSA) && 2509 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2510 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2511 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2512 << CXXBaseDecl; 2513 return nullptr; 2514 } 2515 2516 // A class which contains a flexible array member is not suitable for use as a 2517 // base class: 2518 // - If the layout determines that a base comes before another base, 2519 // the flexible array member would index into the subsequent base. 2520 // - If the layout determines that base comes before the derived class, 2521 // the flexible array member would index into the derived class. 2522 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2523 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2524 << CXXBaseDecl->getDeclName(); 2525 return nullptr; 2526 } 2527 2528 // C++ [class]p3: 2529 // If a class is marked final and it appears as a base-type-specifier in 2530 // base-clause, the program is ill-formed. 2531 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2532 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2533 << CXXBaseDecl->getDeclName() 2534 << FA->isSpelledAsSealed(); 2535 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2536 << CXXBaseDecl->getDeclName() << FA->getRange(); 2537 return nullptr; 2538 } 2539 2540 if (BaseDecl->isInvalidDecl()) 2541 Class->setInvalidDecl(); 2542 2543 // Create the base specifier. 2544 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2545 Class->getTagKind() == TTK_Class, 2546 Access, TInfo, EllipsisLoc); 2547 } 2548 2549 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2550 /// one entry in the base class list of a class specifier, for 2551 /// example: 2552 /// class foo : public bar, virtual private baz { 2553 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2554 BaseResult 2555 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2556 ParsedAttributes &Attributes, 2557 bool Virtual, AccessSpecifier Access, 2558 ParsedType basetype, SourceLocation BaseLoc, 2559 SourceLocation EllipsisLoc) { 2560 if (!classdecl) 2561 return true; 2562 2563 AdjustDeclIfTemplate(classdecl); 2564 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2565 if (!Class) 2566 return true; 2567 2568 // We haven't yet attached the base specifiers. 2569 Class->setIsParsingBaseSpecifiers(); 2570 2571 // We do not support any C++11 attributes on base-specifiers yet. 2572 // Diagnose any attributes we see. 2573 for (const ParsedAttr &AL : Attributes) { 2574 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2575 continue; 2576 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2577 ? (unsigned)diag::warn_unknown_attribute_ignored 2578 : (unsigned)diag::err_base_specifier_attribute) 2579 << AL; 2580 } 2581 2582 TypeSourceInfo *TInfo = nullptr; 2583 GetTypeFromParser(basetype, &TInfo); 2584 2585 if (EllipsisLoc.isInvalid() && 2586 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2587 UPPC_BaseType)) 2588 return true; 2589 2590 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2591 Virtual, Access, TInfo, 2592 EllipsisLoc)) 2593 return BaseSpec; 2594 else 2595 Class->setInvalidDecl(); 2596 2597 return true; 2598 } 2599 2600 /// Use small set to collect indirect bases. As this is only used 2601 /// locally, there's no need to abstract the small size parameter. 2602 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2603 2604 /// Recursively add the bases of Type. Don't add Type itself. 2605 static void 2606 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2607 const QualType &Type) 2608 { 2609 // Even though the incoming type is a base, it might not be 2610 // a class -- it could be a template parm, for instance. 2611 if (auto Rec = Type->getAs<RecordType>()) { 2612 auto Decl = Rec->getAsCXXRecordDecl(); 2613 2614 // Iterate over its bases. 2615 for (const auto &BaseSpec : Decl->bases()) { 2616 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2617 .getUnqualifiedType(); 2618 if (Set.insert(Base).second) 2619 // If we've not already seen it, recurse. 2620 NoteIndirectBases(Context, Set, Base); 2621 } 2622 } 2623 } 2624 2625 /// Performs the actual work of attaching the given base class 2626 /// specifiers to a C++ class. 2627 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2628 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2629 if (Bases.empty()) 2630 return false; 2631 2632 // Used to keep track of which base types we have already seen, so 2633 // that we can properly diagnose redundant direct base types. Note 2634 // that the key is always the unqualified canonical type of the base 2635 // class. 2636 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2637 2638 // Used to track indirect bases so we can see if a direct base is 2639 // ambiguous. 2640 IndirectBaseSet IndirectBaseTypes; 2641 2642 // Copy non-redundant base specifiers into permanent storage. 2643 unsigned NumGoodBases = 0; 2644 bool Invalid = false; 2645 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2646 QualType NewBaseType 2647 = Context.getCanonicalType(Bases[idx]->getType()); 2648 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2649 2650 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2651 if (KnownBase) { 2652 // C++ [class.mi]p3: 2653 // A class shall not be specified as a direct base class of a 2654 // derived class more than once. 2655 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2656 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2657 2658 // Delete the duplicate base class specifier; we're going to 2659 // overwrite its pointer later. 2660 Context.Deallocate(Bases[idx]); 2661 2662 Invalid = true; 2663 } else { 2664 // Okay, add this new base class. 2665 KnownBase = Bases[idx]; 2666 Bases[NumGoodBases++] = Bases[idx]; 2667 2668 // Note this base's direct & indirect bases, if there could be ambiguity. 2669 if (Bases.size() > 1) 2670 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2671 2672 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2673 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2674 if (Class->isInterface() && 2675 (!RD->isInterfaceLike() || 2676 KnownBase->getAccessSpecifier() != AS_public)) { 2677 // The Microsoft extension __interface does not permit bases that 2678 // are not themselves public interfaces. 2679 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2680 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2681 << RD->getSourceRange(); 2682 Invalid = true; 2683 } 2684 if (RD->hasAttr<WeakAttr>()) 2685 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2686 } 2687 } 2688 } 2689 2690 // Attach the remaining base class specifiers to the derived class. 2691 Class->setBases(Bases.data(), NumGoodBases); 2692 2693 // Check that the only base classes that are duplicate are virtual. 2694 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2695 // Check whether this direct base is inaccessible due to ambiguity. 2696 QualType BaseType = Bases[idx]->getType(); 2697 2698 // Skip all dependent types in templates being used as base specifiers. 2699 // Checks below assume that the base specifier is a CXXRecord. 2700 if (BaseType->isDependentType()) 2701 continue; 2702 2703 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2704 .getUnqualifiedType(); 2705 2706 if (IndirectBaseTypes.count(CanonicalBase)) { 2707 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2708 /*DetectVirtual=*/true); 2709 bool found 2710 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2711 assert(found); 2712 (void)found; 2713 2714 if (Paths.isAmbiguous(CanonicalBase)) 2715 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2716 << BaseType << getAmbiguousPathsDisplayString(Paths) 2717 << Bases[idx]->getSourceRange(); 2718 else 2719 assert(Bases[idx]->isVirtual()); 2720 } 2721 2722 // Delete the base class specifier, since its data has been copied 2723 // into the CXXRecordDecl. 2724 Context.Deallocate(Bases[idx]); 2725 } 2726 2727 return Invalid; 2728 } 2729 2730 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2731 /// class, after checking whether there are any duplicate base 2732 /// classes. 2733 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2734 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2735 if (!ClassDecl || Bases.empty()) 2736 return; 2737 2738 AdjustDeclIfTemplate(ClassDecl); 2739 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2740 } 2741 2742 /// Determine whether the type \p Derived is a C++ class that is 2743 /// derived from the type \p Base. 2744 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2745 if (!getLangOpts().CPlusPlus) 2746 return false; 2747 2748 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2749 if (!DerivedRD) 2750 return false; 2751 2752 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2753 if (!BaseRD) 2754 return false; 2755 2756 // If either the base or the derived type is invalid, don't try to 2757 // check whether one is derived from the other. 2758 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2759 return false; 2760 2761 // FIXME: In a modules build, do we need the entire path to be visible for us 2762 // to be able to use the inheritance relationship? 2763 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2764 return false; 2765 2766 return DerivedRD->isDerivedFrom(BaseRD); 2767 } 2768 2769 /// Determine whether the type \p Derived is a C++ class that is 2770 /// derived from the type \p Base. 2771 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2772 CXXBasePaths &Paths) { 2773 if (!getLangOpts().CPlusPlus) 2774 return false; 2775 2776 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2777 if (!DerivedRD) 2778 return false; 2779 2780 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2781 if (!BaseRD) 2782 return false; 2783 2784 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2785 return false; 2786 2787 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2788 } 2789 2790 static void BuildBasePathArray(const CXXBasePath &Path, 2791 CXXCastPath &BasePathArray) { 2792 // We first go backward and check if we have a virtual base. 2793 // FIXME: It would be better if CXXBasePath had the base specifier for 2794 // the nearest virtual base. 2795 unsigned Start = 0; 2796 for (unsigned I = Path.size(); I != 0; --I) { 2797 if (Path[I - 1].Base->isVirtual()) { 2798 Start = I - 1; 2799 break; 2800 } 2801 } 2802 2803 // Now add all bases. 2804 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2805 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2806 } 2807 2808 2809 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2810 CXXCastPath &BasePathArray) { 2811 assert(BasePathArray.empty() && "Base path array must be empty!"); 2812 assert(Paths.isRecordingPaths() && "Must record paths!"); 2813 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2814 } 2815 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2816 /// conversion (where Derived and Base are class types) is 2817 /// well-formed, meaning that the conversion is unambiguous (and 2818 /// that all of the base classes are accessible). Returns true 2819 /// and emits a diagnostic if the code is ill-formed, returns false 2820 /// otherwise. Loc is the location where this routine should point to 2821 /// if there is an error, and Range is the source range to highlight 2822 /// if there is an error. 2823 /// 2824 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2825 /// diagnostic for the respective type of error will be suppressed, but the 2826 /// check for ill-formed code will still be performed. 2827 bool 2828 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2829 unsigned InaccessibleBaseID, 2830 unsigned AmbigiousBaseConvID, 2831 SourceLocation Loc, SourceRange Range, 2832 DeclarationName Name, 2833 CXXCastPath *BasePath, 2834 bool IgnoreAccess) { 2835 // First, determine whether the path from Derived to Base is 2836 // ambiguous. This is slightly more expensive than checking whether 2837 // the Derived to Base conversion exists, because here we need to 2838 // explore multiple paths to determine if there is an ambiguity. 2839 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2840 /*DetectVirtual=*/false); 2841 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2842 if (!DerivationOkay) 2843 return true; 2844 2845 const CXXBasePath *Path = nullptr; 2846 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2847 Path = &Paths.front(); 2848 2849 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2850 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2851 // user to access such bases. 2852 if (!Path && getLangOpts().MSVCCompat) { 2853 for (const CXXBasePath &PossiblePath : Paths) { 2854 if (PossiblePath.size() == 1) { 2855 Path = &PossiblePath; 2856 if (AmbigiousBaseConvID) 2857 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2858 << Base << Derived << Range; 2859 break; 2860 } 2861 } 2862 } 2863 2864 if (Path) { 2865 if (!IgnoreAccess) { 2866 // Check that the base class can be accessed. 2867 switch ( 2868 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2869 case AR_inaccessible: 2870 return true; 2871 case AR_accessible: 2872 case AR_dependent: 2873 case AR_delayed: 2874 break; 2875 } 2876 } 2877 2878 // Build a base path if necessary. 2879 if (BasePath) 2880 ::BuildBasePathArray(*Path, *BasePath); 2881 return false; 2882 } 2883 2884 if (AmbigiousBaseConvID) { 2885 // We know that the derived-to-base conversion is ambiguous, and 2886 // we're going to produce a diagnostic. Perform the derived-to-base 2887 // search just one more time to compute all of the possible paths so 2888 // that we can print them out. This is more expensive than any of 2889 // the previous derived-to-base checks we've done, but at this point 2890 // performance isn't as much of an issue. 2891 Paths.clear(); 2892 Paths.setRecordingPaths(true); 2893 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2894 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2895 (void)StillOkay; 2896 2897 // Build up a textual representation of the ambiguous paths, e.g., 2898 // D -> B -> A, that will be used to illustrate the ambiguous 2899 // conversions in the diagnostic. We only print one of the paths 2900 // to each base class subobject. 2901 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2902 2903 Diag(Loc, AmbigiousBaseConvID) 2904 << Derived << Base << PathDisplayStr << Range << Name; 2905 } 2906 return true; 2907 } 2908 2909 bool 2910 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2911 SourceLocation Loc, SourceRange Range, 2912 CXXCastPath *BasePath, 2913 bool IgnoreAccess) { 2914 return CheckDerivedToBaseConversion( 2915 Derived, Base, diag::err_upcast_to_inaccessible_base, 2916 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2917 BasePath, IgnoreAccess); 2918 } 2919 2920 2921 /// Builds a string representing ambiguous paths from a 2922 /// specific derived class to different subobjects of the same base 2923 /// class. 2924 /// 2925 /// This function builds a string that can be used in error messages 2926 /// to show the different paths that one can take through the 2927 /// inheritance hierarchy to go from the derived class to different 2928 /// subobjects of a base class. The result looks something like this: 2929 /// @code 2930 /// struct D -> struct B -> struct A 2931 /// struct D -> struct C -> struct A 2932 /// @endcode 2933 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2934 std::string PathDisplayStr; 2935 std::set<unsigned> DisplayedPaths; 2936 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2937 Path != Paths.end(); ++Path) { 2938 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2939 // We haven't displayed a path to this particular base 2940 // class subobject yet. 2941 PathDisplayStr += "\n "; 2942 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2943 for (CXXBasePath::const_iterator Element = Path->begin(); 2944 Element != Path->end(); ++Element) 2945 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2946 } 2947 } 2948 2949 return PathDisplayStr; 2950 } 2951 2952 //===----------------------------------------------------------------------===// 2953 // C++ class member Handling 2954 //===----------------------------------------------------------------------===// 2955 2956 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2957 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2958 SourceLocation ColonLoc, 2959 const ParsedAttributesView &Attrs) { 2960 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2961 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2962 ASLoc, ColonLoc); 2963 CurContext->addHiddenDecl(ASDecl); 2964 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2965 } 2966 2967 /// CheckOverrideControl - Check C++11 override control semantics. 2968 void Sema::CheckOverrideControl(NamedDecl *D) { 2969 if (D->isInvalidDecl()) 2970 return; 2971 2972 // We only care about "override" and "final" declarations. 2973 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2974 return; 2975 2976 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2977 2978 // We can't check dependent instance methods. 2979 if (MD && MD->isInstance() && 2980 (MD->getParent()->hasAnyDependentBases() || 2981 MD->getType()->isDependentType())) 2982 return; 2983 2984 if (MD && !MD->isVirtual()) { 2985 // If we have a non-virtual method, check if if hides a virtual method. 2986 // (In that case, it's most likely the method has the wrong type.) 2987 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2988 FindHiddenVirtualMethods(MD, OverloadedMethods); 2989 2990 if (!OverloadedMethods.empty()) { 2991 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2992 Diag(OA->getLocation(), 2993 diag::override_keyword_hides_virtual_member_function) 2994 << "override" << (OverloadedMethods.size() > 1); 2995 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2996 Diag(FA->getLocation(), 2997 diag::override_keyword_hides_virtual_member_function) 2998 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2999 << (OverloadedMethods.size() > 1); 3000 } 3001 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3002 MD->setInvalidDecl(); 3003 return; 3004 } 3005 // Fall through into the general case diagnostic. 3006 // FIXME: We might want to attempt typo correction here. 3007 } 3008 3009 if (!MD || !MD->isVirtual()) { 3010 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3011 Diag(OA->getLocation(), 3012 diag::override_keyword_only_allowed_on_virtual_member_functions) 3013 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3014 D->dropAttr<OverrideAttr>(); 3015 } 3016 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3017 Diag(FA->getLocation(), 3018 diag::override_keyword_only_allowed_on_virtual_member_functions) 3019 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3020 << FixItHint::CreateRemoval(FA->getLocation()); 3021 D->dropAttr<FinalAttr>(); 3022 } 3023 return; 3024 } 3025 3026 // C++11 [class.virtual]p5: 3027 // If a function is marked with the virt-specifier override and 3028 // does not override a member function of a base class, the program is 3029 // ill-formed. 3030 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3031 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3032 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3033 << MD->getDeclName(); 3034 } 3035 3036 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 3037 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3038 return; 3039 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3040 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3041 return; 3042 3043 SourceLocation Loc = MD->getLocation(); 3044 SourceLocation SpellingLoc = Loc; 3045 if (getSourceManager().isMacroArgExpansion(Loc)) 3046 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3047 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3048 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3049 return; 3050 3051 if (MD->size_overridden_methods() > 0) { 3052 unsigned DiagID = isa<CXXDestructorDecl>(MD) 3053 ? diag::warn_destructor_marked_not_override_overriding 3054 : diag::warn_function_marked_not_override_overriding; 3055 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3056 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3057 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3058 } 3059 } 3060 3061 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3062 /// function overrides a virtual member function marked 'final', according to 3063 /// C++11 [class.virtual]p4. 3064 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3065 const CXXMethodDecl *Old) { 3066 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3067 if (!FA) 3068 return false; 3069 3070 Diag(New->getLocation(), diag::err_final_function_overridden) 3071 << New->getDeclName() 3072 << FA->isSpelledAsSealed(); 3073 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3074 return true; 3075 } 3076 3077 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3078 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3079 // FIXME: Destruction of ObjC lifetime types has side-effects. 3080 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3081 return !RD->isCompleteDefinition() || 3082 !RD->hasTrivialDefaultConstructor() || 3083 !RD->hasTrivialDestructor(); 3084 return false; 3085 } 3086 3087 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3088 ParsedAttributesView::const_iterator Itr = 3089 llvm::find_if(list, [](const ParsedAttr &AL) { 3090 return AL.isDeclspecPropertyAttribute(); 3091 }); 3092 if (Itr != list.end()) 3093 return &*Itr; 3094 return nullptr; 3095 } 3096 3097 // Check if there is a field shadowing. 3098 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3099 DeclarationName FieldName, 3100 const CXXRecordDecl *RD, 3101 bool DeclIsField) { 3102 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3103 return; 3104 3105 // To record a shadowed field in a base 3106 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3107 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3108 CXXBasePath &Path) { 3109 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3110 // Record an ambiguous path directly 3111 if (Bases.find(Base) != Bases.end()) 3112 return true; 3113 for (const auto Field : Base->lookup(FieldName)) { 3114 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3115 Field->getAccess() != AS_private) { 3116 assert(Field->getAccess() != AS_none); 3117 assert(Bases.find(Base) == Bases.end()); 3118 Bases[Base] = Field; 3119 return true; 3120 } 3121 } 3122 return false; 3123 }; 3124 3125 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3126 /*DetectVirtual=*/true); 3127 if (!RD->lookupInBases(FieldShadowed, Paths)) 3128 return; 3129 3130 for (const auto &P : Paths) { 3131 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3132 auto It = Bases.find(Base); 3133 // Skip duplicated bases 3134 if (It == Bases.end()) 3135 continue; 3136 auto BaseField = It->second; 3137 assert(BaseField->getAccess() != AS_private); 3138 if (AS_none != 3139 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3140 Diag(Loc, diag::warn_shadow_field) 3141 << FieldName << RD << Base << DeclIsField; 3142 Diag(BaseField->getLocation(), diag::note_shadow_field); 3143 Bases.erase(It); 3144 } 3145 } 3146 } 3147 3148 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3149 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3150 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3151 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3152 /// present (but parsing it has been deferred). 3153 NamedDecl * 3154 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3155 MultiTemplateParamsArg TemplateParameterLists, 3156 Expr *BW, const VirtSpecifiers &VS, 3157 InClassInitStyle InitStyle) { 3158 const DeclSpec &DS = D.getDeclSpec(); 3159 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3160 DeclarationName Name = NameInfo.getName(); 3161 SourceLocation Loc = NameInfo.getLoc(); 3162 3163 // For anonymous bitfields, the location should point to the type. 3164 if (Loc.isInvalid()) 3165 Loc = D.getBeginLoc(); 3166 3167 Expr *BitWidth = static_cast<Expr*>(BW); 3168 3169 assert(isa<CXXRecordDecl>(CurContext)); 3170 assert(!DS.isFriendSpecified()); 3171 3172 bool isFunc = D.isDeclarationOfFunction(); 3173 const ParsedAttr *MSPropertyAttr = 3174 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3175 3176 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3177 // The Microsoft extension __interface only permits public member functions 3178 // and prohibits constructors, destructors, operators, non-public member 3179 // functions, static methods and data members. 3180 unsigned InvalidDecl; 3181 bool ShowDeclName = true; 3182 if (!isFunc && 3183 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3184 InvalidDecl = 0; 3185 else if (!isFunc) 3186 InvalidDecl = 1; 3187 else if (AS != AS_public) 3188 InvalidDecl = 2; 3189 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3190 InvalidDecl = 3; 3191 else switch (Name.getNameKind()) { 3192 case DeclarationName::CXXConstructorName: 3193 InvalidDecl = 4; 3194 ShowDeclName = false; 3195 break; 3196 3197 case DeclarationName::CXXDestructorName: 3198 InvalidDecl = 5; 3199 ShowDeclName = false; 3200 break; 3201 3202 case DeclarationName::CXXOperatorName: 3203 case DeclarationName::CXXConversionFunctionName: 3204 InvalidDecl = 6; 3205 break; 3206 3207 default: 3208 InvalidDecl = 0; 3209 break; 3210 } 3211 3212 if (InvalidDecl) { 3213 if (ShowDeclName) 3214 Diag(Loc, diag::err_invalid_member_in_interface) 3215 << (InvalidDecl-1) << Name; 3216 else 3217 Diag(Loc, diag::err_invalid_member_in_interface) 3218 << (InvalidDecl-1) << ""; 3219 return nullptr; 3220 } 3221 } 3222 3223 // C++ 9.2p6: A member shall not be declared to have automatic storage 3224 // duration (auto, register) or with the extern storage-class-specifier. 3225 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3226 // data members and cannot be applied to names declared const or static, 3227 // and cannot be applied to reference members. 3228 switch (DS.getStorageClassSpec()) { 3229 case DeclSpec::SCS_unspecified: 3230 case DeclSpec::SCS_typedef: 3231 case DeclSpec::SCS_static: 3232 break; 3233 case DeclSpec::SCS_mutable: 3234 if (isFunc) { 3235 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3236 3237 // FIXME: It would be nicer if the keyword was ignored only for this 3238 // declarator. Otherwise we could get follow-up errors. 3239 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3240 } 3241 break; 3242 default: 3243 Diag(DS.getStorageClassSpecLoc(), 3244 diag::err_storageclass_invalid_for_member); 3245 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3246 break; 3247 } 3248 3249 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3250 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3251 !isFunc); 3252 3253 if (DS.hasConstexprSpecifier() && isInstField) { 3254 SemaDiagnosticBuilder B = 3255 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3256 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3257 if (InitStyle == ICIS_NoInit) { 3258 B << 0 << 0; 3259 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3260 B << FixItHint::CreateRemoval(ConstexprLoc); 3261 else { 3262 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3263 D.getMutableDeclSpec().ClearConstexprSpec(); 3264 const char *PrevSpec; 3265 unsigned DiagID; 3266 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3267 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3268 (void)Failed; 3269 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3270 } 3271 } else { 3272 B << 1; 3273 const char *PrevSpec; 3274 unsigned DiagID; 3275 if (D.getMutableDeclSpec().SetStorageClassSpec( 3276 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3277 Context.getPrintingPolicy())) { 3278 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3279 "This is the only DeclSpec that should fail to be applied"); 3280 B << 1; 3281 } else { 3282 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3283 isInstField = false; 3284 } 3285 } 3286 } 3287 3288 NamedDecl *Member; 3289 if (isInstField) { 3290 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3291 3292 // Data members must have identifiers for names. 3293 if (!Name.isIdentifier()) { 3294 Diag(Loc, diag::err_bad_variable_name) 3295 << Name; 3296 return nullptr; 3297 } 3298 3299 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3300 3301 // Member field could not be with "template" keyword. 3302 // So TemplateParameterLists should be empty in this case. 3303 if (TemplateParameterLists.size()) { 3304 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3305 if (TemplateParams->size()) { 3306 // There is no such thing as a member field template. 3307 Diag(D.getIdentifierLoc(), diag::err_template_member) 3308 << II 3309 << SourceRange(TemplateParams->getTemplateLoc(), 3310 TemplateParams->getRAngleLoc()); 3311 } else { 3312 // There is an extraneous 'template<>' for this member. 3313 Diag(TemplateParams->getTemplateLoc(), 3314 diag::err_template_member_noparams) 3315 << II 3316 << SourceRange(TemplateParams->getTemplateLoc(), 3317 TemplateParams->getRAngleLoc()); 3318 } 3319 return nullptr; 3320 } 3321 3322 if (SS.isSet() && !SS.isInvalid()) { 3323 // The user provided a superfluous scope specifier inside a class 3324 // definition: 3325 // 3326 // class X { 3327 // int X::member; 3328 // }; 3329 if (DeclContext *DC = computeDeclContext(SS, false)) 3330 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3331 D.getName().getKind() == 3332 UnqualifiedIdKind::IK_TemplateId); 3333 else 3334 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3335 << Name << SS.getRange(); 3336 3337 SS.clear(); 3338 } 3339 3340 if (MSPropertyAttr) { 3341 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3342 BitWidth, InitStyle, AS, *MSPropertyAttr); 3343 if (!Member) 3344 return nullptr; 3345 isInstField = false; 3346 } else { 3347 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3348 BitWidth, InitStyle, AS); 3349 if (!Member) 3350 return nullptr; 3351 } 3352 3353 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3354 } else { 3355 Member = HandleDeclarator(S, D, TemplateParameterLists); 3356 if (!Member) 3357 return nullptr; 3358 3359 // Non-instance-fields can't have a bitfield. 3360 if (BitWidth) { 3361 if (Member->isInvalidDecl()) { 3362 // don't emit another diagnostic. 3363 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3364 // C++ 9.6p3: A bit-field shall not be a static member. 3365 // "static member 'A' cannot be a bit-field" 3366 Diag(Loc, diag::err_static_not_bitfield) 3367 << Name << BitWidth->getSourceRange(); 3368 } else if (isa<TypedefDecl>(Member)) { 3369 // "typedef member 'x' cannot be a bit-field" 3370 Diag(Loc, diag::err_typedef_not_bitfield) 3371 << Name << BitWidth->getSourceRange(); 3372 } else { 3373 // A function typedef ("typedef int f(); f a;"). 3374 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3375 Diag(Loc, diag::err_not_integral_type_bitfield) 3376 << Name << cast<ValueDecl>(Member)->getType() 3377 << BitWidth->getSourceRange(); 3378 } 3379 3380 BitWidth = nullptr; 3381 Member->setInvalidDecl(); 3382 } 3383 3384 NamedDecl *NonTemplateMember = Member; 3385 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3386 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3387 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3388 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3389 3390 Member->setAccess(AS); 3391 3392 // If we have declared a member function template or static data member 3393 // template, set the access of the templated declaration as well. 3394 if (NonTemplateMember != Member) 3395 NonTemplateMember->setAccess(AS); 3396 3397 // C++ [temp.deduct.guide]p3: 3398 // A deduction guide [...] for a member class template [shall be 3399 // declared] with the same access [as the template]. 3400 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3401 auto *TD = DG->getDeducedTemplate(); 3402 // Access specifiers are only meaningful if both the template and the 3403 // deduction guide are from the same scope. 3404 if (AS != TD->getAccess() && 3405 TD->getDeclContext()->getRedeclContext()->Equals( 3406 DG->getDeclContext()->getRedeclContext())) { 3407 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3408 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3409 << TD->getAccess(); 3410 const AccessSpecDecl *LastAccessSpec = nullptr; 3411 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3412 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3413 LastAccessSpec = AccessSpec; 3414 } 3415 assert(LastAccessSpec && "differing access with no access specifier"); 3416 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3417 << AS; 3418 } 3419 } 3420 } 3421 3422 if (VS.isOverrideSpecified()) 3423 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3424 AttributeCommonInfo::AS_Keyword)); 3425 if (VS.isFinalSpecified()) 3426 Member->addAttr(FinalAttr::Create( 3427 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3428 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3429 3430 if (VS.getLastLocation().isValid()) { 3431 // Update the end location of a method that has a virt-specifiers. 3432 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3433 MD->setRangeEnd(VS.getLastLocation()); 3434 } 3435 3436 CheckOverrideControl(Member); 3437 3438 assert((Name || isInstField) && "No identifier for non-field ?"); 3439 3440 if (isInstField) { 3441 FieldDecl *FD = cast<FieldDecl>(Member); 3442 FieldCollector->Add(FD); 3443 3444 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3445 // Remember all explicit private FieldDecls that have a name, no side 3446 // effects and are not part of a dependent type declaration. 3447 if (!FD->isImplicit() && FD->getDeclName() && 3448 FD->getAccess() == AS_private && 3449 !FD->hasAttr<UnusedAttr>() && 3450 !FD->getParent()->isDependentContext() && 3451 !InitializationHasSideEffects(*FD)) 3452 UnusedPrivateFields.insert(FD); 3453 } 3454 } 3455 3456 return Member; 3457 } 3458 3459 namespace { 3460 class UninitializedFieldVisitor 3461 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3462 Sema &S; 3463 // List of Decls to generate a warning on. Also remove Decls that become 3464 // initialized. 3465 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3466 // List of base classes of the record. Classes are removed after their 3467 // initializers. 3468 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3469 // Vector of decls to be removed from the Decl set prior to visiting the 3470 // nodes. These Decls may have been initialized in the prior initializer. 3471 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3472 // If non-null, add a note to the warning pointing back to the constructor. 3473 const CXXConstructorDecl *Constructor; 3474 // Variables to hold state when processing an initializer list. When 3475 // InitList is true, special case initialization of FieldDecls matching 3476 // InitListFieldDecl. 3477 bool InitList; 3478 FieldDecl *InitListFieldDecl; 3479 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3480 3481 public: 3482 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3483 UninitializedFieldVisitor(Sema &S, 3484 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3485 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3486 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3487 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3488 3489 // Returns true if the use of ME is not an uninitialized use. 3490 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3491 bool CheckReferenceOnly) { 3492 llvm::SmallVector<FieldDecl*, 4> Fields; 3493 bool ReferenceField = false; 3494 while (ME) { 3495 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3496 if (!FD) 3497 return false; 3498 Fields.push_back(FD); 3499 if (FD->getType()->isReferenceType()) 3500 ReferenceField = true; 3501 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3502 } 3503 3504 // Binding a reference to an uninitialized field is not an 3505 // uninitialized use. 3506 if (CheckReferenceOnly && !ReferenceField) 3507 return true; 3508 3509 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3510 // Discard the first field since it is the field decl that is being 3511 // initialized. 3512 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3513 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3514 } 3515 3516 for (auto UsedIter = UsedFieldIndex.begin(), 3517 UsedEnd = UsedFieldIndex.end(), 3518 OrigIter = InitFieldIndex.begin(), 3519 OrigEnd = InitFieldIndex.end(); 3520 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3521 if (*UsedIter < *OrigIter) 3522 return true; 3523 if (*UsedIter > *OrigIter) 3524 break; 3525 } 3526 3527 return false; 3528 } 3529 3530 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3531 bool AddressOf) { 3532 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3533 return; 3534 3535 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3536 // or union. 3537 MemberExpr *FieldME = ME; 3538 3539 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3540 3541 Expr *Base = ME; 3542 while (MemberExpr *SubME = 3543 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3544 3545 if (isa<VarDecl>(SubME->getMemberDecl())) 3546 return; 3547 3548 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3549 if (!FD->isAnonymousStructOrUnion()) 3550 FieldME = SubME; 3551 3552 if (!FieldME->getType().isPODType(S.Context)) 3553 AllPODFields = false; 3554 3555 Base = SubME->getBase(); 3556 } 3557 3558 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3559 return; 3560 3561 if (AddressOf && AllPODFields) 3562 return; 3563 3564 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3565 3566 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3567 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3568 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3569 } 3570 3571 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3572 QualType T = BaseCast->getType(); 3573 if (T->isPointerType() && 3574 BaseClasses.count(T->getPointeeType())) { 3575 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3576 << T->getPointeeType() << FoundVD; 3577 } 3578 } 3579 } 3580 3581 if (!Decls.count(FoundVD)) 3582 return; 3583 3584 const bool IsReference = FoundVD->getType()->isReferenceType(); 3585 3586 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3587 // Special checking for initializer lists. 3588 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3589 return; 3590 } 3591 } else { 3592 // Prevent double warnings on use of unbounded references. 3593 if (CheckReferenceOnly && !IsReference) 3594 return; 3595 } 3596 3597 unsigned diag = IsReference 3598 ? diag::warn_reference_field_is_uninit 3599 : diag::warn_field_is_uninit; 3600 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3601 if (Constructor) 3602 S.Diag(Constructor->getLocation(), 3603 diag::note_uninit_in_this_constructor) 3604 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3605 3606 } 3607 3608 void HandleValue(Expr *E, bool AddressOf) { 3609 E = E->IgnoreParens(); 3610 3611 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3612 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3613 AddressOf /*AddressOf*/); 3614 return; 3615 } 3616 3617 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3618 Visit(CO->getCond()); 3619 HandleValue(CO->getTrueExpr(), AddressOf); 3620 HandleValue(CO->getFalseExpr(), AddressOf); 3621 return; 3622 } 3623 3624 if (BinaryConditionalOperator *BCO = 3625 dyn_cast<BinaryConditionalOperator>(E)) { 3626 Visit(BCO->getCond()); 3627 HandleValue(BCO->getFalseExpr(), AddressOf); 3628 return; 3629 } 3630 3631 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3632 HandleValue(OVE->getSourceExpr(), AddressOf); 3633 return; 3634 } 3635 3636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3637 switch (BO->getOpcode()) { 3638 default: 3639 break; 3640 case(BO_PtrMemD): 3641 case(BO_PtrMemI): 3642 HandleValue(BO->getLHS(), AddressOf); 3643 Visit(BO->getRHS()); 3644 return; 3645 case(BO_Comma): 3646 Visit(BO->getLHS()); 3647 HandleValue(BO->getRHS(), AddressOf); 3648 return; 3649 } 3650 } 3651 3652 Visit(E); 3653 } 3654 3655 void CheckInitListExpr(InitListExpr *ILE) { 3656 InitFieldIndex.push_back(0); 3657 for (auto Child : ILE->children()) { 3658 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3659 CheckInitListExpr(SubList); 3660 } else { 3661 Visit(Child); 3662 } 3663 ++InitFieldIndex.back(); 3664 } 3665 InitFieldIndex.pop_back(); 3666 } 3667 3668 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3669 FieldDecl *Field, const Type *BaseClass) { 3670 // Remove Decls that may have been initialized in the previous 3671 // initializer. 3672 for (ValueDecl* VD : DeclsToRemove) 3673 Decls.erase(VD); 3674 DeclsToRemove.clear(); 3675 3676 Constructor = FieldConstructor; 3677 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3678 3679 if (ILE && Field) { 3680 InitList = true; 3681 InitListFieldDecl = Field; 3682 InitFieldIndex.clear(); 3683 CheckInitListExpr(ILE); 3684 } else { 3685 InitList = false; 3686 Visit(E); 3687 } 3688 3689 if (Field) 3690 Decls.erase(Field); 3691 if (BaseClass) 3692 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3693 } 3694 3695 void VisitMemberExpr(MemberExpr *ME) { 3696 // All uses of unbounded reference fields will warn. 3697 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3698 } 3699 3700 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3701 if (E->getCastKind() == CK_LValueToRValue) { 3702 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3703 return; 3704 } 3705 3706 Inherited::VisitImplicitCastExpr(E); 3707 } 3708 3709 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3710 if (E->getConstructor()->isCopyConstructor()) { 3711 Expr *ArgExpr = E->getArg(0); 3712 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3713 if (ILE->getNumInits() == 1) 3714 ArgExpr = ILE->getInit(0); 3715 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3716 if (ICE->getCastKind() == CK_NoOp) 3717 ArgExpr = ICE->getSubExpr(); 3718 HandleValue(ArgExpr, false /*AddressOf*/); 3719 return; 3720 } 3721 Inherited::VisitCXXConstructExpr(E); 3722 } 3723 3724 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3725 Expr *Callee = E->getCallee(); 3726 if (isa<MemberExpr>(Callee)) { 3727 HandleValue(Callee, false /*AddressOf*/); 3728 for (auto Arg : E->arguments()) 3729 Visit(Arg); 3730 return; 3731 } 3732 3733 Inherited::VisitCXXMemberCallExpr(E); 3734 } 3735 3736 void VisitCallExpr(CallExpr *E) { 3737 // Treat std::move as a use. 3738 if (E->isCallToStdMove()) { 3739 HandleValue(E->getArg(0), /*AddressOf=*/false); 3740 return; 3741 } 3742 3743 Inherited::VisitCallExpr(E); 3744 } 3745 3746 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3747 Expr *Callee = E->getCallee(); 3748 3749 if (isa<UnresolvedLookupExpr>(Callee)) 3750 return Inherited::VisitCXXOperatorCallExpr(E); 3751 3752 Visit(Callee); 3753 for (auto Arg : E->arguments()) 3754 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3755 } 3756 3757 void VisitBinaryOperator(BinaryOperator *E) { 3758 // If a field assignment is detected, remove the field from the 3759 // uninitiailized field set. 3760 if (E->getOpcode() == BO_Assign) 3761 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3762 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3763 if (!FD->getType()->isReferenceType()) 3764 DeclsToRemove.push_back(FD); 3765 3766 if (E->isCompoundAssignmentOp()) { 3767 HandleValue(E->getLHS(), false /*AddressOf*/); 3768 Visit(E->getRHS()); 3769 return; 3770 } 3771 3772 Inherited::VisitBinaryOperator(E); 3773 } 3774 3775 void VisitUnaryOperator(UnaryOperator *E) { 3776 if (E->isIncrementDecrementOp()) { 3777 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3778 return; 3779 } 3780 if (E->getOpcode() == UO_AddrOf) { 3781 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3782 HandleValue(ME->getBase(), true /*AddressOf*/); 3783 return; 3784 } 3785 } 3786 3787 Inherited::VisitUnaryOperator(E); 3788 } 3789 }; 3790 3791 // Diagnose value-uses of fields to initialize themselves, e.g. 3792 // foo(foo) 3793 // where foo is not also a parameter to the constructor. 3794 // Also diagnose across field uninitialized use such as 3795 // x(y), y(x) 3796 // TODO: implement -Wuninitialized and fold this into that framework. 3797 static void DiagnoseUninitializedFields( 3798 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3799 3800 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3801 Constructor->getLocation())) { 3802 return; 3803 } 3804 3805 if (Constructor->isInvalidDecl()) 3806 return; 3807 3808 const CXXRecordDecl *RD = Constructor->getParent(); 3809 3810 if (RD->isDependentContext()) 3811 return; 3812 3813 // Holds fields that are uninitialized. 3814 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3815 3816 // At the beginning, all fields are uninitialized. 3817 for (auto *I : RD->decls()) { 3818 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3819 UninitializedFields.insert(FD); 3820 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3821 UninitializedFields.insert(IFD->getAnonField()); 3822 } 3823 } 3824 3825 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3826 for (auto I : RD->bases()) 3827 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3828 3829 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3830 return; 3831 3832 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3833 UninitializedFields, 3834 UninitializedBaseClasses); 3835 3836 for (const auto *FieldInit : Constructor->inits()) { 3837 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3838 break; 3839 3840 Expr *InitExpr = FieldInit->getInit(); 3841 if (!InitExpr) 3842 continue; 3843 3844 if (CXXDefaultInitExpr *Default = 3845 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3846 InitExpr = Default->getExpr(); 3847 if (!InitExpr) 3848 continue; 3849 // In class initializers will point to the constructor. 3850 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3851 FieldInit->getAnyMember(), 3852 FieldInit->getBaseClass()); 3853 } else { 3854 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3855 FieldInit->getAnyMember(), 3856 FieldInit->getBaseClass()); 3857 } 3858 } 3859 } 3860 } // namespace 3861 3862 /// Enter a new C++ default initializer scope. After calling this, the 3863 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3864 /// parsing or instantiating the initializer failed. 3865 void Sema::ActOnStartCXXInClassMemberInitializer() { 3866 // Create a synthetic function scope to represent the call to the constructor 3867 // that notionally surrounds a use of this initializer. 3868 PushFunctionScope(); 3869 } 3870 3871 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3872 if (!D.isFunctionDeclarator()) 3873 return; 3874 auto &FTI = D.getFunctionTypeInfo(); 3875 if (!FTI.Params) 3876 return; 3877 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3878 FTI.NumParams)) { 3879 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3880 if (ParamDecl->getDeclName()) 3881 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3882 } 3883 } 3884 3885 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3886 if (ConstraintExpr.isInvalid()) 3887 return ExprError(); 3888 return CorrectDelayedTyposInExpr(ConstraintExpr); 3889 } 3890 3891 /// This is invoked after parsing an in-class initializer for a 3892 /// non-static C++ class member, and after instantiating an in-class initializer 3893 /// in a class template. Such actions are deferred until the class is complete. 3894 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3895 SourceLocation InitLoc, 3896 Expr *InitExpr) { 3897 // Pop the notional constructor scope we created earlier. 3898 PopFunctionScopeInfo(nullptr, D); 3899 3900 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3901 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3902 "must set init style when field is created"); 3903 3904 if (!InitExpr) { 3905 D->setInvalidDecl(); 3906 if (FD) 3907 FD->removeInClassInitializer(); 3908 return; 3909 } 3910 3911 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3912 FD->setInvalidDecl(); 3913 FD->removeInClassInitializer(); 3914 return; 3915 } 3916 3917 ExprResult Init = InitExpr; 3918 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3919 InitializedEntity Entity = 3920 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3921 InitializationKind Kind = 3922 FD->getInClassInitStyle() == ICIS_ListInit 3923 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3924 InitExpr->getBeginLoc(), 3925 InitExpr->getEndLoc()) 3926 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3927 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3928 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3929 if (Init.isInvalid()) { 3930 FD->setInvalidDecl(); 3931 return; 3932 } 3933 } 3934 3935 // C++11 [class.base.init]p7: 3936 // The initialization of each base and member constitutes a 3937 // full-expression. 3938 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3939 if (Init.isInvalid()) { 3940 FD->setInvalidDecl(); 3941 return; 3942 } 3943 3944 InitExpr = Init.get(); 3945 3946 FD->setInClassInitializer(InitExpr); 3947 } 3948 3949 /// Find the direct and/or virtual base specifiers that 3950 /// correspond to the given base type, for use in base initialization 3951 /// within a constructor. 3952 static bool FindBaseInitializer(Sema &SemaRef, 3953 CXXRecordDecl *ClassDecl, 3954 QualType BaseType, 3955 const CXXBaseSpecifier *&DirectBaseSpec, 3956 const CXXBaseSpecifier *&VirtualBaseSpec) { 3957 // First, check for a direct base class. 3958 DirectBaseSpec = nullptr; 3959 for (const auto &Base : ClassDecl->bases()) { 3960 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3961 // We found a direct base of this type. That's what we're 3962 // initializing. 3963 DirectBaseSpec = &Base; 3964 break; 3965 } 3966 } 3967 3968 // Check for a virtual base class. 3969 // FIXME: We might be able to short-circuit this if we know in advance that 3970 // there are no virtual bases. 3971 VirtualBaseSpec = nullptr; 3972 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3973 // We haven't found a base yet; search the class hierarchy for a 3974 // virtual base class. 3975 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3976 /*DetectVirtual=*/false); 3977 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3978 SemaRef.Context.getTypeDeclType(ClassDecl), 3979 BaseType, Paths)) { 3980 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3981 Path != Paths.end(); ++Path) { 3982 if (Path->back().Base->isVirtual()) { 3983 VirtualBaseSpec = Path->back().Base; 3984 break; 3985 } 3986 } 3987 } 3988 } 3989 3990 return DirectBaseSpec || VirtualBaseSpec; 3991 } 3992 3993 /// Handle a C++ member initializer using braced-init-list syntax. 3994 MemInitResult 3995 Sema::ActOnMemInitializer(Decl *ConstructorD, 3996 Scope *S, 3997 CXXScopeSpec &SS, 3998 IdentifierInfo *MemberOrBase, 3999 ParsedType TemplateTypeTy, 4000 const DeclSpec &DS, 4001 SourceLocation IdLoc, 4002 Expr *InitList, 4003 SourceLocation EllipsisLoc) { 4004 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4005 DS, IdLoc, InitList, 4006 EllipsisLoc); 4007 } 4008 4009 /// Handle a C++ member initializer using parentheses syntax. 4010 MemInitResult 4011 Sema::ActOnMemInitializer(Decl *ConstructorD, 4012 Scope *S, 4013 CXXScopeSpec &SS, 4014 IdentifierInfo *MemberOrBase, 4015 ParsedType TemplateTypeTy, 4016 const DeclSpec &DS, 4017 SourceLocation IdLoc, 4018 SourceLocation LParenLoc, 4019 ArrayRef<Expr *> Args, 4020 SourceLocation RParenLoc, 4021 SourceLocation EllipsisLoc) { 4022 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4023 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4024 DS, IdLoc, List, EllipsisLoc); 4025 } 4026 4027 namespace { 4028 4029 // Callback to only accept typo corrections that can be a valid C++ member 4030 // intializer: either a non-static field member or a base class. 4031 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4032 public: 4033 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4034 : ClassDecl(ClassDecl) {} 4035 4036 bool ValidateCandidate(const TypoCorrection &candidate) override { 4037 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4038 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4039 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4040 return isa<TypeDecl>(ND); 4041 } 4042 return false; 4043 } 4044 4045 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4046 return std::make_unique<MemInitializerValidatorCCC>(*this); 4047 } 4048 4049 private: 4050 CXXRecordDecl *ClassDecl; 4051 }; 4052 4053 } 4054 4055 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4056 CXXScopeSpec &SS, 4057 ParsedType TemplateTypeTy, 4058 IdentifierInfo *MemberOrBase) { 4059 if (SS.getScopeRep() || TemplateTypeTy) 4060 return nullptr; 4061 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4062 if (Result.empty()) 4063 return nullptr; 4064 ValueDecl *Member; 4065 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4066 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4067 return Member; 4068 return nullptr; 4069 } 4070 4071 /// Handle a C++ member initializer. 4072 MemInitResult 4073 Sema::BuildMemInitializer(Decl *ConstructorD, 4074 Scope *S, 4075 CXXScopeSpec &SS, 4076 IdentifierInfo *MemberOrBase, 4077 ParsedType TemplateTypeTy, 4078 const DeclSpec &DS, 4079 SourceLocation IdLoc, 4080 Expr *Init, 4081 SourceLocation EllipsisLoc) { 4082 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4083 if (!Res.isUsable()) 4084 return true; 4085 Init = Res.get(); 4086 4087 if (!ConstructorD) 4088 return true; 4089 4090 AdjustDeclIfTemplate(ConstructorD); 4091 4092 CXXConstructorDecl *Constructor 4093 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4094 if (!Constructor) { 4095 // The user wrote a constructor initializer on a function that is 4096 // not a C++ constructor. Ignore the error for now, because we may 4097 // have more member initializers coming; we'll diagnose it just 4098 // once in ActOnMemInitializers. 4099 return true; 4100 } 4101 4102 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4103 4104 // C++ [class.base.init]p2: 4105 // Names in a mem-initializer-id are looked up in the scope of the 4106 // constructor's class and, if not found in that scope, are looked 4107 // up in the scope containing the constructor's definition. 4108 // [Note: if the constructor's class contains a member with the 4109 // same name as a direct or virtual base class of the class, a 4110 // mem-initializer-id naming the member or base class and composed 4111 // of a single identifier refers to the class member. A 4112 // mem-initializer-id for the hidden base class may be specified 4113 // using a qualified name. ] 4114 4115 // Look for a member, first. 4116 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4117 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4118 if (EllipsisLoc.isValid()) 4119 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4120 << MemberOrBase 4121 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4122 4123 return BuildMemberInitializer(Member, Init, IdLoc); 4124 } 4125 // It didn't name a member, so see if it names a class. 4126 QualType BaseType; 4127 TypeSourceInfo *TInfo = nullptr; 4128 4129 if (TemplateTypeTy) { 4130 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4131 if (BaseType.isNull()) 4132 return true; 4133 } else if (DS.getTypeSpecType() == TST_decltype) { 4134 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4135 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4136 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4137 return true; 4138 } else { 4139 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4140 LookupParsedName(R, S, &SS); 4141 4142 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4143 if (!TyD) { 4144 if (R.isAmbiguous()) return true; 4145 4146 // We don't want access-control diagnostics here. 4147 R.suppressDiagnostics(); 4148 4149 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4150 bool NotUnknownSpecialization = false; 4151 DeclContext *DC = computeDeclContext(SS, false); 4152 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4153 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4154 4155 if (!NotUnknownSpecialization) { 4156 // When the scope specifier can refer to a member of an unknown 4157 // specialization, we take it as a type name. 4158 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4159 SS.getWithLocInContext(Context), 4160 *MemberOrBase, IdLoc); 4161 if (BaseType.isNull()) 4162 return true; 4163 4164 TInfo = Context.CreateTypeSourceInfo(BaseType); 4165 DependentNameTypeLoc TL = 4166 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4167 if (!TL.isNull()) { 4168 TL.setNameLoc(IdLoc); 4169 TL.setElaboratedKeywordLoc(SourceLocation()); 4170 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4171 } 4172 4173 R.clear(); 4174 R.setLookupName(MemberOrBase); 4175 } 4176 } 4177 4178 // If no results were found, try to correct typos. 4179 TypoCorrection Corr; 4180 MemInitializerValidatorCCC CCC(ClassDecl); 4181 if (R.empty() && BaseType.isNull() && 4182 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4183 CCC, CTK_ErrorRecovery, ClassDecl))) { 4184 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4185 // We have found a non-static data member with a similar 4186 // name to what was typed; complain and initialize that 4187 // member. 4188 diagnoseTypo(Corr, 4189 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4190 << MemberOrBase << true); 4191 return BuildMemberInitializer(Member, Init, IdLoc); 4192 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4193 const CXXBaseSpecifier *DirectBaseSpec; 4194 const CXXBaseSpecifier *VirtualBaseSpec; 4195 if (FindBaseInitializer(*this, ClassDecl, 4196 Context.getTypeDeclType(Type), 4197 DirectBaseSpec, VirtualBaseSpec)) { 4198 // We have found a direct or virtual base class with a 4199 // similar name to what was typed; complain and initialize 4200 // that base class. 4201 diagnoseTypo(Corr, 4202 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4203 << MemberOrBase << false, 4204 PDiag() /*Suppress note, we provide our own.*/); 4205 4206 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4207 : VirtualBaseSpec; 4208 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4209 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4210 4211 TyD = Type; 4212 } 4213 } 4214 } 4215 4216 if (!TyD && BaseType.isNull()) { 4217 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4218 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4219 return true; 4220 } 4221 } 4222 4223 if (BaseType.isNull()) { 4224 BaseType = Context.getTypeDeclType(TyD); 4225 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4226 if (SS.isSet()) { 4227 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4228 BaseType); 4229 TInfo = Context.CreateTypeSourceInfo(BaseType); 4230 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4231 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4232 TL.setElaboratedKeywordLoc(SourceLocation()); 4233 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4234 } 4235 } 4236 } 4237 4238 if (!TInfo) 4239 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4240 4241 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4242 } 4243 4244 MemInitResult 4245 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4246 SourceLocation IdLoc) { 4247 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4248 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4249 assert((DirectMember || IndirectMember) && 4250 "Member must be a FieldDecl or IndirectFieldDecl"); 4251 4252 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4253 return true; 4254 4255 if (Member->isInvalidDecl()) 4256 return true; 4257 4258 MultiExprArg Args; 4259 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4260 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4261 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4262 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4263 } else { 4264 // Template instantiation doesn't reconstruct ParenListExprs for us. 4265 Args = Init; 4266 } 4267 4268 SourceRange InitRange = Init->getSourceRange(); 4269 4270 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4271 // Can't check initialization for a member of dependent type or when 4272 // any of the arguments are type-dependent expressions. 4273 DiscardCleanupsInEvaluationContext(); 4274 } else { 4275 bool InitList = false; 4276 if (isa<InitListExpr>(Init)) { 4277 InitList = true; 4278 Args = Init; 4279 } 4280 4281 // Initialize the member. 4282 InitializedEntity MemberEntity = 4283 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4284 : InitializedEntity::InitializeMember(IndirectMember, 4285 nullptr); 4286 InitializationKind Kind = 4287 InitList ? InitializationKind::CreateDirectList( 4288 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4289 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4290 InitRange.getEnd()); 4291 4292 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4293 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4294 nullptr); 4295 if (MemberInit.isInvalid()) 4296 return true; 4297 4298 // C++11 [class.base.init]p7: 4299 // The initialization of each base and member constitutes a 4300 // full-expression. 4301 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4302 /*DiscardedValue*/ false); 4303 if (MemberInit.isInvalid()) 4304 return true; 4305 4306 Init = MemberInit.get(); 4307 } 4308 4309 if (DirectMember) { 4310 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4311 InitRange.getBegin(), Init, 4312 InitRange.getEnd()); 4313 } else { 4314 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4315 InitRange.getBegin(), Init, 4316 InitRange.getEnd()); 4317 } 4318 } 4319 4320 MemInitResult 4321 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4322 CXXRecordDecl *ClassDecl) { 4323 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4324 if (!LangOpts.CPlusPlus11) 4325 return Diag(NameLoc, diag::err_delegating_ctor) 4326 << TInfo->getTypeLoc().getLocalSourceRange(); 4327 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4328 4329 bool InitList = true; 4330 MultiExprArg Args = Init; 4331 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4332 InitList = false; 4333 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4334 } 4335 4336 SourceRange InitRange = Init->getSourceRange(); 4337 // Initialize the object. 4338 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4339 QualType(ClassDecl->getTypeForDecl(), 0)); 4340 InitializationKind Kind = 4341 InitList ? InitializationKind::CreateDirectList( 4342 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4343 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4344 InitRange.getEnd()); 4345 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4346 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4347 Args, nullptr); 4348 if (DelegationInit.isInvalid()) 4349 return true; 4350 4351 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4352 "Delegating constructor with no target?"); 4353 4354 // C++11 [class.base.init]p7: 4355 // The initialization of each base and member constitutes a 4356 // full-expression. 4357 DelegationInit = ActOnFinishFullExpr( 4358 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4359 if (DelegationInit.isInvalid()) 4360 return true; 4361 4362 // If we are in a dependent context, template instantiation will 4363 // perform this type-checking again. Just save the arguments that we 4364 // received in a ParenListExpr. 4365 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4366 // of the information that we have about the base 4367 // initializer. However, deconstructing the ASTs is a dicey process, 4368 // and this approach is far more likely to get the corner cases right. 4369 if (CurContext->isDependentContext()) 4370 DelegationInit = Init; 4371 4372 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4373 DelegationInit.getAs<Expr>(), 4374 InitRange.getEnd()); 4375 } 4376 4377 MemInitResult 4378 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4379 Expr *Init, CXXRecordDecl *ClassDecl, 4380 SourceLocation EllipsisLoc) { 4381 SourceLocation BaseLoc 4382 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4383 4384 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4385 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4386 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4387 4388 // C++ [class.base.init]p2: 4389 // [...] Unless the mem-initializer-id names a nonstatic data 4390 // member of the constructor's class or a direct or virtual base 4391 // of that class, the mem-initializer is ill-formed. A 4392 // mem-initializer-list can initialize a base class using any 4393 // name that denotes that base class type. 4394 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4395 4396 SourceRange InitRange = Init->getSourceRange(); 4397 if (EllipsisLoc.isValid()) { 4398 // This is a pack expansion. 4399 if (!BaseType->containsUnexpandedParameterPack()) { 4400 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4401 << SourceRange(BaseLoc, InitRange.getEnd()); 4402 4403 EllipsisLoc = SourceLocation(); 4404 } 4405 } else { 4406 // Check for any unexpanded parameter packs. 4407 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4408 return true; 4409 4410 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4411 return true; 4412 } 4413 4414 // Check for direct and virtual base classes. 4415 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4416 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4417 if (!Dependent) { 4418 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4419 BaseType)) 4420 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4421 4422 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4423 VirtualBaseSpec); 4424 4425 // C++ [base.class.init]p2: 4426 // Unless the mem-initializer-id names a nonstatic data member of the 4427 // constructor's class or a direct or virtual base of that class, the 4428 // mem-initializer is ill-formed. 4429 if (!DirectBaseSpec && !VirtualBaseSpec) { 4430 // If the class has any dependent bases, then it's possible that 4431 // one of those types will resolve to the same type as 4432 // BaseType. Therefore, just treat this as a dependent base 4433 // class initialization. FIXME: Should we try to check the 4434 // initialization anyway? It seems odd. 4435 if (ClassDecl->hasAnyDependentBases()) 4436 Dependent = true; 4437 else 4438 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4439 << BaseType << Context.getTypeDeclType(ClassDecl) 4440 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4441 } 4442 } 4443 4444 if (Dependent) { 4445 DiscardCleanupsInEvaluationContext(); 4446 4447 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4448 /*IsVirtual=*/false, 4449 InitRange.getBegin(), Init, 4450 InitRange.getEnd(), EllipsisLoc); 4451 } 4452 4453 // C++ [base.class.init]p2: 4454 // If a mem-initializer-id is ambiguous because it designates both 4455 // a direct non-virtual base class and an inherited virtual base 4456 // class, the mem-initializer is ill-formed. 4457 if (DirectBaseSpec && VirtualBaseSpec) 4458 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4459 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4460 4461 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4462 if (!BaseSpec) 4463 BaseSpec = VirtualBaseSpec; 4464 4465 // Initialize the base. 4466 bool InitList = true; 4467 MultiExprArg Args = Init; 4468 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4469 InitList = false; 4470 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4471 } 4472 4473 InitializedEntity BaseEntity = 4474 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4475 InitializationKind Kind = 4476 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4477 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4478 InitRange.getEnd()); 4479 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4480 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4481 if (BaseInit.isInvalid()) 4482 return true; 4483 4484 // C++11 [class.base.init]p7: 4485 // The initialization of each base and member constitutes a 4486 // full-expression. 4487 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4488 /*DiscardedValue*/ false); 4489 if (BaseInit.isInvalid()) 4490 return true; 4491 4492 // If we are in a dependent context, template instantiation will 4493 // perform this type-checking again. Just save the arguments that we 4494 // received in a ParenListExpr. 4495 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4496 // of the information that we have about the base 4497 // initializer. However, deconstructing the ASTs is a dicey process, 4498 // and this approach is far more likely to get the corner cases right. 4499 if (CurContext->isDependentContext()) 4500 BaseInit = Init; 4501 4502 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4503 BaseSpec->isVirtual(), 4504 InitRange.getBegin(), 4505 BaseInit.getAs<Expr>(), 4506 InitRange.getEnd(), EllipsisLoc); 4507 } 4508 4509 // Create a static_cast\<T&&>(expr). 4510 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4511 if (T.isNull()) T = E->getType(); 4512 QualType TargetType = SemaRef.BuildReferenceType( 4513 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4514 SourceLocation ExprLoc = E->getBeginLoc(); 4515 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4516 TargetType, ExprLoc); 4517 4518 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4519 SourceRange(ExprLoc, ExprLoc), 4520 E->getSourceRange()).get(); 4521 } 4522 4523 /// ImplicitInitializerKind - How an implicit base or member initializer should 4524 /// initialize its base or member. 4525 enum ImplicitInitializerKind { 4526 IIK_Default, 4527 IIK_Copy, 4528 IIK_Move, 4529 IIK_Inherit 4530 }; 4531 4532 static bool 4533 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4534 ImplicitInitializerKind ImplicitInitKind, 4535 CXXBaseSpecifier *BaseSpec, 4536 bool IsInheritedVirtualBase, 4537 CXXCtorInitializer *&CXXBaseInit) { 4538 InitializedEntity InitEntity 4539 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4540 IsInheritedVirtualBase); 4541 4542 ExprResult BaseInit; 4543 4544 switch (ImplicitInitKind) { 4545 case IIK_Inherit: 4546 case IIK_Default: { 4547 InitializationKind InitKind 4548 = InitializationKind::CreateDefault(Constructor->getLocation()); 4549 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4550 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4551 break; 4552 } 4553 4554 case IIK_Move: 4555 case IIK_Copy: { 4556 bool Moving = ImplicitInitKind == IIK_Move; 4557 ParmVarDecl *Param = Constructor->getParamDecl(0); 4558 QualType ParamType = Param->getType().getNonReferenceType(); 4559 4560 Expr *CopyCtorArg = 4561 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4562 SourceLocation(), Param, false, 4563 Constructor->getLocation(), ParamType, 4564 VK_LValue, nullptr); 4565 4566 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4567 4568 // Cast to the base class to avoid ambiguities. 4569 QualType ArgTy = 4570 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4571 ParamType.getQualifiers()); 4572 4573 if (Moving) { 4574 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4575 } 4576 4577 CXXCastPath BasePath; 4578 BasePath.push_back(BaseSpec); 4579 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4580 CK_UncheckedDerivedToBase, 4581 Moving ? VK_XValue : VK_LValue, 4582 &BasePath).get(); 4583 4584 InitializationKind InitKind 4585 = InitializationKind::CreateDirect(Constructor->getLocation(), 4586 SourceLocation(), SourceLocation()); 4587 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4588 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4589 break; 4590 } 4591 } 4592 4593 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4594 if (BaseInit.isInvalid()) 4595 return true; 4596 4597 CXXBaseInit = 4598 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4599 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4600 SourceLocation()), 4601 BaseSpec->isVirtual(), 4602 SourceLocation(), 4603 BaseInit.getAs<Expr>(), 4604 SourceLocation(), 4605 SourceLocation()); 4606 4607 return false; 4608 } 4609 4610 static bool RefersToRValueRef(Expr *MemRef) { 4611 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4612 return Referenced->getType()->isRValueReferenceType(); 4613 } 4614 4615 static bool 4616 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4617 ImplicitInitializerKind ImplicitInitKind, 4618 FieldDecl *Field, IndirectFieldDecl *Indirect, 4619 CXXCtorInitializer *&CXXMemberInit) { 4620 if (Field->isInvalidDecl()) 4621 return true; 4622 4623 SourceLocation Loc = Constructor->getLocation(); 4624 4625 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4626 bool Moving = ImplicitInitKind == IIK_Move; 4627 ParmVarDecl *Param = Constructor->getParamDecl(0); 4628 QualType ParamType = Param->getType().getNonReferenceType(); 4629 4630 // Suppress copying zero-width bitfields. 4631 if (Field->isZeroLengthBitField(SemaRef.Context)) 4632 return false; 4633 4634 Expr *MemberExprBase = 4635 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4636 SourceLocation(), Param, false, 4637 Loc, ParamType, VK_LValue, nullptr); 4638 4639 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4640 4641 if (Moving) { 4642 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4643 } 4644 4645 // Build a reference to this field within the parameter. 4646 CXXScopeSpec SS; 4647 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4648 Sema::LookupMemberName); 4649 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4650 : cast<ValueDecl>(Field), AS_public); 4651 MemberLookup.resolveKind(); 4652 ExprResult CtorArg 4653 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4654 ParamType, Loc, 4655 /*IsArrow=*/false, 4656 SS, 4657 /*TemplateKWLoc=*/SourceLocation(), 4658 /*FirstQualifierInScope=*/nullptr, 4659 MemberLookup, 4660 /*TemplateArgs=*/nullptr, 4661 /*S*/nullptr); 4662 if (CtorArg.isInvalid()) 4663 return true; 4664 4665 // C++11 [class.copy]p15: 4666 // - if a member m has rvalue reference type T&&, it is direct-initialized 4667 // with static_cast<T&&>(x.m); 4668 if (RefersToRValueRef(CtorArg.get())) { 4669 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4670 } 4671 4672 InitializedEntity Entity = 4673 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4674 /*Implicit*/ true) 4675 : InitializedEntity::InitializeMember(Field, nullptr, 4676 /*Implicit*/ true); 4677 4678 // Direct-initialize to use the copy constructor. 4679 InitializationKind InitKind = 4680 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4681 4682 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4683 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4684 ExprResult MemberInit = 4685 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4686 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4687 if (MemberInit.isInvalid()) 4688 return true; 4689 4690 if (Indirect) 4691 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4692 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4693 else 4694 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4695 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4696 return false; 4697 } 4698 4699 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4700 "Unhandled implicit init kind!"); 4701 4702 QualType FieldBaseElementType = 4703 SemaRef.Context.getBaseElementType(Field->getType()); 4704 4705 if (FieldBaseElementType->isRecordType()) { 4706 InitializedEntity InitEntity = 4707 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4708 /*Implicit*/ true) 4709 : InitializedEntity::InitializeMember(Field, nullptr, 4710 /*Implicit*/ true); 4711 InitializationKind InitKind = 4712 InitializationKind::CreateDefault(Loc); 4713 4714 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4715 ExprResult MemberInit = 4716 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4717 4718 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4719 if (MemberInit.isInvalid()) 4720 return true; 4721 4722 if (Indirect) 4723 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4724 Indirect, Loc, 4725 Loc, 4726 MemberInit.get(), 4727 Loc); 4728 else 4729 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4730 Field, Loc, Loc, 4731 MemberInit.get(), 4732 Loc); 4733 return false; 4734 } 4735 4736 if (!Field->getParent()->isUnion()) { 4737 if (FieldBaseElementType->isReferenceType()) { 4738 SemaRef.Diag(Constructor->getLocation(), 4739 diag::err_uninitialized_member_in_ctor) 4740 << (int)Constructor->isImplicit() 4741 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4742 << 0 << Field->getDeclName(); 4743 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4744 return true; 4745 } 4746 4747 if (FieldBaseElementType.isConstQualified()) { 4748 SemaRef.Diag(Constructor->getLocation(), 4749 diag::err_uninitialized_member_in_ctor) 4750 << (int)Constructor->isImplicit() 4751 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4752 << 1 << Field->getDeclName(); 4753 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4754 return true; 4755 } 4756 } 4757 4758 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4759 // ARC and Weak: 4760 // Default-initialize Objective-C pointers to NULL. 4761 CXXMemberInit 4762 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4763 Loc, Loc, 4764 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4765 Loc); 4766 return false; 4767 } 4768 4769 // Nothing to initialize. 4770 CXXMemberInit = nullptr; 4771 return false; 4772 } 4773 4774 namespace { 4775 struct BaseAndFieldInfo { 4776 Sema &S; 4777 CXXConstructorDecl *Ctor; 4778 bool AnyErrorsInInits; 4779 ImplicitInitializerKind IIK; 4780 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4781 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4782 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4783 4784 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4785 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4786 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4787 if (Ctor->getInheritedConstructor()) 4788 IIK = IIK_Inherit; 4789 else if (Generated && Ctor->isCopyConstructor()) 4790 IIK = IIK_Copy; 4791 else if (Generated && Ctor->isMoveConstructor()) 4792 IIK = IIK_Move; 4793 else 4794 IIK = IIK_Default; 4795 } 4796 4797 bool isImplicitCopyOrMove() const { 4798 switch (IIK) { 4799 case IIK_Copy: 4800 case IIK_Move: 4801 return true; 4802 4803 case IIK_Default: 4804 case IIK_Inherit: 4805 return false; 4806 } 4807 4808 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4809 } 4810 4811 bool addFieldInitializer(CXXCtorInitializer *Init) { 4812 AllToInit.push_back(Init); 4813 4814 // Check whether this initializer makes the field "used". 4815 if (Init->getInit()->HasSideEffects(S.Context)) 4816 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4817 4818 return false; 4819 } 4820 4821 bool isInactiveUnionMember(FieldDecl *Field) { 4822 RecordDecl *Record = Field->getParent(); 4823 if (!Record->isUnion()) 4824 return false; 4825 4826 if (FieldDecl *Active = 4827 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4828 return Active != Field->getCanonicalDecl(); 4829 4830 // In an implicit copy or move constructor, ignore any in-class initializer. 4831 if (isImplicitCopyOrMove()) 4832 return true; 4833 4834 // If there's no explicit initialization, the field is active only if it 4835 // has an in-class initializer... 4836 if (Field->hasInClassInitializer()) 4837 return false; 4838 // ... or it's an anonymous struct or union whose class has an in-class 4839 // initializer. 4840 if (!Field->isAnonymousStructOrUnion()) 4841 return true; 4842 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4843 return !FieldRD->hasInClassInitializer(); 4844 } 4845 4846 /// Determine whether the given field is, or is within, a union member 4847 /// that is inactive (because there was an initializer given for a different 4848 /// member of the union, or because the union was not initialized at all). 4849 bool isWithinInactiveUnionMember(FieldDecl *Field, 4850 IndirectFieldDecl *Indirect) { 4851 if (!Indirect) 4852 return isInactiveUnionMember(Field); 4853 4854 for (auto *C : Indirect->chain()) { 4855 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4856 if (Field && isInactiveUnionMember(Field)) 4857 return true; 4858 } 4859 return false; 4860 } 4861 }; 4862 } 4863 4864 /// Determine whether the given type is an incomplete or zero-lenfgth 4865 /// array type. 4866 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4867 if (T->isIncompleteArrayType()) 4868 return true; 4869 4870 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4871 if (!ArrayT->getSize()) 4872 return true; 4873 4874 T = ArrayT->getElementType(); 4875 } 4876 4877 return false; 4878 } 4879 4880 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4881 FieldDecl *Field, 4882 IndirectFieldDecl *Indirect = nullptr) { 4883 if (Field->isInvalidDecl()) 4884 return false; 4885 4886 // Overwhelmingly common case: we have a direct initializer for this field. 4887 if (CXXCtorInitializer *Init = 4888 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4889 return Info.addFieldInitializer(Init); 4890 4891 // C++11 [class.base.init]p8: 4892 // if the entity is a non-static data member that has a 4893 // brace-or-equal-initializer and either 4894 // -- the constructor's class is a union and no other variant member of that 4895 // union is designated by a mem-initializer-id or 4896 // -- the constructor's class is not a union, and, if the entity is a member 4897 // of an anonymous union, no other member of that union is designated by 4898 // a mem-initializer-id, 4899 // the entity is initialized as specified in [dcl.init]. 4900 // 4901 // We also apply the same rules to handle anonymous structs within anonymous 4902 // unions. 4903 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4904 return false; 4905 4906 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4907 ExprResult DIE = 4908 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4909 if (DIE.isInvalid()) 4910 return true; 4911 4912 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4913 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4914 4915 CXXCtorInitializer *Init; 4916 if (Indirect) 4917 Init = new (SemaRef.Context) 4918 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4919 SourceLocation(), DIE.get(), SourceLocation()); 4920 else 4921 Init = new (SemaRef.Context) 4922 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4923 SourceLocation(), DIE.get(), SourceLocation()); 4924 return Info.addFieldInitializer(Init); 4925 } 4926 4927 // Don't initialize incomplete or zero-length arrays. 4928 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4929 return false; 4930 4931 // Don't try to build an implicit initializer if there were semantic 4932 // errors in any of the initializers (and therefore we might be 4933 // missing some that the user actually wrote). 4934 if (Info.AnyErrorsInInits) 4935 return false; 4936 4937 CXXCtorInitializer *Init = nullptr; 4938 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4939 Indirect, Init)) 4940 return true; 4941 4942 if (!Init) 4943 return false; 4944 4945 return Info.addFieldInitializer(Init); 4946 } 4947 4948 bool 4949 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4950 CXXCtorInitializer *Initializer) { 4951 assert(Initializer->isDelegatingInitializer()); 4952 Constructor->setNumCtorInitializers(1); 4953 CXXCtorInitializer **initializer = 4954 new (Context) CXXCtorInitializer*[1]; 4955 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4956 Constructor->setCtorInitializers(initializer); 4957 4958 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4959 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4960 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4961 } 4962 4963 DelegatingCtorDecls.push_back(Constructor); 4964 4965 DiagnoseUninitializedFields(*this, Constructor); 4966 4967 return false; 4968 } 4969 4970 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4971 ArrayRef<CXXCtorInitializer *> Initializers) { 4972 if (Constructor->isDependentContext()) { 4973 // Just store the initializers as written, they will be checked during 4974 // instantiation. 4975 if (!Initializers.empty()) { 4976 Constructor->setNumCtorInitializers(Initializers.size()); 4977 CXXCtorInitializer **baseOrMemberInitializers = 4978 new (Context) CXXCtorInitializer*[Initializers.size()]; 4979 memcpy(baseOrMemberInitializers, Initializers.data(), 4980 Initializers.size() * sizeof(CXXCtorInitializer*)); 4981 Constructor->setCtorInitializers(baseOrMemberInitializers); 4982 } 4983 4984 // Let template instantiation know whether we had errors. 4985 if (AnyErrors) 4986 Constructor->setInvalidDecl(); 4987 4988 return false; 4989 } 4990 4991 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4992 4993 // We need to build the initializer AST according to order of construction 4994 // and not what user specified in the Initializers list. 4995 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4996 if (!ClassDecl) 4997 return true; 4998 4999 bool HadError = false; 5000 5001 for (unsigned i = 0; i < Initializers.size(); i++) { 5002 CXXCtorInitializer *Member = Initializers[i]; 5003 5004 if (Member->isBaseInitializer()) 5005 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5006 else { 5007 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5008 5009 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5010 for (auto *C : F->chain()) { 5011 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5012 if (FD && FD->getParent()->isUnion()) 5013 Info.ActiveUnionMember.insert(std::make_pair( 5014 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5015 } 5016 } else if (FieldDecl *FD = Member->getMember()) { 5017 if (FD->getParent()->isUnion()) 5018 Info.ActiveUnionMember.insert(std::make_pair( 5019 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5020 } 5021 } 5022 } 5023 5024 // Keep track of the direct virtual bases. 5025 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5026 for (auto &I : ClassDecl->bases()) { 5027 if (I.isVirtual()) 5028 DirectVBases.insert(&I); 5029 } 5030 5031 // Push virtual bases before others. 5032 for (auto &VBase : ClassDecl->vbases()) { 5033 if (CXXCtorInitializer *Value 5034 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5035 // [class.base.init]p7, per DR257: 5036 // A mem-initializer where the mem-initializer-id names a virtual base 5037 // class is ignored during execution of a constructor of any class that 5038 // is not the most derived class. 5039 if (ClassDecl->isAbstract()) { 5040 // FIXME: Provide a fixit to remove the base specifier. This requires 5041 // tracking the location of the associated comma for a base specifier. 5042 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5043 << VBase.getType() << ClassDecl; 5044 DiagnoseAbstractType(ClassDecl); 5045 } 5046 5047 Info.AllToInit.push_back(Value); 5048 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5049 // [class.base.init]p8, per DR257: 5050 // If a given [...] base class is not named by a mem-initializer-id 5051 // [...] and the entity is not a virtual base class of an abstract 5052 // class, then [...] the entity is default-initialized. 5053 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5054 CXXCtorInitializer *CXXBaseInit; 5055 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5056 &VBase, IsInheritedVirtualBase, 5057 CXXBaseInit)) { 5058 HadError = true; 5059 continue; 5060 } 5061 5062 Info.AllToInit.push_back(CXXBaseInit); 5063 } 5064 } 5065 5066 // Non-virtual bases. 5067 for (auto &Base : ClassDecl->bases()) { 5068 // Virtuals are in the virtual base list and already constructed. 5069 if (Base.isVirtual()) 5070 continue; 5071 5072 if (CXXCtorInitializer *Value 5073 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5074 Info.AllToInit.push_back(Value); 5075 } else if (!AnyErrors) { 5076 CXXCtorInitializer *CXXBaseInit; 5077 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5078 &Base, /*IsInheritedVirtualBase=*/false, 5079 CXXBaseInit)) { 5080 HadError = true; 5081 continue; 5082 } 5083 5084 Info.AllToInit.push_back(CXXBaseInit); 5085 } 5086 } 5087 5088 // Fields. 5089 for (auto *Mem : ClassDecl->decls()) { 5090 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5091 // C++ [class.bit]p2: 5092 // A declaration for a bit-field that omits the identifier declares an 5093 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5094 // initialized. 5095 if (F->isUnnamedBitfield()) 5096 continue; 5097 5098 // If we're not generating the implicit copy/move constructor, then we'll 5099 // handle anonymous struct/union fields based on their individual 5100 // indirect fields. 5101 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5102 continue; 5103 5104 if (CollectFieldInitializer(*this, Info, F)) 5105 HadError = true; 5106 continue; 5107 } 5108 5109 // Beyond this point, we only consider default initialization. 5110 if (Info.isImplicitCopyOrMove()) 5111 continue; 5112 5113 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5114 if (F->getType()->isIncompleteArrayType()) { 5115 assert(ClassDecl->hasFlexibleArrayMember() && 5116 "Incomplete array type is not valid"); 5117 continue; 5118 } 5119 5120 // Initialize each field of an anonymous struct individually. 5121 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5122 HadError = true; 5123 5124 continue; 5125 } 5126 } 5127 5128 unsigned NumInitializers = Info.AllToInit.size(); 5129 if (NumInitializers > 0) { 5130 Constructor->setNumCtorInitializers(NumInitializers); 5131 CXXCtorInitializer **baseOrMemberInitializers = 5132 new (Context) CXXCtorInitializer*[NumInitializers]; 5133 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5134 NumInitializers * sizeof(CXXCtorInitializer*)); 5135 Constructor->setCtorInitializers(baseOrMemberInitializers); 5136 5137 // Constructors implicitly reference the base and member 5138 // destructors. 5139 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5140 Constructor->getParent()); 5141 } 5142 5143 return HadError; 5144 } 5145 5146 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5147 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5148 const RecordDecl *RD = RT->getDecl(); 5149 if (RD->isAnonymousStructOrUnion()) { 5150 for (auto *Field : RD->fields()) 5151 PopulateKeysForFields(Field, IdealInits); 5152 return; 5153 } 5154 } 5155 IdealInits.push_back(Field->getCanonicalDecl()); 5156 } 5157 5158 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5159 return Context.getCanonicalType(BaseType).getTypePtr(); 5160 } 5161 5162 static const void *GetKeyForMember(ASTContext &Context, 5163 CXXCtorInitializer *Member) { 5164 if (!Member->isAnyMemberInitializer()) 5165 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5166 5167 return Member->getAnyMember()->getCanonicalDecl(); 5168 } 5169 5170 static void DiagnoseBaseOrMemInitializerOrder( 5171 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5172 ArrayRef<CXXCtorInitializer *> Inits) { 5173 if (Constructor->getDeclContext()->isDependentContext()) 5174 return; 5175 5176 // Don't check initializers order unless the warning is enabled at the 5177 // location of at least one initializer. 5178 bool ShouldCheckOrder = false; 5179 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5180 CXXCtorInitializer *Init = Inits[InitIndex]; 5181 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5182 Init->getSourceLocation())) { 5183 ShouldCheckOrder = true; 5184 break; 5185 } 5186 } 5187 if (!ShouldCheckOrder) 5188 return; 5189 5190 // Build the list of bases and members in the order that they'll 5191 // actually be initialized. The explicit initializers should be in 5192 // this same order but may be missing things. 5193 SmallVector<const void*, 32> IdealInitKeys; 5194 5195 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5196 5197 // 1. Virtual bases. 5198 for (const auto &VBase : ClassDecl->vbases()) 5199 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5200 5201 // 2. Non-virtual bases. 5202 for (const auto &Base : ClassDecl->bases()) { 5203 if (Base.isVirtual()) 5204 continue; 5205 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5206 } 5207 5208 // 3. Direct fields. 5209 for (auto *Field : ClassDecl->fields()) { 5210 if (Field->isUnnamedBitfield()) 5211 continue; 5212 5213 PopulateKeysForFields(Field, IdealInitKeys); 5214 } 5215 5216 unsigned NumIdealInits = IdealInitKeys.size(); 5217 unsigned IdealIndex = 0; 5218 5219 CXXCtorInitializer *PrevInit = nullptr; 5220 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5221 CXXCtorInitializer *Init = Inits[InitIndex]; 5222 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5223 5224 // Scan forward to try to find this initializer in the idealized 5225 // initializers list. 5226 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5227 if (InitKey == IdealInitKeys[IdealIndex]) 5228 break; 5229 5230 // If we didn't find this initializer, it must be because we 5231 // scanned past it on a previous iteration. That can only 5232 // happen if we're out of order; emit a warning. 5233 if (IdealIndex == NumIdealInits && PrevInit) { 5234 Sema::SemaDiagnosticBuilder D = 5235 SemaRef.Diag(PrevInit->getSourceLocation(), 5236 diag::warn_initializer_out_of_order); 5237 5238 if (PrevInit->isAnyMemberInitializer()) 5239 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5240 else 5241 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5242 5243 if (Init->isAnyMemberInitializer()) 5244 D << 0 << Init->getAnyMember()->getDeclName(); 5245 else 5246 D << 1 << Init->getTypeSourceInfo()->getType(); 5247 5248 // Move back to the initializer's location in the ideal list. 5249 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5250 if (InitKey == IdealInitKeys[IdealIndex]) 5251 break; 5252 5253 assert(IdealIndex < NumIdealInits && 5254 "initializer not found in initializer list"); 5255 } 5256 5257 PrevInit = Init; 5258 } 5259 } 5260 5261 namespace { 5262 bool CheckRedundantInit(Sema &S, 5263 CXXCtorInitializer *Init, 5264 CXXCtorInitializer *&PrevInit) { 5265 if (!PrevInit) { 5266 PrevInit = Init; 5267 return false; 5268 } 5269 5270 if (FieldDecl *Field = Init->getAnyMember()) 5271 S.Diag(Init->getSourceLocation(), 5272 diag::err_multiple_mem_initialization) 5273 << Field->getDeclName() 5274 << Init->getSourceRange(); 5275 else { 5276 const Type *BaseClass = Init->getBaseClass(); 5277 assert(BaseClass && "neither field nor base"); 5278 S.Diag(Init->getSourceLocation(), 5279 diag::err_multiple_base_initialization) 5280 << QualType(BaseClass, 0) 5281 << Init->getSourceRange(); 5282 } 5283 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5284 << 0 << PrevInit->getSourceRange(); 5285 5286 return true; 5287 } 5288 5289 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5290 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5291 5292 bool CheckRedundantUnionInit(Sema &S, 5293 CXXCtorInitializer *Init, 5294 RedundantUnionMap &Unions) { 5295 FieldDecl *Field = Init->getAnyMember(); 5296 RecordDecl *Parent = Field->getParent(); 5297 NamedDecl *Child = Field; 5298 5299 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5300 if (Parent->isUnion()) { 5301 UnionEntry &En = Unions[Parent]; 5302 if (En.first && En.first != Child) { 5303 S.Diag(Init->getSourceLocation(), 5304 diag::err_multiple_mem_union_initialization) 5305 << Field->getDeclName() 5306 << Init->getSourceRange(); 5307 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5308 << 0 << En.second->getSourceRange(); 5309 return true; 5310 } 5311 if (!En.first) { 5312 En.first = Child; 5313 En.second = Init; 5314 } 5315 if (!Parent->isAnonymousStructOrUnion()) 5316 return false; 5317 } 5318 5319 Child = Parent; 5320 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5321 } 5322 5323 return false; 5324 } 5325 } 5326 5327 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5328 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5329 SourceLocation ColonLoc, 5330 ArrayRef<CXXCtorInitializer*> MemInits, 5331 bool AnyErrors) { 5332 if (!ConstructorDecl) 5333 return; 5334 5335 AdjustDeclIfTemplate(ConstructorDecl); 5336 5337 CXXConstructorDecl *Constructor 5338 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5339 5340 if (!Constructor) { 5341 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5342 return; 5343 } 5344 5345 // Mapping for the duplicate initializers check. 5346 // For member initializers, this is keyed with a FieldDecl*. 5347 // For base initializers, this is keyed with a Type*. 5348 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5349 5350 // Mapping for the inconsistent anonymous-union initializers check. 5351 RedundantUnionMap MemberUnions; 5352 5353 bool HadError = false; 5354 for (unsigned i = 0; i < MemInits.size(); i++) { 5355 CXXCtorInitializer *Init = MemInits[i]; 5356 5357 // Set the source order index. 5358 Init->setSourceOrder(i); 5359 5360 if (Init->isAnyMemberInitializer()) { 5361 const void *Key = GetKeyForMember(Context, Init); 5362 if (CheckRedundantInit(*this, Init, Members[Key]) || 5363 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5364 HadError = true; 5365 } else if (Init->isBaseInitializer()) { 5366 const void *Key = GetKeyForMember(Context, Init); 5367 if (CheckRedundantInit(*this, Init, Members[Key])) 5368 HadError = true; 5369 } else { 5370 assert(Init->isDelegatingInitializer()); 5371 // This must be the only initializer 5372 if (MemInits.size() != 1) { 5373 Diag(Init->getSourceLocation(), 5374 diag::err_delegating_initializer_alone) 5375 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5376 // We will treat this as being the only initializer. 5377 } 5378 SetDelegatingInitializer(Constructor, MemInits[i]); 5379 // Return immediately as the initializer is set. 5380 return; 5381 } 5382 } 5383 5384 if (HadError) 5385 return; 5386 5387 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5388 5389 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5390 5391 DiagnoseUninitializedFields(*this, Constructor); 5392 } 5393 5394 void 5395 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5396 CXXRecordDecl *ClassDecl) { 5397 // Ignore dependent contexts. Also ignore unions, since their members never 5398 // have destructors implicitly called. 5399 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5400 return; 5401 5402 // FIXME: all the access-control diagnostics are positioned on the 5403 // field/base declaration. That's probably good; that said, the 5404 // user might reasonably want to know why the destructor is being 5405 // emitted, and we currently don't say. 5406 5407 // Non-static data members. 5408 for (auto *Field : ClassDecl->fields()) { 5409 if (Field->isInvalidDecl()) 5410 continue; 5411 5412 // Don't destroy incomplete or zero-length arrays. 5413 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5414 continue; 5415 5416 QualType FieldType = Context.getBaseElementType(Field->getType()); 5417 5418 const RecordType* RT = FieldType->getAs<RecordType>(); 5419 if (!RT) 5420 continue; 5421 5422 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5423 if (FieldClassDecl->isInvalidDecl()) 5424 continue; 5425 if (FieldClassDecl->hasIrrelevantDestructor()) 5426 continue; 5427 // The destructor for an implicit anonymous union member is never invoked. 5428 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5429 continue; 5430 5431 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5432 assert(Dtor && "No dtor found for FieldClassDecl!"); 5433 CheckDestructorAccess(Field->getLocation(), Dtor, 5434 PDiag(diag::err_access_dtor_field) 5435 << Field->getDeclName() 5436 << FieldType); 5437 5438 MarkFunctionReferenced(Location, Dtor); 5439 DiagnoseUseOfDecl(Dtor, Location); 5440 } 5441 5442 // We only potentially invoke the destructors of potentially constructed 5443 // subobjects. 5444 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5445 5446 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5447 5448 // Bases. 5449 for (const auto &Base : ClassDecl->bases()) { 5450 // Bases are always records in a well-formed non-dependent class. 5451 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5452 5453 // Remember direct virtual bases. 5454 if (Base.isVirtual()) { 5455 if (!VisitVirtualBases) 5456 continue; 5457 DirectVirtualBases.insert(RT); 5458 } 5459 5460 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5461 // If our base class is invalid, we probably can't get its dtor anyway. 5462 if (BaseClassDecl->isInvalidDecl()) 5463 continue; 5464 if (BaseClassDecl->hasIrrelevantDestructor()) 5465 continue; 5466 5467 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5468 assert(Dtor && "No dtor found for BaseClassDecl!"); 5469 5470 // FIXME: caret should be on the start of the class name 5471 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5472 PDiag(diag::err_access_dtor_base) 5473 << Base.getType() << Base.getSourceRange(), 5474 Context.getTypeDeclType(ClassDecl)); 5475 5476 MarkFunctionReferenced(Location, Dtor); 5477 DiagnoseUseOfDecl(Dtor, Location); 5478 } 5479 5480 if (!VisitVirtualBases) 5481 return; 5482 5483 // Virtual bases. 5484 for (const auto &VBase : ClassDecl->vbases()) { 5485 // Bases are always records in a well-formed non-dependent class. 5486 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5487 5488 // Ignore direct virtual bases. 5489 if (DirectVirtualBases.count(RT)) 5490 continue; 5491 5492 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5493 // If our base class is invalid, we probably can't get its dtor anyway. 5494 if (BaseClassDecl->isInvalidDecl()) 5495 continue; 5496 if (BaseClassDecl->hasIrrelevantDestructor()) 5497 continue; 5498 5499 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5500 assert(Dtor && "No dtor found for BaseClassDecl!"); 5501 if (CheckDestructorAccess( 5502 ClassDecl->getLocation(), Dtor, 5503 PDiag(diag::err_access_dtor_vbase) 5504 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5505 Context.getTypeDeclType(ClassDecl)) == 5506 AR_accessible) { 5507 CheckDerivedToBaseConversion( 5508 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5509 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5510 SourceRange(), DeclarationName(), nullptr); 5511 } 5512 5513 MarkFunctionReferenced(Location, Dtor); 5514 DiagnoseUseOfDecl(Dtor, Location); 5515 } 5516 } 5517 5518 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5519 if (!CDtorDecl) 5520 return; 5521 5522 if (CXXConstructorDecl *Constructor 5523 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5524 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5525 DiagnoseUninitializedFields(*this, Constructor); 5526 } 5527 } 5528 5529 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5530 if (!getLangOpts().CPlusPlus) 5531 return false; 5532 5533 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5534 if (!RD) 5535 return false; 5536 5537 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5538 // class template specialization here, but doing so breaks a lot of code. 5539 5540 // We can't answer whether something is abstract until it has a 5541 // definition. If it's currently being defined, we'll walk back 5542 // over all the declarations when we have a full definition. 5543 const CXXRecordDecl *Def = RD->getDefinition(); 5544 if (!Def || Def->isBeingDefined()) 5545 return false; 5546 5547 return RD->isAbstract(); 5548 } 5549 5550 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5551 TypeDiagnoser &Diagnoser) { 5552 if (!isAbstractType(Loc, T)) 5553 return false; 5554 5555 T = Context.getBaseElementType(T); 5556 Diagnoser.diagnose(*this, Loc, T); 5557 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5558 return true; 5559 } 5560 5561 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5562 // Check if we've already emitted the list of pure virtual functions 5563 // for this class. 5564 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5565 return; 5566 5567 // If the diagnostic is suppressed, don't emit the notes. We're only 5568 // going to emit them once, so try to attach them to a diagnostic we're 5569 // actually going to show. 5570 if (Diags.isLastDiagnosticIgnored()) 5571 return; 5572 5573 CXXFinalOverriderMap FinalOverriders; 5574 RD->getFinalOverriders(FinalOverriders); 5575 5576 // Keep a set of seen pure methods so we won't diagnose the same method 5577 // more than once. 5578 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5579 5580 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5581 MEnd = FinalOverriders.end(); 5582 M != MEnd; 5583 ++M) { 5584 for (OverridingMethods::iterator SO = M->second.begin(), 5585 SOEnd = M->second.end(); 5586 SO != SOEnd; ++SO) { 5587 // C++ [class.abstract]p4: 5588 // A class is abstract if it contains or inherits at least one 5589 // pure virtual function for which the final overrider is pure 5590 // virtual. 5591 5592 // 5593 if (SO->second.size() != 1) 5594 continue; 5595 5596 if (!SO->second.front().Method->isPure()) 5597 continue; 5598 5599 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5600 continue; 5601 5602 Diag(SO->second.front().Method->getLocation(), 5603 diag::note_pure_virtual_function) 5604 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5605 } 5606 } 5607 5608 if (!PureVirtualClassDiagSet) 5609 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5610 PureVirtualClassDiagSet->insert(RD); 5611 } 5612 5613 namespace { 5614 struct AbstractUsageInfo { 5615 Sema &S; 5616 CXXRecordDecl *Record; 5617 CanQualType AbstractType; 5618 bool Invalid; 5619 5620 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5621 : S(S), Record(Record), 5622 AbstractType(S.Context.getCanonicalType( 5623 S.Context.getTypeDeclType(Record))), 5624 Invalid(false) {} 5625 5626 void DiagnoseAbstractType() { 5627 if (Invalid) return; 5628 S.DiagnoseAbstractType(Record); 5629 Invalid = true; 5630 } 5631 5632 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5633 }; 5634 5635 struct CheckAbstractUsage { 5636 AbstractUsageInfo &Info; 5637 const NamedDecl *Ctx; 5638 5639 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5640 : Info(Info), Ctx(Ctx) {} 5641 5642 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5643 switch (TL.getTypeLocClass()) { 5644 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5645 #define TYPELOC(CLASS, PARENT) \ 5646 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5647 #include "clang/AST/TypeLocNodes.def" 5648 } 5649 } 5650 5651 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5652 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5653 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5654 if (!TL.getParam(I)) 5655 continue; 5656 5657 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5658 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5659 } 5660 } 5661 5662 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5663 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5664 } 5665 5666 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5667 // Visit the type parameters from a permissive context. 5668 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5669 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5670 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5671 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5672 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5673 // TODO: other template argument types? 5674 } 5675 } 5676 5677 // Visit pointee types from a permissive context. 5678 #define CheckPolymorphic(Type) \ 5679 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5680 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5681 } 5682 CheckPolymorphic(PointerTypeLoc) 5683 CheckPolymorphic(ReferenceTypeLoc) 5684 CheckPolymorphic(MemberPointerTypeLoc) 5685 CheckPolymorphic(BlockPointerTypeLoc) 5686 CheckPolymorphic(AtomicTypeLoc) 5687 5688 /// Handle all the types we haven't given a more specific 5689 /// implementation for above. 5690 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5691 // Every other kind of type that we haven't called out already 5692 // that has an inner type is either (1) sugar or (2) contains that 5693 // inner type in some way as a subobject. 5694 if (TypeLoc Next = TL.getNextTypeLoc()) 5695 return Visit(Next, Sel); 5696 5697 // If there's no inner type and we're in a permissive context, 5698 // don't diagnose. 5699 if (Sel == Sema::AbstractNone) return; 5700 5701 // Check whether the type matches the abstract type. 5702 QualType T = TL.getType(); 5703 if (T->isArrayType()) { 5704 Sel = Sema::AbstractArrayType; 5705 T = Info.S.Context.getBaseElementType(T); 5706 } 5707 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5708 if (CT != Info.AbstractType) return; 5709 5710 // It matched; do some magic. 5711 if (Sel == Sema::AbstractArrayType) { 5712 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5713 << T << TL.getSourceRange(); 5714 } else { 5715 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5716 << Sel << T << TL.getSourceRange(); 5717 } 5718 Info.DiagnoseAbstractType(); 5719 } 5720 }; 5721 5722 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5723 Sema::AbstractDiagSelID Sel) { 5724 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5725 } 5726 5727 } 5728 5729 /// Check for invalid uses of an abstract type in a method declaration. 5730 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5731 CXXMethodDecl *MD) { 5732 // No need to do the check on definitions, which require that 5733 // the return/param types be complete. 5734 if (MD->doesThisDeclarationHaveABody()) 5735 return; 5736 5737 // For safety's sake, just ignore it if we don't have type source 5738 // information. This should never happen for non-implicit methods, 5739 // but... 5740 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5741 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5742 } 5743 5744 /// Check for invalid uses of an abstract type within a class definition. 5745 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5746 CXXRecordDecl *RD) { 5747 for (auto *D : RD->decls()) { 5748 if (D->isImplicit()) continue; 5749 5750 // Methods and method templates. 5751 if (isa<CXXMethodDecl>(D)) { 5752 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5753 } else if (isa<FunctionTemplateDecl>(D)) { 5754 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5755 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5756 5757 // Fields and static variables. 5758 } else if (isa<FieldDecl>(D)) { 5759 FieldDecl *FD = cast<FieldDecl>(D); 5760 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5761 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5762 } else if (isa<VarDecl>(D)) { 5763 VarDecl *VD = cast<VarDecl>(D); 5764 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5765 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5766 5767 // Nested classes and class templates. 5768 } else if (isa<CXXRecordDecl>(D)) { 5769 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5770 } else if (isa<ClassTemplateDecl>(D)) { 5771 CheckAbstractClassUsage(Info, 5772 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5773 } 5774 } 5775 } 5776 5777 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5778 Attr *ClassAttr = getDLLAttr(Class); 5779 if (!ClassAttr) 5780 return; 5781 5782 assert(ClassAttr->getKind() == attr::DLLExport); 5783 5784 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5785 5786 if (TSK == TSK_ExplicitInstantiationDeclaration) 5787 // Don't go any further if this is just an explicit instantiation 5788 // declaration. 5789 return; 5790 5791 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5792 S.MarkVTableUsed(Class->getLocation(), Class, true); 5793 5794 for (Decl *Member : Class->decls()) { 5795 // Defined static variables that are members of an exported base 5796 // class must be marked export too. 5797 auto *VD = dyn_cast<VarDecl>(Member); 5798 if (VD && Member->getAttr<DLLExportAttr>() && 5799 VD->getStorageClass() == SC_Static && 5800 TSK == TSK_ImplicitInstantiation) 5801 S.MarkVariableReferenced(VD->getLocation(), VD); 5802 5803 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5804 if (!MD) 5805 continue; 5806 5807 if (Member->getAttr<DLLExportAttr>()) { 5808 if (MD->isUserProvided()) { 5809 // Instantiate non-default class member functions ... 5810 5811 // .. except for certain kinds of template specializations. 5812 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5813 continue; 5814 5815 S.MarkFunctionReferenced(Class->getLocation(), MD); 5816 5817 // The function will be passed to the consumer when its definition is 5818 // encountered. 5819 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5820 MD->isCopyAssignmentOperator() || 5821 MD->isMoveAssignmentOperator()) { 5822 // Synthesize and instantiate non-trivial implicit methods, explicitly 5823 // defaulted methods, and the copy and move assignment operators. The 5824 // latter are exported even if they are trivial, because the address of 5825 // an operator can be taken and should compare equal across libraries. 5826 DiagnosticErrorTrap Trap(S.Diags); 5827 S.MarkFunctionReferenced(Class->getLocation(), MD); 5828 if (Trap.hasErrorOccurred()) { 5829 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5830 << Class << !S.getLangOpts().CPlusPlus11; 5831 break; 5832 } 5833 5834 // There is no later point when we will see the definition of this 5835 // function, so pass it to the consumer now. 5836 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5837 } 5838 } 5839 } 5840 } 5841 5842 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5843 CXXRecordDecl *Class) { 5844 // Only the MS ABI has default constructor closures, so we don't need to do 5845 // this semantic checking anywhere else. 5846 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5847 return; 5848 5849 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5850 for (Decl *Member : Class->decls()) { 5851 // Look for exported default constructors. 5852 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5853 if (!CD || !CD->isDefaultConstructor()) 5854 continue; 5855 auto *Attr = CD->getAttr<DLLExportAttr>(); 5856 if (!Attr) 5857 continue; 5858 5859 // If the class is non-dependent, mark the default arguments as ODR-used so 5860 // that we can properly codegen the constructor closure. 5861 if (!Class->isDependentContext()) { 5862 for (ParmVarDecl *PD : CD->parameters()) { 5863 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5864 S.DiscardCleanupsInEvaluationContext(); 5865 } 5866 } 5867 5868 if (LastExportedDefaultCtor) { 5869 S.Diag(LastExportedDefaultCtor->getLocation(), 5870 diag::err_attribute_dll_ambiguous_default_ctor) 5871 << Class; 5872 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5873 << CD->getDeclName(); 5874 return; 5875 } 5876 LastExportedDefaultCtor = CD; 5877 } 5878 } 5879 5880 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5881 // Mark any compiler-generated routines with the implicit code_seg attribute. 5882 for (auto *Method : Class->methods()) { 5883 if (Method->isUserProvided()) 5884 continue; 5885 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5886 Method->addAttr(A); 5887 } 5888 } 5889 5890 /// Check class-level dllimport/dllexport attribute. 5891 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5892 Attr *ClassAttr = getDLLAttr(Class); 5893 5894 // MSVC inherits DLL attributes to partial class template specializations. 5895 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5896 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5897 if (Attr *TemplateAttr = 5898 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5899 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5900 A->setInherited(true); 5901 ClassAttr = A; 5902 } 5903 } 5904 } 5905 5906 if (!ClassAttr) 5907 return; 5908 5909 if (!Class->isExternallyVisible()) { 5910 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5911 << Class << ClassAttr; 5912 return; 5913 } 5914 5915 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5916 !ClassAttr->isInherited()) { 5917 // Diagnose dll attributes on members of class with dll attribute. 5918 for (Decl *Member : Class->decls()) { 5919 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5920 continue; 5921 InheritableAttr *MemberAttr = getDLLAttr(Member); 5922 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5923 continue; 5924 5925 Diag(MemberAttr->getLocation(), 5926 diag::err_attribute_dll_member_of_dll_class) 5927 << MemberAttr << ClassAttr; 5928 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5929 Member->setInvalidDecl(); 5930 } 5931 } 5932 5933 if (Class->getDescribedClassTemplate()) 5934 // Don't inherit dll attribute until the template is instantiated. 5935 return; 5936 5937 // The class is either imported or exported. 5938 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5939 5940 // Check if this was a dllimport attribute propagated from a derived class to 5941 // a base class template specialization. We don't apply these attributes to 5942 // static data members. 5943 const bool PropagatedImport = 5944 !ClassExported && 5945 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5946 5947 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5948 5949 // Ignore explicit dllexport on explicit class template instantiation 5950 // declarations, except in MinGW mode. 5951 if (ClassExported && !ClassAttr->isInherited() && 5952 TSK == TSK_ExplicitInstantiationDeclaration && 5953 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 5954 Class->dropAttr<DLLExportAttr>(); 5955 return; 5956 } 5957 5958 // Force declaration of implicit members so they can inherit the attribute. 5959 ForceDeclarationOfImplicitMembers(Class); 5960 5961 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5962 // seem to be true in practice? 5963 5964 for (Decl *Member : Class->decls()) { 5965 VarDecl *VD = dyn_cast<VarDecl>(Member); 5966 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5967 5968 // Only methods and static fields inherit the attributes. 5969 if (!VD && !MD) 5970 continue; 5971 5972 if (MD) { 5973 // Don't process deleted methods. 5974 if (MD->isDeleted()) 5975 continue; 5976 5977 if (MD->isInlined()) { 5978 // MinGW does not import or export inline methods. But do it for 5979 // template instantiations. 5980 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5981 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 5982 TSK != TSK_ExplicitInstantiationDeclaration && 5983 TSK != TSK_ExplicitInstantiationDefinition) 5984 continue; 5985 5986 // MSVC versions before 2015 don't export the move assignment operators 5987 // and move constructor, so don't attempt to import/export them if 5988 // we have a definition. 5989 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5990 if ((MD->isMoveAssignmentOperator() || 5991 (Ctor && Ctor->isMoveConstructor())) && 5992 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5993 continue; 5994 5995 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5996 // operator is exported anyway. 5997 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5998 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5999 continue; 6000 } 6001 } 6002 6003 // Don't apply dllimport attributes to static data members of class template 6004 // instantiations when the attribute is propagated from a derived class. 6005 if (VD && PropagatedImport) 6006 continue; 6007 6008 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6009 continue; 6010 6011 if (!getDLLAttr(Member)) { 6012 InheritableAttr *NewAttr = nullptr; 6013 6014 // Do not export/import inline function when -fno-dllexport-inlines is 6015 // passed. But add attribute for later local static var check. 6016 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6017 TSK != TSK_ExplicitInstantiationDeclaration && 6018 TSK != TSK_ExplicitInstantiationDefinition) { 6019 if (ClassExported) { 6020 NewAttr = ::new (getASTContext()) 6021 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6022 } else { 6023 NewAttr = ::new (getASTContext()) 6024 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6025 } 6026 } else { 6027 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6028 } 6029 6030 NewAttr->setInherited(true); 6031 Member->addAttr(NewAttr); 6032 6033 if (MD) { 6034 // Propagate DLLAttr to friend re-declarations of MD that have already 6035 // been constructed. 6036 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6037 FD = FD->getPreviousDecl()) { 6038 if (FD->getFriendObjectKind() == Decl::FOK_None) 6039 continue; 6040 assert(!getDLLAttr(FD) && 6041 "friend re-decl should not already have a DLLAttr"); 6042 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6043 NewAttr->setInherited(true); 6044 FD->addAttr(NewAttr); 6045 } 6046 } 6047 } 6048 } 6049 6050 if (ClassExported) 6051 DelayedDllExportClasses.push_back(Class); 6052 } 6053 6054 /// Perform propagation of DLL attributes from a derived class to a 6055 /// templated base class for MS compatibility. 6056 void Sema::propagateDLLAttrToBaseClassTemplate( 6057 CXXRecordDecl *Class, Attr *ClassAttr, 6058 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6059 if (getDLLAttr( 6060 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6061 // If the base class template has a DLL attribute, don't try to change it. 6062 return; 6063 } 6064 6065 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6066 if (!getDLLAttr(BaseTemplateSpec) && 6067 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6068 TSK == TSK_ImplicitInstantiation)) { 6069 // The template hasn't been instantiated yet (or it has, but only as an 6070 // explicit instantiation declaration or implicit instantiation, which means 6071 // we haven't codegenned any members yet), so propagate the attribute. 6072 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6073 NewAttr->setInherited(true); 6074 BaseTemplateSpec->addAttr(NewAttr); 6075 6076 // If this was an import, mark that we propagated it from a derived class to 6077 // a base class template specialization. 6078 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6079 ImportAttr->setPropagatedToBaseTemplate(); 6080 6081 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6082 // needs to be run again to work see the new attribute. Otherwise this will 6083 // get run whenever the template is instantiated. 6084 if (TSK != TSK_Undeclared) 6085 checkClassLevelDLLAttribute(BaseTemplateSpec); 6086 6087 return; 6088 } 6089 6090 if (getDLLAttr(BaseTemplateSpec)) { 6091 // The template has already been specialized or instantiated with an 6092 // attribute, explicitly or through propagation. We should not try to change 6093 // it. 6094 return; 6095 } 6096 6097 // The template was previously instantiated or explicitly specialized without 6098 // a dll attribute, It's too late for us to add an attribute, so warn that 6099 // this is unsupported. 6100 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6101 << BaseTemplateSpec->isExplicitSpecialization(); 6102 Diag(ClassAttr->getLocation(), diag::note_attribute); 6103 if (BaseTemplateSpec->isExplicitSpecialization()) { 6104 Diag(BaseTemplateSpec->getLocation(), 6105 diag::note_template_class_explicit_specialization_was_here) 6106 << BaseTemplateSpec; 6107 } else { 6108 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6109 diag::note_template_class_instantiation_was_here) 6110 << BaseTemplateSpec; 6111 } 6112 } 6113 6114 /// Determine the kind of defaulting that would be done for a given function. 6115 /// 6116 /// If the function is both a default constructor and a copy / move constructor 6117 /// (due to having a default argument for the first parameter), this picks 6118 /// CXXDefaultConstructor. 6119 /// 6120 /// FIXME: Check that case is properly handled by all callers. 6121 Sema::DefaultedFunctionKind 6122 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6123 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6124 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6125 if (Ctor->isDefaultConstructor()) 6126 return Sema::CXXDefaultConstructor; 6127 6128 if (Ctor->isCopyConstructor()) 6129 return Sema::CXXCopyConstructor; 6130 6131 if (Ctor->isMoveConstructor()) 6132 return Sema::CXXMoveConstructor; 6133 } 6134 6135 if (MD->isCopyAssignmentOperator()) 6136 return Sema::CXXCopyAssignment; 6137 6138 if (MD->isMoveAssignmentOperator()) 6139 return Sema::CXXMoveAssignment; 6140 6141 if (isa<CXXDestructorDecl>(FD)) 6142 return Sema::CXXDestructor; 6143 } 6144 6145 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6146 case OO_EqualEqual: 6147 return DefaultedComparisonKind::Equal; 6148 6149 case OO_ExclaimEqual: 6150 return DefaultedComparisonKind::NotEqual; 6151 6152 case OO_Spaceship: 6153 // No point allowing this if <=> doesn't exist in the current language mode. 6154 if (!getLangOpts().CPlusPlus2a) 6155 break; 6156 return DefaultedComparisonKind::ThreeWay; 6157 6158 case OO_Less: 6159 case OO_LessEqual: 6160 case OO_Greater: 6161 case OO_GreaterEqual: 6162 // No point allowing this if <=> doesn't exist in the current language mode. 6163 if (!getLangOpts().CPlusPlus2a) 6164 break; 6165 return DefaultedComparisonKind::Relational; 6166 6167 default: 6168 break; 6169 } 6170 6171 // Not defaultable. 6172 return DefaultedFunctionKind(); 6173 } 6174 6175 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 6176 SourceLocation DefaultLoc) { 6177 switch (S.getSpecialMember(MD)) { 6178 case Sema::CXXDefaultConstructor: 6179 S.DefineImplicitDefaultConstructor(DefaultLoc, 6180 cast<CXXConstructorDecl>(MD)); 6181 break; 6182 case Sema::CXXCopyConstructor: 6183 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6184 break; 6185 case Sema::CXXCopyAssignment: 6186 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 6187 break; 6188 case Sema::CXXDestructor: 6189 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 6190 break; 6191 case Sema::CXXMoveConstructor: 6192 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6193 break; 6194 case Sema::CXXMoveAssignment: 6195 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 6196 break; 6197 case Sema::CXXInvalid: 6198 llvm_unreachable("Invalid special member."); 6199 } 6200 } 6201 6202 /// Determine whether a type is permitted to be passed or returned in 6203 /// registers, per C++ [class.temporary]p3. 6204 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6205 TargetInfo::CallingConvKind CCK) { 6206 if (D->isDependentType() || D->isInvalidDecl()) 6207 return false; 6208 6209 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6210 // The PS4 platform ABI follows the behavior of Clang 3.2. 6211 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6212 return !D->hasNonTrivialDestructorForCall() && 6213 !D->hasNonTrivialCopyConstructorForCall(); 6214 6215 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6216 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6217 bool DtorIsTrivialForCall = false; 6218 6219 // If a class has at least one non-deleted, trivial copy constructor, it 6220 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6221 // 6222 // Note: This permits classes with non-trivial copy or move ctors to be 6223 // passed in registers, so long as they *also* have a trivial copy ctor, 6224 // which is non-conforming. 6225 if (D->needsImplicitCopyConstructor()) { 6226 if (!D->defaultedCopyConstructorIsDeleted()) { 6227 if (D->hasTrivialCopyConstructor()) 6228 CopyCtorIsTrivial = true; 6229 if (D->hasTrivialCopyConstructorForCall()) 6230 CopyCtorIsTrivialForCall = true; 6231 } 6232 } else { 6233 for (const CXXConstructorDecl *CD : D->ctors()) { 6234 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6235 if (CD->isTrivial()) 6236 CopyCtorIsTrivial = true; 6237 if (CD->isTrivialForCall()) 6238 CopyCtorIsTrivialForCall = true; 6239 } 6240 } 6241 } 6242 6243 if (D->needsImplicitDestructor()) { 6244 if (!D->defaultedDestructorIsDeleted() && 6245 D->hasTrivialDestructorForCall()) 6246 DtorIsTrivialForCall = true; 6247 } else if (const auto *DD = D->getDestructor()) { 6248 if (!DD->isDeleted() && DD->isTrivialForCall()) 6249 DtorIsTrivialForCall = true; 6250 } 6251 6252 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6253 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6254 return true; 6255 6256 // If a class has a destructor, we'd really like to pass it indirectly 6257 // because it allows us to elide copies. Unfortunately, MSVC makes that 6258 // impossible for small types, which it will pass in a single register or 6259 // stack slot. Most objects with dtors are large-ish, so handle that early. 6260 // We can't call out all large objects as being indirect because there are 6261 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6262 // how we pass large POD types. 6263 6264 // Note: This permits small classes with nontrivial destructors to be 6265 // passed in registers, which is non-conforming. 6266 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6267 uint64_t TypeSize = isAArch64 ? 128 : 64; 6268 6269 if (CopyCtorIsTrivial && 6270 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6271 return true; 6272 return false; 6273 } 6274 6275 // Per C++ [class.temporary]p3, the relevant condition is: 6276 // each copy constructor, move constructor, and destructor of X is 6277 // either trivial or deleted, and X has at least one non-deleted copy 6278 // or move constructor 6279 bool HasNonDeletedCopyOrMove = false; 6280 6281 if (D->needsImplicitCopyConstructor() && 6282 !D->defaultedCopyConstructorIsDeleted()) { 6283 if (!D->hasTrivialCopyConstructorForCall()) 6284 return false; 6285 HasNonDeletedCopyOrMove = true; 6286 } 6287 6288 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6289 !D->defaultedMoveConstructorIsDeleted()) { 6290 if (!D->hasTrivialMoveConstructorForCall()) 6291 return false; 6292 HasNonDeletedCopyOrMove = true; 6293 } 6294 6295 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6296 !D->hasTrivialDestructorForCall()) 6297 return false; 6298 6299 for (const CXXMethodDecl *MD : D->methods()) { 6300 if (MD->isDeleted()) 6301 continue; 6302 6303 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6304 if (CD && CD->isCopyOrMoveConstructor()) 6305 HasNonDeletedCopyOrMove = true; 6306 else if (!isa<CXXDestructorDecl>(MD)) 6307 continue; 6308 6309 if (!MD->isTrivialForCall()) 6310 return false; 6311 } 6312 6313 return HasNonDeletedCopyOrMove; 6314 } 6315 6316 /// Perform semantic checks on a class definition that has been 6317 /// completing, introducing implicitly-declared members, checking for 6318 /// abstract types, etc. 6319 /// 6320 /// \param S The scope in which the class was parsed. Null if we didn't just 6321 /// parse a class definition. 6322 /// \param Record The completed class. 6323 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6324 if (!Record) 6325 return; 6326 6327 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6328 AbstractUsageInfo Info(*this, Record); 6329 CheckAbstractClassUsage(Info, Record); 6330 } 6331 6332 // If this is not an aggregate type and has no user-declared constructor, 6333 // complain about any non-static data members of reference or const scalar 6334 // type, since they will never get initializers. 6335 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6336 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6337 !Record->isLambda()) { 6338 bool Complained = false; 6339 for (const auto *F : Record->fields()) { 6340 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6341 continue; 6342 6343 if (F->getType()->isReferenceType() || 6344 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6345 if (!Complained) { 6346 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6347 << Record->getTagKind() << Record; 6348 Complained = true; 6349 } 6350 6351 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6352 << F->getType()->isReferenceType() 6353 << F->getDeclName(); 6354 } 6355 } 6356 } 6357 6358 if (Record->getIdentifier()) { 6359 // C++ [class.mem]p13: 6360 // If T is the name of a class, then each of the following shall have a 6361 // name different from T: 6362 // - every member of every anonymous union that is a member of class T. 6363 // 6364 // C++ [class.mem]p14: 6365 // In addition, if class T has a user-declared constructor (12.1), every 6366 // non-static data member of class T shall have a name different from T. 6367 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6368 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6369 ++I) { 6370 NamedDecl *D = (*I)->getUnderlyingDecl(); 6371 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6372 Record->hasUserDeclaredConstructor()) || 6373 isa<IndirectFieldDecl>(D)) { 6374 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6375 << D->getDeclName(); 6376 break; 6377 } 6378 } 6379 } 6380 6381 // Warn if the class has virtual methods but non-virtual public destructor. 6382 if (Record->isPolymorphic() && !Record->isDependentType()) { 6383 CXXDestructorDecl *dtor = Record->getDestructor(); 6384 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6385 !Record->hasAttr<FinalAttr>()) 6386 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6387 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6388 } 6389 6390 if (Record->isAbstract()) { 6391 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6392 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6393 << FA->isSpelledAsSealed(); 6394 DiagnoseAbstractType(Record); 6395 } 6396 } 6397 6398 // Warn if the class has a final destructor but is not itself marked final. 6399 if (!Record->hasAttr<FinalAttr>()) { 6400 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6401 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6402 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6403 << FA->isSpelledAsSealed() 6404 << FixItHint::CreateInsertion( 6405 getLocForEndOfToken(Record->getLocation()), 6406 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6407 Diag(Record->getLocation(), 6408 diag::note_final_dtor_non_final_class_silence) 6409 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6410 } 6411 } 6412 } 6413 6414 // See if trivial_abi has to be dropped. 6415 if (Record->hasAttr<TrivialABIAttr>()) 6416 checkIllFormedTrivialABIStruct(*Record); 6417 6418 // Set HasTrivialSpecialMemberForCall if the record has attribute 6419 // "trivial_abi". 6420 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6421 6422 if (HasTrivialABI) 6423 Record->setHasTrivialSpecialMemberForCall(); 6424 6425 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6426 // We check these last because they can depend on the properties of the 6427 // primary comparison functions (==, <=>). 6428 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6429 6430 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) { 6431 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6432 return; 6433 6434 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6435 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6436 DFK.asComparison() == DefaultedComparisonKind::Relational) 6437 DefaultedSecondaryComparisons.push_back(FD); 6438 else 6439 CheckExplicitlyDefaultedFunction(S, FD); 6440 }; 6441 6442 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6443 // Check whether the explicitly-defaulted members are valid. 6444 CheckForDefaultedFunction(M); 6445 6446 // Skip the rest of the checks for a member of a dependent class. 6447 if (Record->isDependentType()) 6448 return; 6449 6450 // For an explicitly defaulted or deleted special member, we defer 6451 // determining triviality until the class is complete. That time is now! 6452 CXXSpecialMember CSM = getSpecialMember(M); 6453 if (!M->isImplicit() && !M->isUserProvided()) { 6454 if (CSM != CXXInvalid) { 6455 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6456 // Inform the class that we've finished declaring this member. 6457 Record->finishedDefaultedOrDeletedMember(M); 6458 M->setTrivialForCall( 6459 HasTrivialABI || 6460 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6461 Record->setTrivialForCallFlags(M); 6462 } 6463 } 6464 6465 // Set triviality for the purpose of calls if this is a user-provided 6466 // copy/move constructor or destructor. 6467 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6468 CSM == CXXDestructor) && M->isUserProvided()) { 6469 M->setTrivialForCall(HasTrivialABI); 6470 Record->setTrivialForCallFlags(M); 6471 } 6472 6473 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6474 M->hasAttr<DLLExportAttr>()) { 6475 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6476 M->isTrivial() && 6477 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6478 CSM == CXXDestructor)) 6479 M->dropAttr<DLLExportAttr>(); 6480 6481 if (M->hasAttr<DLLExportAttr>()) { 6482 // Define after any fields with in-class initializers have been parsed. 6483 DelayedDllExportMemberFunctions.push_back(M); 6484 } 6485 } 6486 6487 // Define defaulted constexpr virtual functions that override a base class 6488 // function right away. 6489 // FIXME: We can defer doing this until the vtable is marked as used. 6490 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6491 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6492 }; 6493 6494 // Check the destructor before any other member function. We need to 6495 // determine whether it's trivial in order to determine whether the claas 6496 // type is a literal type, which is a prerequisite for determining whether 6497 // other special member functions are valid and whether they're implicitly 6498 // 'constexpr'. 6499 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6500 CompleteMemberFunction(Dtor); 6501 6502 bool HasMethodWithOverrideControl = false, 6503 HasOverridingMethodWithoutOverrideControl = false; 6504 for (auto *D : Record->decls()) { 6505 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6506 // FIXME: We could do this check for dependent types with non-dependent 6507 // bases. 6508 if (!Record->isDependentType()) { 6509 // See if a method overloads virtual methods in a base 6510 // class without overriding any. 6511 if (!M->isStatic()) 6512 DiagnoseHiddenVirtualMethods(M); 6513 if (M->hasAttr<OverrideAttr>()) 6514 HasMethodWithOverrideControl = true; 6515 else if (M->size_overridden_methods() > 0) 6516 HasOverridingMethodWithoutOverrideControl = true; 6517 } 6518 6519 if (!isa<CXXDestructorDecl>(M)) 6520 CompleteMemberFunction(M); 6521 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6522 CheckForDefaultedFunction( 6523 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6524 } 6525 } 6526 6527 if (HasMethodWithOverrideControl && 6528 HasOverridingMethodWithoutOverrideControl) { 6529 // At least one method has the 'override' control declared. 6530 // Diagnose all other overridden methods which do not have 'override' 6531 // specified on them. 6532 for (auto *M : Record->methods()) 6533 DiagnoseAbsenceOfOverrideControl(M); 6534 } 6535 6536 // Check the defaulted secondary comparisons after any other member functions. 6537 for (FunctionDecl *FD : DefaultedSecondaryComparisons) 6538 CheckExplicitlyDefaultedFunction(S, FD); 6539 6540 // ms_struct is a request to use the same ABI rules as MSVC. Check 6541 // whether this class uses any C++ features that are implemented 6542 // completely differently in MSVC, and if so, emit a diagnostic. 6543 // That diagnostic defaults to an error, but we allow projects to 6544 // map it down to a warning (or ignore it). It's a fairly common 6545 // practice among users of the ms_struct pragma to mass-annotate 6546 // headers, sweeping up a bunch of types that the project doesn't 6547 // really rely on MSVC-compatible layout for. We must therefore 6548 // support "ms_struct except for C++ stuff" as a secondary ABI. 6549 if (Record->isMsStruct(Context) && 6550 (Record->isPolymorphic() || Record->getNumBases())) { 6551 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6552 } 6553 6554 checkClassLevelDLLAttribute(Record); 6555 checkClassLevelCodeSegAttribute(Record); 6556 6557 bool ClangABICompat4 = 6558 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6559 TargetInfo::CallingConvKind CCK = 6560 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6561 bool CanPass = canPassInRegisters(*this, Record, CCK); 6562 6563 // Do not change ArgPassingRestrictions if it has already been set to 6564 // APK_CanNeverPassInRegs. 6565 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6566 Record->setArgPassingRestrictions(CanPass 6567 ? RecordDecl::APK_CanPassInRegs 6568 : RecordDecl::APK_CannotPassInRegs); 6569 6570 // If canPassInRegisters returns true despite the record having a non-trivial 6571 // destructor, the record is destructed in the callee. This happens only when 6572 // the record or one of its subobjects has a field annotated with trivial_abi 6573 // or a field qualified with ObjC __strong/__weak. 6574 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6575 Record->setParamDestroyedInCallee(true); 6576 else if (Record->hasNonTrivialDestructor()) 6577 Record->setParamDestroyedInCallee(CanPass); 6578 6579 if (getLangOpts().ForceEmitVTables) { 6580 // If we want to emit all the vtables, we need to mark it as used. This 6581 // is especially required for cases like vtable assumption loads. 6582 MarkVTableUsed(Record->getInnerLocStart(), Record); 6583 } 6584 } 6585 6586 /// Look up the special member function that would be called by a special 6587 /// member function for a subobject of class type. 6588 /// 6589 /// \param Class The class type of the subobject. 6590 /// \param CSM The kind of special member function. 6591 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6592 /// \param ConstRHS True if this is a copy operation with a const object 6593 /// on its RHS, that is, if the argument to the outer special member 6594 /// function is 'const' and this is not a field marked 'mutable'. 6595 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6596 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6597 unsigned FieldQuals, bool ConstRHS) { 6598 unsigned LHSQuals = 0; 6599 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6600 LHSQuals = FieldQuals; 6601 6602 unsigned RHSQuals = FieldQuals; 6603 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6604 RHSQuals = 0; 6605 else if (ConstRHS) 6606 RHSQuals |= Qualifiers::Const; 6607 6608 return S.LookupSpecialMember(Class, CSM, 6609 RHSQuals & Qualifiers::Const, 6610 RHSQuals & Qualifiers::Volatile, 6611 false, 6612 LHSQuals & Qualifiers::Const, 6613 LHSQuals & Qualifiers::Volatile); 6614 } 6615 6616 class Sema::InheritedConstructorInfo { 6617 Sema &S; 6618 SourceLocation UseLoc; 6619 6620 /// A mapping from the base classes through which the constructor was 6621 /// inherited to the using shadow declaration in that base class (or a null 6622 /// pointer if the constructor was declared in that base class). 6623 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6624 InheritedFromBases; 6625 6626 public: 6627 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6628 ConstructorUsingShadowDecl *Shadow) 6629 : S(S), UseLoc(UseLoc) { 6630 bool DiagnosedMultipleConstructedBases = false; 6631 CXXRecordDecl *ConstructedBase = nullptr; 6632 UsingDecl *ConstructedBaseUsing = nullptr; 6633 6634 // Find the set of such base class subobjects and check that there's a 6635 // unique constructed subobject. 6636 for (auto *D : Shadow->redecls()) { 6637 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6638 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6639 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6640 6641 InheritedFromBases.insert( 6642 std::make_pair(DNominatedBase->getCanonicalDecl(), 6643 DShadow->getNominatedBaseClassShadowDecl())); 6644 if (DShadow->constructsVirtualBase()) 6645 InheritedFromBases.insert( 6646 std::make_pair(DConstructedBase->getCanonicalDecl(), 6647 DShadow->getConstructedBaseClassShadowDecl())); 6648 else 6649 assert(DNominatedBase == DConstructedBase); 6650 6651 // [class.inhctor.init]p2: 6652 // If the constructor was inherited from multiple base class subobjects 6653 // of type B, the program is ill-formed. 6654 if (!ConstructedBase) { 6655 ConstructedBase = DConstructedBase; 6656 ConstructedBaseUsing = D->getUsingDecl(); 6657 } else if (ConstructedBase != DConstructedBase && 6658 !Shadow->isInvalidDecl()) { 6659 if (!DiagnosedMultipleConstructedBases) { 6660 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6661 << Shadow->getTargetDecl(); 6662 S.Diag(ConstructedBaseUsing->getLocation(), 6663 diag::note_ambiguous_inherited_constructor_using) 6664 << ConstructedBase; 6665 DiagnosedMultipleConstructedBases = true; 6666 } 6667 S.Diag(D->getUsingDecl()->getLocation(), 6668 diag::note_ambiguous_inherited_constructor_using) 6669 << DConstructedBase; 6670 } 6671 } 6672 6673 if (DiagnosedMultipleConstructedBases) 6674 Shadow->setInvalidDecl(); 6675 } 6676 6677 /// Find the constructor to use for inherited construction of a base class, 6678 /// and whether that base class constructor inherits the constructor from a 6679 /// virtual base class (in which case it won't actually invoke it). 6680 std::pair<CXXConstructorDecl *, bool> 6681 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6682 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6683 if (It == InheritedFromBases.end()) 6684 return std::make_pair(nullptr, false); 6685 6686 // This is an intermediary class. 6687 if (It->second) 6688 return std::make_pair( 6689 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6690 It->second->constructsVirtualBase()); 6691 6692 // This is the base class from which the constructor was inherited. 6693 return std::make_pair(Ctor, false); 6694 } 6695 }; 6696 6697 /// Is the special member function which would be selected to perform the 6698 /// specified operation on the specified class type a constexpr constructor? 6699 static bool 6700 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6701 Sema::CXXSpecialMember CSM, unsigned Quals, 6702 bool ConstRHS, 6703 CXXConstructorDecl *InheritedCtor = nullptr, 6704 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6705 // If we're inheriting a constructor, see if we need to call it for this base 6706 // class. 6707 if (InheritedCtor) { 6708 assert(CSM == Sema::CXXDefaultConstructor); 6709 auto BaseCtor = 6710 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6711 if (BaseCtor) 6712 return BaseCtor->isConstexpr(); 6713 } 6714 6715 if (CSM == Sema::CXXDefaultConstructor) 6716 return ClassDecl->hasConstexprDefaultConstructor(); 6717 if (CSM == Sema::CXXDestructor) 6718 return ClassDecl->hasConstexprDestructor(); 6719 6720 Sema::SpecialMemberOverloadResult SMOR = 6721 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6722 if (!SMOR.getMethod()) 6723 // A constructor we wouldn't select can't be "involved in initializing" 6724 // anything. 6725 return true; 6726 return SMOR.getMethod()->isConstexpr(); 6727 } 6728 6729 /// Determine whether the specified special member function would be constexpr 6730 /// if it were implicitly defined. 6731 static bool defaultedSpecialMemberIsConstexpr( 6732 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6733 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6734 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6735 if (!S.getLangOpts().CPlusPlus11) 6736 return false; 6737 6738 // C++11 [dcl.constexpr]p4: 6739 // In the definition of a constexpr constructor [...] 6740 bool Ctor = true; 6741 switch (CSM) { 6742 case Sema::CXXDefaultConstructor: 6743 if (Inherited) 6744 break; 6745 // Since default constructor lookup is essentially trivial (and cannot 6746 // involve, for instance, template instantiation), we compute whether a 6747 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6748 // 6749 // This is important for performance; we need to know whether the default 6750 // constructor is constexpr to determine whether the type is a literal type. 6751 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6752 6753 case Sema::CXXCopyConstructor: 6754 case Sema::CXXMoveConstructor: 6755 // For copy or move constructors, we need to perform overload resolution. 6756 break; 6757 6758 case Sema::CXXCopyAssignment: 6759 case Sema::CXXMoveAssignment: 6760 if (!S.getLangOpts().CPlusPlus14) 6761 return false; 6762 // In C++1y, we need to perform overload resolution. 6763 Ctor = false; 6764 break; 6765 6766 case Sema::CXXDestructor: 6767 return ClassDecl->defaultedDestructorIsConstexpr(); 6768 6769 case Sema::CXXInvalid: 6770 return false; 6771 } 6772 6773 // -- if the class is a non-empty union, or for each non-empty anonymous 6774 // union member of a non-union class, exactly one non-static data member 6775 // shall be initialized; [DR1359] 6776 // 6777 // If we squint, this is guaranteed, since exactly one non-static data member 6778 // will be initialized (if the constructor isn't deleted), we just don't know 6779 // which one. 6780 if (Ctor && ClassDecl->isUnion()) 6781 return CSM == Sema::CXXDefaultConstructor 6782 ? ClassDecl->hasInClassInitializer() || 6783 !ClassDecl->hasVariantMembers() 6784 : true; 6785 6786 // -- the class shall not have any virtual base classes; 6787 if (Ctor && ClassDecl->getNumVBases()) 6788 return false; 6789 6790 // C++1y [class.copy]p26: 6791 // -- [the class] is a literal type, and 6792 if (!Ctor && !ClassDecl->isLiteral()) 6793 return false; 6794 6795 // -- every constructor involved in initializing [...] base class 6796 // sub-objects shall be a constexpr constructor; 6797 // -- the assignment operator selected to copy/move each direct base 6798 // class is a constexpr function, and 6799 for (const auto &B : ClassDecl->bases()) { 6800 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6801 if (!BaseType) continue; 6802 6803 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6804 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6805 InheritedCtor, Inherited)) 6806 return false; 6807 } 6808 6809 // -- every constructor involved in initializing non-static data members 6810 // [...] shall be a constexpr constructor; 6811 // -- every non-static data member and base class sub-object shall be 6812 // initialized 6813 // -- for each non-static data member of X that is of class type (or array 6814 // thereof), the assignment operator selected to copy/move that member is 6815 // a constexpr function 6816 for (const auto *F : ClassDecl->fields()) { 6817 if (F->isInvalidDecl()) 6818 continue; 6819 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6820 continue; 6821 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6822 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6823 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6824 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6825 BaseType.getCVRQualifiers(), 6826 ConstArg && !F->isMutable())) 6827 return false; 6828 } else if (CSM == Sema::CXXDefaultConstructor) { 6829 return false; 6830 } 6831 } 6832 6833 // All OK, it's constexpr! 6834 return true; 6835 } 6836 6837 namespace { 6838 /// RAII object to register a defaulted function as having its exception 6839 /// specification computed. 6840 struct ComputingExceptionSpec { 6841 Sema &S; 6842 6843 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 6844 : S(S) { 6845 Sema::CodeSynthesisContext Ctx; 6846 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 6847 Ctx.PointOfInstantiation = Loc; 6848 Ctx.Entity = FD; 6849 S.pushCodeSynthesisContext(Ctx); 6850 } 6851 ~ComputingExceptionSpec() { 6852 S.popCodeSynthesisContext(); 6853 } 6854 }; 6855 } 6856 6857 static Sema::ImplicitExceptionSpecification 6858 ComputeDefaultedSpecialMemberExceptionSpec( 6859 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6860 Sema::InheritedConstructorInfo *ICI); 6861 6862 static Sema::ImplicitExceptionSpecification 6863 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 6864 FunctionDecl *FD, 6865 Sema::DefaultedComparisonKind DCK); 6866 6867 static Sema::ImplicitExceptionSpecification 6868 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 6869 auto DFK = S.getDefaultedFunctionKind(FD); 6870 if (DFK.isSpecialMember()) 6871 return ComputeDefaultedSpecialMemberExceptionSpec( 6872 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 6873 if (DFK.isComparison()) 6874 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 6875 DFK.asComparison()); 6876 6877 auto *CD = cast<CXXConstructorDecl>(FD); 6878 assert(CD->getInheritedConstructor() && 6879 "only defaulted functions and inherited constructors have implicit " 6880 "exception specs"); 6881 Sema::InheritedConstructorInfo ICI( 6882 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6883 return ComputeDefaultedSpecialMemberExceptionSpec( 6884 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6885 } 6886 6887 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6888 CXXMethodDecl *MD) { 6889 FunctionProtoType::ExtProtoInfo EPI; 6890 6891 // Build an exception specification pointing back at this member. 6892 EPI.ExceptionSpec.Type = EST_Unevaluated; 6893 EPI.ExceptionSpec.SourceDecl = MD; 6894 6895 // Set the calling convention to the default for C++ instance methods. 6896 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6897 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6898 /*IsCXXMethod=*/true)); 6899 return EPI; 6900 } 6901 6902 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 6903 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 6904 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6905 return; 6906 6907 // Evaluate the exception specification. 6908 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 6909 auto ESI = IES.getExceptionSpec(); 6910 6911 // Update the type of the special member to use it. 6912 UpdateExceptionSpec(FD, ESI); 6913 } 6914 6915 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 6916 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 6917 6918 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 6919 if (!DefKind) { 6920 assert(FD->getDeclContext()->isDependentContext()); 6921 return; 6922 } 6923 6924 if (DefKind.isSpecialMember() 6925 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 6926 DefKind.asSpecialMember()) 6927 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 6928 FD->setInvalidDecl(); 6929 } 6930 6931 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 6932 CXXSpecialMember CSM) { 6933 CXXRecordDecl *RD = MD->getParent(); 6934 6935 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6936 "not an explicitly-defaulted special member"); 6937 6938 // Defer all checking for special members of a dependent type. 6939 if (RD->isDependentType()) 6940 return false; 6941 6942 // Whether this was the first-declared instance of the constructor. 6943 // This affects whether we implicitly add an exception spec and constexpr. 6944 bool First = MD == MD->getCanonicalDecl(); 6945 6946 bool HadError = false; 6947 6948 // C++11 [dcl.fct.def.default]p1: 6949 // A function that is explicitly defaulted shall 6950 // -- be a special member function [...] (checked elsewhere), 6951 // -- have the same type (except for ref-qualifiers, and except that a 6952 // copy operation can take a non-const reference) as an implicit 6953 // declaration, and 6954 // -- not have default arguments. 6955 // C++2a changes the second bullet to instead delete the function if it's 6956 // defaulted on its first declaration, unless it's "an assignment operator, 6957 // and its return type differs or its parameter type is not a reference". 6958 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6959 bool ShouldDeleteForTypeMismatch = false; 6960 unsigned ExpectedParams = 1; 6961 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6962 ExpectedParams = 0; 6963 if (MD->getNumParams() != ExpectedParams) { 6964 // This checks for default arguments: a copy or move constructor with a 6965 // default argument is classified as a default constructor, and assignment 6966 // operations and destructors can't have default arguments. 6967 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6968 << CSM << MD->getSourceRange(); 6969 HadError = true; 6970 } else if (MD->isVariadic()) { 6971 if (DeleteOnTypeMismatch) 6972 ShouldDeleteForTypeMismatch = true; 6973 else { 6974 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6975 << CSM << MD->getSourceRange(); 6976 HadError = true; 6977 } 6978 } 6979 6980 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6981 6982 bool CanHaveConstParam = false; 6983 if (CSM == CXXCopyConstructor) 6984 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6985 else if (CSM == CXXCopyAssignment) 6986 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6987 6988 QualType ReturnType = Context.VoidTy; 6989 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6990 // Check for return type matching. 6991 ReturnType = Type->getReturnType(); 6992 6993 QualType DeclType = Context.getTypeDeclType(RD); 6994 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 6995 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6996 6997 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6998 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6999 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7000 HadError = true; 7001 } 7002 7003 // A defaulted special member cannot have cv-qualifiers. 7004 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7005 if (DeleteOnTypeMismatch) 7006 ShouldDeleteForTypeMismatch = true; 7007 else { 7008 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7009 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7010 HadError = true; 7011 } 7012 } 7013 } 7014 7015 // Check for parameter type matching. 7016 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7017 bool HasConstParam = false; 7018 if (ExpectedParams && ArgType->isReferenceType()) { 7019 // Argument must be reference to possibly-const T. 7020 QualType ReferentType = ArgType->getPointeeType(); 7021 HasConstParam = ReferentType.isConstQualified(); 7022 7023 if (ReferentType.isVolatileQualified()) { 7024 if (DeleteOnTypeMismatch) 7025 ShouldDeleteForTypeMismatch = true; 7026 else { 7027 Diag(MD->getLocation(), 7028 diag::err_defaulted_special_member_volatile_param) << CSM; 7029 HadError = true; 7030 } 7031 } 7032 7033 if (HasConstParam && !CanHaveConstParam) { 7034 if (DeleteOnTypeMismatch) 7035 ShouldDeleteForTypeMismatch = true; 7036 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7037 Diag(MD->getLocation(), 7038 diag::err_defaulted_special_member_copy_const_param) 7039 << (CSM == CXXCopyAssignment); 7040 // FIXME: Explain why this special member can't be const. 7041 HadError = true; 7042 } else { 7043 Diag(MD->getLocation(), 7044 diag::err_defaulted_special_member_move_const_param) 7045 << (CSM == CXXMoveAssignment); 7046 HadError = true; 7047 } 7048 } 7049 } else if (ExpectedParams) { 7050 // A copy assignment operator can take its argument by value, but a 7051 // defaulted one cannot. 7052 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7053 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7054 HadError = true; 7055 } 7056 7057 // C++11 [dcl.fct.def.default]p2: 7058 // An explicitly-defaulted function may be declared constexpr only if it 7059 // would have been implicitly declared as constexpr, 7060 // Do not apply this rule to members of class templates, since core issue 1358 7061 // makes such functions always instantiate to constexpr functions. For 7062 // functions which cannot be constexpr (for non-constructors in C++11 and for 7063 // destructors in C++14 and C++17), this is checked elsewhere. 7064 // 7065 // FIXME: This should not apply if the member is deleted. 7066 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7067 HasConstParam); 7068 if ((getLangOpts().CPlusPlus2a || 7069 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7070 : isa<CXXConstructorDecl>(MD))) && 7071 MD->isConstexpr() && !Constexpr && 7072 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7073 Diag(MD->getBeginLoc(), MD->isConsteval() 7074 ? diag::err_incorrect_defaulted_consteval 7075 : diag::err_incorrect_defaulted_constexpr) 7076 << CSM; 7077 // FIXME: Explain why the special member can't be constexpr. 7078 HadError = true; 7079 } 7080 7081 if (First) { 7082 // C++2a [dcl.fct.def.default]p3: 7083 // If a function is explicitly defaulted on its first declaration, it is 7084 // implicitly considered to be constexpr if the implicit declaration 7085 // would be. 7086 MD->setConstexprKind( 7087 Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr) 7088 : CSK_unspecified); 7089 7090 if (!Type->hasExceptionSpec()) { 7091 // C++2a [except.spec]p3: 7092 // If a declaration of a function does not have a noexcept-specifier 7093 // [and] is defaulted on its first declaration, [...] the exception 7094 // specification is as specified below 7095 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7096 EPI.ExceptionSpec.Type = EST_Unevaluated; 7097 EPI.ExceptionSpec.SourceDecl = MD; 7098 MD->setType(Context.getFunctionType(ReturnType, 7099 llvm::makeArrayRef(&ArgType, 7100 ExpectedParams), 7101 EPI)); 7102 } 7103 } 7104 7105 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7106 if (First) { 7107 SetDeclDeleted(MD, MD->getLocation()); 7108 if (!inTemplateInstantiation() && !HadError) { 7109 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7110 if (ShouldDeleteForTypeMismatch) { 7111 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7112 } else { 7113 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7114 } 7115 } 7116 if (ShouldDeleteForTypeMismatch && !HadError) { 7117 Diag(MD->getLocation(), 7118 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7119 } 7120 } else { 7121 // C++11 [dcl.fct.def.default]p4: 7122 // [For a] user-provided explicitly-defaulted function [...] if such a 7123 // function is implicitly defined as deleted, the program is ill-formed. 7124 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7125 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7126 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7127 HadError = true; 7128 } 7129 } 7130 7131 return HadError; 7132 } 7133 7134 namespace { 7135 /// Helper class for building and checking a defaulted comparison. 7136 /// 7137 /// Defaulted functions are built in two phases: 7138 /// 7139 /// * First, the set of operations that the function will perform are 7140 /// identified, and some of them are checked. If any of the checked 7141 /// operations is invalid in certain ways, the comparison function is 7142 /// defined as deleted and no body is built. 7143 /// * Then, if the function is not defined as deleted, the body is built. 7144 /// 7145 /// This is accomplished by performing two visitation steps over the eventual 7146 /// body of the function. 7147 template<typename Derived, typename ResultList, typename Result, 7148 typename Subobject> 7149 class DefaultedComparisonVisitor { 7150 public: 7151 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7152 7153 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7154 DefaultedComparisonKind DCK) 7155 : S(S), RD(RD), FD(FD), DCK(DCK) { 7156 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7157 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7158 // UnresolvedSet to avoid this copy. 7159 Fns.assign(Info->getUnqualifiedLookups().begin(), 7160 Info->getUnqualifiedLookups().end()); 7161 } 7162 } 7163 7164 ResultList visit() { 7165 // The type of an lvalue naming a parameter of this function. 7166 QualType ParamLvalType = 7167 FD->getParamDecl(0)->getType().getNonReferenceType(); 7168 7169 ResultList Results; 7170 7171 switch (DCK) { 7172 case DefaultedComparisonKind::None: 7173 llvm_unreachable("not a defaulted comparison"); 7174 7175 case DefaultedComparisonKind::Equal: 7176 case DefaultedComparisonKind::ThreeWay: 7177 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7178 return Results; 7179 7180 case DefaultedComparisonKind::NotEqual: 7181 case DefaultedComparisonKind::Relational: 7182 Results.add(getDerived().visitExpandedSubobject( 7183 ParamLvalType, getDerived().getCompleteObject())); 7184 return Results; 7185 } 7186 llvm_unreachable(""); 7187 } 7188 7189 protected: 7190 Derived &getDerived() { return static_cast<Derived&>(*this); } 7191 7192 /// Visit the expanded list of subobjects of the given type, as specified in 7193 /// C++2a [class.compare.default]. 7194 /// 7195 /// \return \c true if the ResultList object said we're done, \c false if not. 7196 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7197 Qualifiers Quals) { 7198 // C++2a [class.compare.default]p4: 7199 // The direct base class subobjects of C 7200 for (CXXBaseSpecifier &Base : Record->bases()) 7201 if (Results.add(getDerived().visitSubobject( 7202 S.Context.getQualifiedType(Base.getType(), Quals), 7203 getDerived().getBase(&Base)))) 7204 return true; 7205 7206 // followed by the non-static data members of C 7207 for (FieldDecl *Field : Record->fields()) { 7208 // Recursively expand anonymous structs. 7209 if (Field->isAnonymousStructOrUnion()) { 7210 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7211 Quals)) 7212 return true; 7213 continue; 7214 } 7215 7216 // Figure out the type of an lvalue denoting this field. 7217 Qualifiers FieldQuals = Quals; 7218 if (Field->isMutable()) 7219 FieldQuals.removeConst(); 7220 QualType FieldType = 7221 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7222 7223 if (Results.add(getDerived().visitSubobject( 7224 FieldType, getDerived().getField(Field)))) 7225 return true; 7226 } 7227 7228 // form a list of subobjects. 7229 return false; 7230 } 7231 7232 Result visitSubobject(QualType Type, Subobject Subobj) { 7233 // In that list, any subobject of array type is recursively expanded 7234 const ArrayType *AT = S.Context.getAsArrayType(Type); 7235 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7236 return getDerived().visitSubobjectArray(CAT->getElementType(), 7237 CAT->getSize(), Subobj); 7238 return getDerived().visitExpandedSubobject(Type, Subobj); 7239 } 7240 7241 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7242 Subobject Subobj) { 7243 return getDerived().visitSubobject(Type, Subobj); 7244 } 7245 7246 protected: 7247 Sema &S; 7248 CXXRecordDecl *RD; 7249 FunctionDecl *FD; 7250 DefaultedComparisonKind DCK; 7251 UnresolvedSet<16> Fns; 7252 }; 7253 7254 /// Information about a defaulted comparison, as determined by 7255 /// DefaultedComparisonAnalyzer. 7256 struct DefaultedComparisonInfo { 7257 bool Deleted = false; 7258 bool Constexpr = true; 7259 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7260 7261 static DefaultedComparisonInfo deleted() { 7262 DefaultedComparisonInfo Deleted; 7263 Deleted.Deleted = true; 7264 return Deleted; 7265 } 7266 7267 bool add(const DefaultedComparisonInfo &R) { 7268 Deleted |= R.Deleted; 7269 Constexpr &= R.Constexpr; 7270 Category = commonComparisonType(Category, R.Category); 7271 return Deleted; 7272 } 7273 }; 7274 7275 /// An element in the expanded list of subobjects of a defaulted comparison, as 7276 /// specified in C++2a [class.compare.default]p4. 7277 struct DefaultedComparisonSubobject { 7278 enum { CompleteObject, Member, Base } Kind; 7279 NamedDecl *Decl; 7280 SourceLocation Loc; 7281 }; 7282 7283 /// A visitor over the notional body of a defaulted comparison that determines 7284 /// whether that body would be deleted or constexpr. 7285 class DefaultedComparisonAnalyzer 7286 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7287 DefaultedComparisonInfo, 7288 DefaultedComparisonInfo, 7289 DefaultedComparisonSubobject> { 7290 public: 7291 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7292 7293 private: 7294 DiagnosticKind Diagnose; 7295 7296 public: 7297 using Base = DefaultedComparisonVisitor; 7298 using Result = DefaultedComparisonInfo; 7299 using Subobject = DefaultedComparisonSubobject; 7300 7301 friend Base; 7302 7303 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7304 DefaultedComparisonKind DCK, 7305 DiagnosticKind Diagnose = NoDiagnostics) 7306 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7307 7308 Result visit() { 7309 if ((DCK == DefaultedComparisonKind::Equal || 7310 DCK == DefaultedComparisonKind::ThreeWay) && 7311 RD->hasVariantMembers()) { 7312 // C++2a [class.compare.default]p2 [P2002R0]: 7313 // A defaulted comparison operator function for class C is defined as 7314 // deleted if [...] C has variant members. 7315 if (Diagnose == ExplainDeleted) { 7316 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7317 << FD << RD->isUnion() << RD; 7318 } 7319 return Result::deleted(); 7320 } 7321 7322 return Base::visit(); 7323 } 7324 7325 private: 7326 Subobject getCompleteObject() { 7327 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7328 } 7329 7330 Subobject getBase(CXXBaseSpecifier *Base) { 7331 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7332 Base->getBaseTypeLoc()}; 7333 } 7334 7335 Subobject getField(FieldDecl *Field) { 7336 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7337 } 7338 7339 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7340 // C++2a [class.compare.default]p2 [P2002R0]: 7341 // A defaulted <=> or == operator function for class C is defined as 7342 // deleted if any non-static data member of C is of reference type 7343 if (Type->isReferenceType()) { 7344 if (Diagnose == ExplainDeleted) { 7345 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7346 << FD << RD; 7347 } 7348 return Result::deleted(); 7349 } 7350 7351 // [...] Let xi be an lvalue denoting the ith element [...] 7352 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7353 Expr *Args[] = {&Xi, &Xi}; 7354 7355 // All operators start by trying to apply that same operator recursively. 7356 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7357 assert(OO != OO_None && "not an overloaded operator!"); 7358 return visitBinaryOperator(OO, Args, Subobj); 7359 } 7360 7361 Result 7362 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7363 Subobject Subobj, 7364 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7365 // Note that there is no need to consider rewritten candidates here if 7366 // we've already found there is no viable 'operator<=>' candidate (and are 7367 // considering synthesizing a '<=>' from '==' and '<'). 7368 OverloadCandidateSet CandidateSet( 7369 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7370 OverloadCandidateSet::OperatorRewriteInfo( 7371 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7372 7373 /// C++2a [class.compare.default]p1 [P2002R0]: 7374 /// [...] the defaulted function itself is never a candidate for overload 7375 /// resolution [...] 7376 CandidateSet.exclude(FD); 7377 7378 if (Args[0]->getType()->isOverloadableType()) 7379 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7380 else { 7381 // FIXME: We determine whether this is a valid expression by checking to 7382 // see if there's a viable builtin operator candidate for it. That isn't 7383 // really what the rules ask us to do, but should give the right results. 7384 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7385 } 7386 7387 Result R; 7388 7389 OverloadCandidateSet::iterator Best; 7390 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7391 case OR_Success: { 7392 // C++2a [class.compare.secondary]p2 [P2002R0]: 7393 // The operator function [...] is defined as deleted if [...] the 7394 // candidate selected by overload resolution is not a rewritten 7395 // candidate. 7396 if ((DCK == DefaultedComparisonKind::NotEqual || 7397 DCK == DefaultedComparisonKind::Relational) && 7398 !Best->RewriteKind) { 7399 if (Diagnose == ExplainDeleted) { 7400 S.Diag(Best->Function->getLocation(), 7401 diag::note_defaulted_comparison_not_rewritten_callee) 7402 << FD; 7403 } 7404 return Result::deleted(); 7405 } 7406 7407 // Throughout C++2a [class.compare]: if overload resolution does not 7408 // result in a usable function, the candidate function is defined as 7409 // deleted. This requires that we selected an accessible function. 7410 // 7411 // Note that this only considers the access of the function when named 7412 // within the type of the subobject, and not the access path for any 7413 // derived-to-base conversion. 7414 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7415 if (ArgClass && Best->FoundDecl.getDecl() && 7416 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7417 QualType ObjectType = Subobj.Kind == Subobject::Member 7418 ? Args[0]->getType() 7419 : S.Context.getRecordType(RD); 7420 if (!S.isMemberAccessibleForDeletion( 7421 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7422 Diagnose == ExplainDeleted 7423 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7424 << FD << Subobj.Kind << Subobj.Decl 7425 : S.PDiag())) 7426 return Result::deleted(); 7427 } 7428 7429 // C++2a [class.compare.default]p3 [P2002R0]: 7430 // A defaulted comparison function is constexpr-compatible if [...] 7431 // no overlod resolution performed [...] results in a non-constexpr 7432 // function. 7433 if (FunctionDecl *BestFD = Best->Function) { 7434 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7435 // If it's not constexpr, explain why not. 7436 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7437 if (Subobj.Kind != Subobject::CompleteObject) 7438 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7439 << Subobj.Kind << Subobj.Decl; 7440 S.Diag(BestFD->getLocation(), 7441 diag::note_defaulted_comparison_not_constexpr_here); 7442 // Bail out after explaining; we don't want any more notes. 7443 return Result::deleted(); 7444 } 7445 R.Constexpr &= BestFD->isConstexpr(); 7446 } 7447 7448 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7449 if (auto *BestFD = Best->Function) { 7450 // If any callee has an undeduced return type, deduce it now. 7451 // FIXME: It's not clear how a failure here should be handled. For 7452 // now, we produce an eager diagnostic, because that is forward 7453 // compatible with most (all?) other reasonable options. 7454 if (BestFD->getReturnType()->isUndeducedType() && 7455 S.DeduceReturnType(BestFD, FD->getLocation(), 7456 /*Diagnose=*/false)) { 7457 // Don't produce a duplicate error when asked to explain why the 7458 // comparison is deleted: we diagnosed that when initially checking 7459 // the defaulted operator. 7460 if (Diagnose == NoDiagnostics) { 7461 S.Diag( 7462 FD->getLocation(), 7463 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7464 << Subobj.Kind << Subobj.Decl; 7465 S.Diag( 7466 Subobj.Loc, 7467 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7468 << Subobj.Kind << Subobj.Decl; 7469 S.Diag(BestFD->getLocation(), 7470 diag::note_defaulted_comparison_cannot_deduce_callee) 7471 << Subobj.Kind << Subobj.Decl; 7472 } 7473 return Result::deleted(); 7474 } 7475 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7476 BestFD->getCallResultType())) { 7477 R.Category = Info->Kind; 7478 } else { 7479 if (Diagnose == ExplainDeleted) { 7480 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7481 << Subobj.Kind << Subobj.Decl 7482 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7483 S.Diag(BestFD->getLocation(), 7484 diag::note_defaulted_comparison_cannot_deduce_callee) 7485 << Subobj.Kind << Subobj.Decl; 7486 } 7487 return Result::deleted(); 7488 } 7489 } else { 7490 Optional<ComparisonCategoryType> Cat = 7491 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7492 assert(Cat && "no category for builtin comparison?"); 7493 R.Category = *Cat; 7494 } 7495 } 7496 7497 // Note that we might be rewriting to a different operator. That call is 7498 // not considered until we come to actually build the comparison function. 7499 break; 7500 } 7501 7502 case OR_Ambiguous: 7503 if (Diagnose == ExplainDeleted) { 7504 unsigned Kind = 0; 7505 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7506 Kind = OO == OO_EqualEqual ? 1 : 2; 7507 CandidateSet.NoteCandidates( 7508 PartialDiagnosticAt( 7509 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7510 << FD << Kind << Subobj.Kind << Subobj.Decl), 7511 S, OCD_AmbiguousCandidates, Args); 7512 } 7513 R = Result::deleted(); 7514 break; 7515 7516 case OR_Deleted: 7517 if (Diagnose == ExplainDeleted) { 7518 if ((DCK == DefaultedComparisonKind::NotEqual || 7519 DCK == DefaultedComparisonKind::Relational) && 7520 !Best->RewriteKind) { 7521 S.Diag(Best->Function->getLocation(), 7522 diag::note_defaulted_comparison_not_rewritten_callee) 7523 << FD; 7524 } else { 7525 S.Diag(Subobj.Loc, 7526 diag::note_defaulted_comparison_calls_deleted) 7527 << FD << Subobj.Kind << Subobj.Decl; 7528 S.NoteDeletedFunction(Best->Function); 7529 } 7530 } 7531 R = Result::deleted(); 7532 break; 7533 7534 case OR_No_Viable_Function: 7535 // If there's no usable candidate, we're done unless we can rewrite a 7536 // '<=>' in terms of '==' and '<'. 7537 if (OO == OO_Spaceship && 7538 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7539 // For any kind of comparison category return type, we need a usable 7540 // '==' and a usable '<'. 7541 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7542 &CandidateSet))) 7543 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7544 break; 7545 } 7546 7547 if (Diagnose == ExplainDeleted) { 7548 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7549 << FD << Subobj.Kind << Subobj.Decl; 7550 7551 // For a three-way comparison, list both the candidates for the 7552 // original operator and the candidates for the synthesized operator. 7553 if (SpaceshipCandidates) { 7554 SpaceshipCandidates->NoteCandidates( 7555 S, Args, 7556 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7557 Args, FD->getLocation())); 7558 S.Diag(Subobj.Loc, 7559 diag::note_defaulted_comparison_no_viable_function_synthesized) 7560 << (OO == OO_EqualEqual ? 0 : 1); 7561 } 7562 7563 CandidateSet.NoteCandidates( 7564 S, Args, 7565 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7566 FD->getLocation())); 7567 } 7568 R = Result::deleted(); 7569 break; 7570 } 7571 7572 return R; 7573 } 7574 }; 7575 7576 /// A list of statements. 7577 struct StmtListResult { 7578 bool IsInvalid = false; 7579 llvm::SmallVector<Stmt*, 16> Stmts; 7580 7581 bool add(const StmtResult &S) { 7582 IsInvalid |= S.isInvalid(); 7583 if (IsInvalid) 7584 return true; 7585 Stmts.push_back(S.get()); 7586 return false; 7587 } 7588 }; 7589 7590 /// A visitor over the notional body of a defaulted comparison that synthesizes 7591 /// the actual body. 7592 class DefaultedComparisonSynthesizer 7593 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7594 StmtListResult, StmtResult, 7595 std::pair<ExprResult, ExprResult>> { 7596 SourceLocation Loc; 7597 unsigned ArrayDepth = 0; 7598 7599 public: 7600 using Base = DefaultedComparisonVisitor; 7601 using ExprPair = std::pair<ExprResult, ExprResult>; 7602 7603 friend Base; 7604 7605 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7606 DefaultedComparisonKind DCK, 7607 SourceLocation BodyLoc) 7608 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7609 7610 /// Build a suitable function body for this defaulted comparison operator. 7611 StmtResult build() { 7612 Sema::CompoundScopeRAII CompoundScope(S); 7613 7614 StmtListResult Stmts = visit(); 7615 if (Stmts.IsInvalid) 7616 return StmtError(); 7617 7618 ExprResult RetVal; 7619 switch (DCK) { 7620 case DefaultedComparisonKind::None: 7621 llvm_unreachable("not a defaulted comparison"); 7622 7623 case DefaultedComparisonKind::Equal: { 7624 // C++2a [class.eq]p3: 7625 // [...] compar[e] the corresponding elements [...] until the first 7626 // index i where xi == yi yields [...] false. If no such index exists, 7627 // V is true. Otherwise, V is false. 7628 // 7629 // Join the comparisons with '&&'s and return the result. Use a right 7630 // fold (traversing the conditions right-to-left), because that 7631 // short-circuits more naturally. 7632 auto OldStmts = std::move(Stmts.Stmts); 7633 Stmts.Stmts.clear(); 7634 ExprResult CmpSoFar; 7635 // Finish a particular comparison chain. 7636 auto FinishCmp = [&] { 7637 if (Expr *Prior = CmpSoFar.get()) { 7638 // Convert the last expression to 'return ...;' 7639 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7640 RetVal = CmpSoFar; 7641 // Convert any prior comparison to 'if (!(...)) return false;' 7642 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7643 return true; 7644 CmpSoFar = ExprResult(); 7645 } 7646 return false; 7647 }; 7648 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7649 Expr *E = dyn_cast<Expr>(EAsStmt); 7650 if (!E) { 7651 // Found an array comparison. 7652 if (FinishCmp() || Stmts.add(EAsStmt)) 7653 return StmtError(); 7654 continue; 7655 } 7656 7657 if (CmpSoFar.isUnset()) { 7658 CmpSoFar = E; 7659 continue; 7660 } 7661 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7662 if (CmpSoFar.isInvalid()) 7663 return StmtError(); 7664 } 7665 if (FinishCmp()) 7666 return StmtError(); 7667 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7668 // If no such index exists, V is true. 7669 if (RetVal.isUnset()) 7670 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7671 break; 7672 } 7673 7674 case DefaultedComparisonKind::ThreeWay: { 7675 // Per C++2a [class.spaceship]p3, as a fallback add: 7676 // return static_cast<R>(std::strong_ordering::equal); 7677 QualType StrongOrdering = S.CheckComparisonCategoryType( 7678 ComparisonCategoryType::StrongOrdering, Loc, 7679 Sema::ComparisonCategoryUsage::DefaultedOperator); 7680 if (StrongOrdering.isNull()) 7681 return StmtError(); 7682 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7683 .getValueInfo(ComparisonCategoryResult::Equal) 7684 ->VD; 7685 RetVal = getDecl(EqualVD); 7686 if (RetVal.isInvalid()) 7687 return StmtError(); 7688 RetVal = buildStaticCastToR(RetVal.get()); 7689 break; 7690 } 7691 7692 case DefaultedComparisonKind::NotEqual: 7693 case DefaultedComparisonKind::Relational: 7694 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 7695 break; 7696 } 7697 7698 // Build the final return statement. 7699 if (RetVal.isInvalid()) 7700 return StmtError(); 7701 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 7702 if (ReturnStmt.isInvalid()) 7703 return StmtError(); 7704 Stmts.Stmts.push_back(ReturnStmt.get()); 7705 7706 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 7707 } 7708 7709 private: 7710 ExprResult getDecl(ValueDecl *VD) { 7711 return S.BuildDeclarationNameExpr( 7712 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 7713 } 7714 7715 ExprResult getParam(unsigned I) { 7716 ParmVarDecl *PD = FD->getParamDecl(I); 7717 return getDecl(PD); 7718 } 7719 7720 ExprPair getCompleteObject() { 7721 unsigned Param = 0; 7722 ExprResult LHS; 7723 if (isa<CXXMethodDecl>(FD)) { 7724 // LHS is '*this'. 7725 LHS = S.ActOnCXXThis(Loc); 7726 if (!LHS.isInvalid()) 7727 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 7728 } else { 7729 LHS = getParam(Param++); 7730 } 7731 ExprResult RHS = getParam(Param++); 7732 assert(Param == FD->getNumParams()); 7733 return {LHS, RHS}; 7734 } 7735 7736 ExprPair getBase(CXXBaseSpecifier *Base) { 7737 ExprPair Obj = getCompleteObject(); 7738 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7739 return {ExprError(), ExprError()}; 7740 CXXCastPath Path = {Base}; 7741 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 7742 CK_DerivedToBase, VK_LValue, &Path), 7743 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 7744 CK_DerivedToBase, VK_LValue, &Path)}; 7745 } 7746 7747 ExprPair getField(FieldDecl *Field) { 7748 ExprPair Obj = getCompleteObject(); 7749 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7750 return {ExprError(), ExprError()}; 7751 7752 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 7753 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 7754 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 7755 CXXScopeSpec(), Field, Found, NameInfo), 7756 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 7757 CXXScopeSpec(), Field, Found, NameInfo)}; 7758 } 7759 7760 // FIXME: When expanding a subobject, register a note in the code synthesis 7761 // stack to say which subobject we're comparing. 7762 7763 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 7764 if (Cond.isInvalid()) 7765 return StmtError(); 7766 7767 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 7768 if (NotCond.isInvalid()) 7769 return StmtError(); 7770 7771 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 7772 assert(!False.isInvalid() && "should never fail"); 7773 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 7774 if (ReturnFalse.isInvalid()) 7775 return StmtError(); 7776 7777 return S.ActOnIfStmt(Loc, false, nullptr, 7778 S.ActOnCondition(nullptr, Loc, NotCond.get(), 7779 Sema::ConditionKind::Boolean), 7780 ReturnFalse.get(), SourceLocation(), nullptr); 7781 } 7782 7783 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 7784 ExprPair Subobj) { 7785 QualType SizeType = S.Context.getSizeType(); 7786 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 7787 7788 // Build 'size_t i$n = 0'. 7789 IdentifierInfo *IterationVarName = nullptr; 7790 { 7791 SmallString<8> Str; 7792 llvm::raw_svector_ostream OS(Str); 7793 OS << "i" << ArrayDepth; 7794 IterationVarName = &S.Context.Idents.get(OS.str()); 7795 } 7796 VarDecl *IterationVar = VarDecl::Create( 7797 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 7798 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 7799 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7800 IterationVar->setInit( 7801 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7802 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 7803 7804 auto IterRef = [&] { 7805 ExprResult Ref = S.BuildDeclarationNameExpr( 7806 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 7807 IterationVar); 7808 assert(!Ref.isInvalid() && "can't reference our own variable?"); 7809 return Ref.get(); 7810 }; 7811 7812 // Build 'i$n != Size'. 7813 ExprResult Cond = S.CreateBuiltinBinOp( 7814 Loc, BO_NE, IterRef(), 7815 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 7816 assert(!Cond.isInvalid() && "should never fail"); 7817 7818 // Build '++i$n'. 7819 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 7820 assert(!Inc.isInvalid() && "should never fail"); 7821 7822 // Build 'a[i$n]' and 'b[i$n]'. 7823 auto Index = [&](ExprResult E) { 7824 if (E.isInvalid()) 7825 return ExprError(); 7826 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 7827 }; 7828 Subobj.first = Index(Subobj.first); 7829 Subobj.second = Index(Subobj.second); 7830 7831 // Compare the array elements. 7832 ++ArrayDepth; 7833 StmtResult Substmt = visitSubobject(Type, Subobj); 7834 --ArrayDepth; 7835 7836 if (Substmt.isInvalid()) 7837 return StmtError(); 7838 7839 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 7840 // For outer levels or for an 'operator<=>' we already have a suitable 7841 // statement that returns as necessary. 7842 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 7843 assert(DCK == DefaultedComparisonKind::Equal && 7844 "should have non-expression statement"); 7845 Substmt = buildIfNotCondReturnFalse(ElemCmp); 7846 if (Substmt.isInvalid()) 7847 return StmtError(); 7848 } 7849 7850 // Build 'for (...) ...' 7851 return S.ActOnForStmt(Loc, Loc, Init, 7852 S.ActOnCondition(nullptr, Loc, Cond.get(), 7853 Sema::ConditionKind::Boolean), 7854 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 7855 Substmt.get()); 7856 } 7857 7858 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 7859 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7860 return StmtError(); 7861 7862 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7863 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 7864 ExprResult Op; 7865 if (Type->isOverloadableType()) 7866 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 7867 Obj.second.get(), /*PerformADL=*/true, 7868 /*AllowRewrittenCandidates=*/true, FD); 7869 else 7870 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 7871 if (Op.isInvalid()) 7872 return StmtError(); 7873 7874 switch (DCK) { 7875 case DefaultedComparisonKind::None: 7876 llvm_unreachable("not a defaulted comparison"); 7877 7878 case DefaultedComparisonKind::Equal: 7879 // Per C++2a [class.eq]p2, each comparison is individually contextually 7880 // converted to bool. 7881 Op = S.PerformContextuallyConvertToBool(Op.get()); 7882 if (Op.isInvalid()) 7883 return StmtError(); 7884 return Op.get(); 7885 7886 case DefaultedComparisonKind::ThreeWay: { 7887 // Per C++2a [class.spaceship]p3, form: 7888 // if (R cmp = static_cast<R>(op); cmp != 0) 7889 // return cmp; 7890 QualType R = FD->getReturnType(); 7891 Op = buildStaticCastToR(Op.get()); 7892 if (Op.isInvalid()) 7893 return StmtError(); 7894 7895 // R cmp = ...; 7896 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 7897 VarDecl *VD = 7898 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 7899 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 7900 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 7901 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 7902 7903 // cmp != 0 7904 ExprResult VDRef = getDecl(VD); 7905 if (VDRef.isInvalid()) 7906 return StmtError(); 7907 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 7908 Expr *Zero = 7909 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 7910 ExprResult Comp; 7911 if (VDRef.get()->getType()->isOverloadableType()) 7912 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 7913 true, FD); 7914 else 7915 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 7916 if (Comp.isInvalid()) 7917 return StmtError(); 7918 Sema::ConditionResult Cond = S.ActOnCondition( 7919 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 7920 if (Cond.isInvalid()) 7921 return StmtError(); 7922 7923 // return cmp; 7924 VDRef = getDecl(VD); 7925 if (VDRef.isInvalid()) 7926 return StmtError(); 7927 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 7928 if (ReturnStmt.isInvalid()) 7929 return StmtError(); 7930 7931 // if (...) 7932 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond, 7933 ReturnStmt.get(), /*ElseLoc=*/SourceLocation(), 7934 /*Else=*/nullptr); 7935 } 7936 7937 case DefaultedComparisonKind::NotEqual: 7938 case DefaultedComparisonKind::Relational: 7939 // C++2a [class.compare.secondary]p2: 7940 // Otherwise, the operator function yields x @ y. 7941 return Op.get(); 7942 } 7943 llvm_unreachable(""); 7944 } 7945 7946 /// Build "static_cast<R>(E)". 7947 ExprResult buildStaticCastToR(Expr *E) { 7948 QualType R = FD->getReturnType(); 7949 assert(!R->isUndeducedType() && "type should have been deduced already"); 7950 7951 // Don't bother forming a no-op cast in the common case. 7952 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 7953 return E; 7954 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 7955 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 7956 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 7957 } 7958 }; 7959 } 7960 7961 /// Perform the unqualified lookups that might be needed to form a defaulted 7962 /// comparison function for the given operator. 7963 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 7964 UnresolvedSetImpl &Operators, 7965 OverloadedOperatorKind Op) { 7966 auto Lookup = [&](OverloadedOperatorKind OO) { 7967 Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators); 7968 }; 7969 7970 // Every defaulted operator looks up itself. 7971 Lookup(Op); 7972 // ... and the rewritten form of itself, if any. 7973 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 7974 Lookup(ExtraOp); 7975 7976 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 7977 // synthesize a three-way comparison from '<' and '=='. In a dependent 7978 // context, we also need to look up '==' in case we implicitly declare a 7979 // defaulted 'operator=='. 7980 if (Op == OO_Spaceship) { 7981 Lookup(OO_ExclaimEqual); 7982 Lookup(OO_Less); 7983 Lookup(OO_EqualEqual); 7984 } 7985 } 7986 7987 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 7988 DefaultedComparisonKind DCK) { 7989 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 7990 7991 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 7992 assert(RD && "defaulted comparison is not defaulted in a class"); 7993 7994 // Perform any unqualified lookups we're going to need to default this 7995 // function. 7996 if (S) { 7997 UnresolvedSet<32> Operators; 7998 lookupOperatorsForDefaultedComparison(*this, S, Operators, 7999 FD->getOverloadedOperator()); 8000 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8001 Context, Operators.pairs())); 8002 } 8003 8004 // C++2a [class.compare.default]p1: 8005 // A defaulted comparison operator function for some class C shall be a 8006 // non-template function declared in the member-specification of C that is 8007 // -- a non-static const member of C having one parameter of type 8008 // const C&, or 8009 // -- a friend of C having two parameters of type const C& or two 8010 // parameters of type C. 8011 QualType ExpectedParmType1 = Context.getRecordType(RD); 8012 QualType ExpectedParmType2 = 8013 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8014 if (isa<CXXMethodDecl>(FD)) 8015 ExpectedParmType1 = ExpectedParmType2; 8016 for (const ParmVarDecl *Param : FD->parameters()) { 8017 if (!Param->getType()->isDependentType() && 8018 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8019 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8020 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8021 // corresponding defaulted 'operator<=>' already. 8022 if (!FD->isImplicit()) { 8023 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8024 << (int)DCK << Param->getType() << ExpectedParmType1 8025 << !isa<CXXMethodDecl>(FD) 8026 << ExpectedParmType2 << Param->getSourceRange(); 8027 } 8028 return true; 8029 } 8030 } 8031 if (FD->getNumParams() == 2 && 8032 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8033 FD->getParamDecl(1)->getType())) { 8034 if (!FD->isImplicit()) { 8035 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8036 << (int)DCK 8037 << FD->getParamDecl(0)->getType() 8038 << FD->getParamDecl(0)->getSourceRange() 8039 << FD->getParamDecl(1)->getType() 8040 << FD->getParamDecl(1)->getSourceRange(); 8041 } 8042 return true; 8043 } 8044 8045 // ... non-static const member ... 8046 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8047 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8048 if (!MD->isConst()) { 8049 SourceLocation InsertLoc; 8050 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8051 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8052 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8053 // corresponding defaulted 'operator<=>' already. 8054 if (!MD->isImplicit()) { 8055 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8056 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8057 } 8058 8059 // Add the 'const' to the type to recover. 8060 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8061 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8062 EPI.TypeQuals.addConst(); 8063 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8064 FPT->getParamTypes(), EPI)); 8065 } 8066 } else { 8067 // A non-member function declared in a class must be a friend. 8068 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8069 } 8070 8071 // C++2a [class.eq]p1, [class.rel]p1: 8072 // A [defaulted comparison other than <=>] shall have a declared return 8073 // type bool. 8074 if (DCK != DefaultedComparisonKind::ThreeWay && 8075 !FD->getDeclaredReturnType()->isDependentType() && 8076 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8077 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8078 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8079 << FD->getReturnTypeSourceRange(); 8080 return true; 8081 } 8082 // C++2a [class.spaceship]p2 [P2002R0]: 8083 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8084 // R shall not contain a placeholder type. 8085 if (DCK == DefaultedComparisonKind::ThreeWay && 8086 FD->getDeclaredReturnType()->getContainedDeducedType() && 8087 !Context.hasSameType(FD->getDeclaredReturnType(), 8088 Context.getAutoDeductType())) { 8089 Diag(FD->getLocation(), 8090 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8091 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8092 << FD->getReturnTypeSourceRange(); 8093 return true; 8094 } 8095 8096 // For a defaulted function in a dependent class, defer all remaining checks 8097 // until instantiation. 8098 if (RD->isDependentType()) 8099 return false; 8100 8101 // Determine whether the function should be defined as deleted. 8102 DefaultedComparisonInfo Info = 8103 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8104 8105 bool First = FD == FD->getCanonicalDecl(); 8106 8107 // If we want to delete the function, then do so; there's nothing else to 8108 // check in that case. 8109 if (Info.Deleted) { 8110 if (!First) { 8111 // C++11 [dcl.fct.def.default]p4: 8112 // [For a] user-provided explicitly-defaulted function [...] if such a 8113 // function is implicitly defined as deleted, the program is ill-formed. 8114 // 8115 // This is really just a consequence of the general rule that you can 8116 // only delete a function on its first declaration. 8117 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8118 << FD->isImplicit() << (int)DCK; 8119 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8120 DefaultedComparisonAnalyzer::ExplainDeleted) 8121 .visit(); 8122 return true; 8123 } 8124 8125 SetDeclDeleted(FD, FD->getLocation()); 8126 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8127 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8128 << (int)DCK; 8129 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8130 DefaultedComparisonAnalyzer::ExplainDeleted) 8131 .visit(); 8132 } 8133 return false; 8134 } 8135 8136 // C++2a [class.spaceship]p2: 8137 // The return type is deduced as the common comparison type of R0, R1, ... 8138 if (DCK == DefaultedComparisonKind::ThreeWay && 8139 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8140 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8141 if (RetLoc.isInvalid()) 8142 RetLoc = FD->getBeginLoc(); 8143 // FIXME: Should we really care whether we have the complete type and the 8144 // 'enumerator' constants here? A forward declaration seems sufficient. 8145 QualType Cat = CheckComparisonCategoryType( 8146 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8147 if (Cat.isNull()) 8148 return true; 8149 Context.adjustDeducedFunctionResultType( 8150 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8151 } 8152 8153 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8154 // An explicitly-defaulted function that is not defined as deleted may be 8155 // declared constexpr or consteval only if it is constexpr-compatible. 8156 // C++2a [class.compare.default]p3 [P2002R0]: 8157 // A defaulted comparison function is constexpr-compatible if it satisfies 8158 // the requirements for a constexpr function [...] 8159 // The only relevant requirements are that the parameter and return types are 8160 // literal types. The remaining conditions are checked by the analyzer. 8161 if (FD->isConstexpr()) { 8162 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8163 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8164 !Info.Constexpr) { 8165 Diag(FD->getBeginLoc(), 8166 diag::err_incorrect_defaulted_comparison_constexpr) 8167 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8168 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8169 DefaultedComparisonAnalyzer::ExplainConstexpr) 8170 .visit(); 8171 } 8172 } 8173 8174 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8175 // If a constexpr-compatible function is explicitly defaulted on its first 8176 // declaration, it is implicitly considered to be constexpr. 8177 // FIXME: Only applying this to the first declaration seems problematic, as 8178 // simple reorderings can affect the meaning of the program. 8179 if (First && !FD->isConstexpr() && Info.Constexpr) 8180 FD->setConstexprKind(CSK_constexpr); 8181 8182 // C++2a [except.spec]p3: 8183 // If a declaration of a function does not have a noexcept-specifier 8184 // [and] is defaulted on its first declaration, [...] the exception 8185 // specification is as specified below 8186 if (FD->getExceptionSpecType() == EST_None) { 8187 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8188 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8189 EPI.ExceptionSpec.Type = EST_Unevaluated; 8190 EPI.ExceptionSpec.SourceDecl = FD; 8191 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8192 FPT->getParamTypes(), EPI)); 8193 } 8194 8195 return false; 8196 } 8197 8198 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8199 FunctionDecl *Spaceship) { 8200 Sema::CodeSynthesisContext Ctx; 8201 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8202 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8203 Ctx.Entity = Spaceship; 8204 pushCodeSynthesisContext(Ctx); 8205 8206 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8207 EqualEqual->setImplicit(); 8208 8209 popCodeSynthesisContext(); 8210 } 8211 8212 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8213 DefaultedComparisonKind DCK) { 8214 assert(FD->isDefaulted() && !FD->isDeleted() && 8215 !FD->doesThisDeclarationHaveABody()); 8216 if (FD->willHaveBody() || FD->isInvalidDecl()) 8217 return; 8218 8219 SynthesizedFunctionScope Scope(*this, FD); 8220 8221 // Add a context note for diagnostics produced after this point. 8222 Scope.addContextNote(UseLoc); 8223 8224 { 8225 // Build and set up the function body. 8226 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8227 SourceLocation BodyLoc = 8228 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8229 StmtResult Body = 8230 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8231 if (Body.isInvalid()) { 8232 FD->setInvalidDecl(); 8233 return; 8234 } 8235 FD->setBody(Body.get()); 8236 FD->markUsed(Context); 8237 } 8238 8239 // The exception specification is needed because we are defining the 8240 // function. Note that this will reuse the body we just built. 8241 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8242 8243 if (ASTMutationListener *L = getASTMutationListener()) 8244 L->CompletedImplicitDefinition(FD); 8245 } 8246 8247 static Sema::ImplicitExceptionSpecification 8248 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8249 FunctionDecl *FD, 8250 Sema::DefaultedComparisonKind DCK) { 8251 ComputingExceptionSpec CES(S, FD, Loc); 8252 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8253 8254 if (FD->isInvalidDecl()) 8255 return ExceptSpec; 8256 8257 // The common case is that we just defined the comparison function. In that 8258 // case, just look at whether the body can throw. 8259 if (FD->hasBody()) { 8260 ExceptSpec.CalledStmt(FD->getBody()); 8261 } else { 8262 // Otherwise, build a body so we can check it. This should ideally only 8263 // happen when we're not actually marking the function referenced. (This is 8264 // only really important for efficiency: we don't want to build and throw 8265 // away bodies for comparison functions more than we strictly need to.) 8266 8267 // Pretend to synthesize the function body in an unevaluated context. 8268 // Note that we can't actually just go ahead and define the function here: 8269 // we are not permitted to mark its callees as referenced. 8270 Sema::SynthesizedFunctionScope Scope(S, FD); 8271 EnterExpressionEvaluationContext Context( 8272 S, Sema::ExpressionEvaluationContext::Unevaluated); 8273 8274 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8275 SourceLocation BodyLoc = 8276 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8277 StmtResult Body = 8278 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8279 if (!Body.isInvalid()) 8280 ExceptSpec.CalledStmt(Body.get()); 8281 8282 // FIXME: Can we hold onto this body and just transform it to potentially 8283 // evaluated when we're asked to define the function rather than rebuilding 8284 // it? Either that, or we should only build the bits of the body that we 8285 // need (the expressions, not the statements). 8286 } 8287 8288 return ExceptSpec; 8289 } 8290 8291 void Sema::CheckDelayedMemberExceptionSpecs() { 8292 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8293 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8294 8295 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8296 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8297 8298 // Perform any deferred checking of exception specifications for virtual 8299 // destructors. 8300 for (auto &Check : Overriding) 8301 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8302 8303 // Perform any deferred checking of exception specifications for befriended 8304 // special members. 8305 for (auto &Check : Equivalent) 8306 CheckEquivalentExceptionSpec(Check.second, Check.first); 8307 } 8308 8309 namespace { 8310 /// CRTP base class for visiting operations performed by a special member 8311 /// function (or inherited constructor). 8312 template<typename Derived> 8313 struct SpecialMemberVisitor { 8314 Sema &S; 8315 CXXMethodDecl *MD; 8316 Sema::CXXSpecialMember CSM; 8317 Sema::InheritedConstructorInfo *ICI; 8318 8319 // Properties of the special member, computed for convenience. 8320 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8321 8322 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8323 Sema::InheritedConstructorInfo *ICI) 8324 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8325 switch (CSM) { 8326 case Sema::CXXDefaultConstructor: 8327 case Sema::CXXCopyConstructor: 8328 case Sema::CXXMoveConstructor: 8329 IsConstructor = true; 8330 break; 8331 case Sema::CXXCopyAssignment: 8332 case Sema::CXXMoveAssignment: 8333 IsAssignment = true; 8334 break; 8335 case Sema::CXXDestructor: 8336 break; 8337 case Sema::CXXInvalid: 8338 llvm_unreachable("invalid special member kind"); 8339 } 8340 8341 if (MD->getNumParams()) { 8342 if (const ReferenceType *RT = 8343 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8344 ConstArg = RT->getPointeeType().isConstQualified(); 8345 } 8346 } 8347 8348 Derived &getDerived() { return static_cast<Derived&>(*this); } 8349 8350 /// Is this a "move" special member? 8351 bool isMove() const { 8352 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8353 } 8354 8355 /// Look up the corresponding special member in the given class. 8356 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8357 unsigned Quals, bool IsMutable) { 8358 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8359 ConstArg && !IsMutable); 8360 } 8361 8362 /// Look up the constructor for the specified base class to see if it's 8363 /// overridden due to this being an inherited constructor. 8364 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8365 if (!ICI) 8366 return {}; 8367 assert(CSM == Sema::CXXDefaultConstructor); 8368 auto *BaseCtor = 8369 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8370 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8371 return MD; 8372 return {}; 8373 } 8374 8375 /// A base or member subobject. 8376 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8377 8378 /// Get the location to use for a subobject in diagnostics. 8379 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8380 // FIXME: For an indirect virtual base, the direct base leading to 8381 // the indirect virtual base would be a more useful choice. 8382 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8383 return B->getBaseTypeLoc(); 8384 else 8385 return Subobj.get<FieldDecl*>()->getLocation(); 8386 } 8387 8388 enum BasesToVisit { 8389 /// Visit all non-virtual (direct) bases. 8390 VisitNonVirtualBases, 8391 /// Visit all direct bases, virtual or not. 8392 VisitDirectBases, 8393 /// Visit all non-virtual bases, and all virtual bases if the class 8394 /// is not abstract. 8395 VisitPotentiallyConstructedBases, 8396 /// Visit all direct or virtual bases. 8397 VisitAllBases 8398 }; 8399 8400 // Visit the bases and members of the class. 8401 bool visit(BasesToVisit Bases) { 8402 CXXRecordDecl *RD = MD->getParent(); 8403 8404 if (Bases == VisitPotentiallyConstructedBases) 8405 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8406 8407 for (auto &B : RD->bases()) 8408 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8409 getDerived().visitBase(&B)) 8410 return true; 8411 8412 if (Bases == VisitAllBases) 8413 for (auto &B : RD->vbases()) 8414 if (getDerived().visitBase(&B)) 8415 return true; 8416 8417 for (auto *F : RD->fields()) 8418 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8419 getDerived().visitField(F)) 8420 return true; 8421 8422 return false; 8423 } 8424 }; 8425 } 8426 8427 namespace { 8428 struct SpecialMemberDeletionInfo 8429 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8430 bool Diagnose; 8431 8432 SourceLocation Loc; 8433 8434 bool AllFieldsAreConst; 8435 8436 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8437 Sema::CXXSpecialMember CSM, 8438 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8439 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8440 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8441 8442 bool inUnion() const { return MD->getParent()->isUnion(); } 8443 8444 Sema::CXXSpecialMember getEffectiveCSM() { 8445 return ICI ? Sema::CXXInvalid : CSM; 8446 } 8447 8448 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8449 8450 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8451 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8452 8453 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8454 bool shouldDeleteForField(FieldDecl *FD); 8455 bool shouldDeleteForAllConstMembers(); 8456 8457 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8458 unsigned Quals); 8459 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8460 Sema::SpecialMemberOverloadResult SMOR, 8461 bool IsDtorCallInCtor); 8462 8463 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8464 }; 8465 } 8466 8467 /// Is the given special member inaccessible when used on the given 8468 /// sub-object. 8469 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8470 CXXMethodDecl *target) { 8471 /// If we're operating on a base class, the object type is the 8472 /// type of this special member. 8473 QualType objectTy; 8474 AccessSpecifier access = target->getAccess(); 8475 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8476 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8477 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8478 8479 // If we're operating on a field, the object type is the type of the field. 8480 } else { 8481 objectTy = S.Context.getTypeDeclType(target->getParent()); 8482 } 8483 8484 return S.isMemberAccessibleForDeletion( 8485 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8486 } 8487 8488 /// Check whether we should delete a special member due to the implicit 8489 /// definition containing a call to a special member of a subobject. 8490 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8491 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8492 bool IsDtorCallInCtor) { 8493 CXXMethodDecl *Decl = SMOR.getMethod(); 8494 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8495 8496 int DiagKind = -1; 8497 8498 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8499 DiagKind = !Decl ? 0 : 1; 8500 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8501 DiagKind = 2; 8502 else if (!isAccessible(Subobj, Decl)) 8503 DiagKind = 3; 8504 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8505 !Decl->isTrivial()) { 8506 // A member of a union must have a trivial corresponding special member. 8507 // As a weird special case, a destructor call from a union's constructor 8508 // must be accessible and non-deleted, but need not be trivial. Such a 8509 // destructor is never actually called, but is semantically checked as 8510 // if it were. 8511 DiagKind = 4; 8512 } 8513 8514 if (DiagKind == -1) 8515 return false; 8516 8517 if (Diagnose) { 8518 if (Field) { 8519 S.Diag(Field->getLocation(), 8520 diag::note_deleted_special_member_class_subobject) 8521 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8522 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8523 } else { 8524 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8525 S.Diag(Base->getBeginLoc(), 8526 diag::note_deleted_special_member_class_subobject) 8527 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8528 << Base->getType() << DiagKind << IsDtorCallInCtor 8529 << /*IsObjCPtr*/false; 8530 } 8531 8532 if (DiagKind == 1) 8533 S.NoteDeletedFunction(Decl); 8534 // FIXME: Explain inaccessibility if DiagKind == 3. 8535 } 8536 8537 return true; 8538 } 8539 8540 /// Check whether we should delete a special member function due to having a 8541 /// direct or virtual base class or non-static data member of class type M. 8542 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8543 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8544 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8545 bool IsMutable = Field && Field->isMutable(); 8546 8547 // C++11 [class.ctor]p5: 8548 // -- any direct or virtual base class, or non-static data member with no 8549 // brace-or-equal-initializer, has class type M (or array thereof) and 8550 // either M has no default constructor or overload resolution as applied 8551 // to M's default constructor results in an ambiguity or in a function 8552 // that is deleted or inaccessible 8553 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8554 // -- a direct or virtual base class B that cannot be copied/moved because 8555 // overload resolution, as applied to B's corresponding special member, 8556 // results in an ambiguity or a function that is deleted or inaccessible 8557 // from the defaulted special member 8558 // C++11 [class.dtor]p5: 8559 // -- any direct or virtual base class [...] has a type with a destructor 8560 // that is deleted or inaccessible 8561 if (!(CSM == Sema::CXXDefaultConstructor && 8562 Field && Field->hasInClassInitializer()) && 8563 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8564 false)) 8565 return true; 8566 8567 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8568 // -- any direct or virtual base class or non-static data member has a 8569 // type with a destructor that is deleted or inaccessible 8570 if (IsConstructor) { 8571 Sema::SpecialMemberOverloadResult SMOR = 8572 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8573 false, false, false, false, false); 8574 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8575 return true; 8576 } 8577 8578 return false; 8579 } 8580 8581 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8582 FieldDecl *FD, QualType FieldType) { 8583 // The defaulted special functions are defined as deleted if this is a variant 8584 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8585 // type under ARC. 8586 if (!FieldType.hasNonTrivialObjCLifetime()) 8587 return false; 8588 8589 // Don't make the defaulted default constructor defined as deleted if the 8590 // member has an in-class initializer. 8591 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8592 return false; 8593 8594 if (Diagnose) { 8595 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8596 S.Diag(FD->getLocation(), 8597 diag::note_deleted_special_member_class_subobject) 8598 << getEffectiveCSM() << ParentClass << /*IsField*/true 8599 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8600 } 8601 8602 return true; 8603 } 8604 8605 /// Check whether we should delete a special member function due to the class 8606 /// having a particular direct or virtual base class. 8607 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8608 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8609 // If program is correct, BaseClass cannot be null, but if it is, the error 8610 // must be reported elsewhere. 8611 if (!BaseClass) 8612 return false; 8613 // If we have an inheriting constructor, check whether we're calling an 8614 // inherited constructor instead of a default constructor. 8615 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8616 if (auto *BaseCtor = SMOR.getMethod()) { 8617 // Note that we do not check access along this path; other than that, 8618 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8619 // FIXME: Check that the base has a usable destructor! Sink this into 8620 // shouldDeleteForClassSubobject. 8621 if (BaseCtor->isDeleted() && Diagnose) { 8622 S.Diag(Base->getBeginLoc(), 8623 diag::note_deleted_special_member_class_subobject) 8624 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8625 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8626 << /*IsObjCPtr*/false; 8627 S.NoteDeletedFunction(BaseCtor); 8628 } 8629 return BaseCtor->isDeleted(); 8630 } 8631 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8632 } 8633 8634 /// Check whether we should delete a special member function due to the class 8635 /// having a particular non-static data member. 8636 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8637 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8638 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8639 8640 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8641 return true; 8642 8643 if (CSM == Sema::CXXDefaultConstructor) { 8644 // For a default constructor, all references must be initialized in-class 8645 // and, if a union, it must have a non-const member. 8646 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8647 if (Diagnose) 8648 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8649 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8650 return true; 8651 } 8652 // C++11 [class.ctor]p5: any non-variant non-static data member of 8653 // const-qualified type (or array thereof) with no 8654 // brace-or-equal-initializer does not have a user-provided default 8655 // constructor. 8656 if (!inUnion() && FieldType.isConstQualified() && 8657 !FD->hasInClassInitializer() && 8658 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8659 if (Diagnose) 8660 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8661 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8662 return true; 8663 } 8664 8665 if (inUnion() && !FieldType.isConstQualified()) 8666 AllFieldsAreConst = false; 8667 } else if (CSM == Sema::CXXCopyConstructor) { 8668 // For a copy constructor, data members must not be of rvalue reference 8669 // type. 8670 if (FieldType->isRValueReferenceType()) { 8671 if (Diagnose) 8672 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8673 << MD->getParent() << FD << FieldType; 8674 return true; 8675 } 8676 } else if (IsAssignment) { 8677 // For an assignment operator, data members must not be of reference type. 8678 if (FieldType->isReferenceType()) { 8679 if (Diagnose) 8680 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8681 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8682 return true; 8683 } 8684 if (!FieldRecord && FieldType.isConstQualified()) { 8685 // C++11 [class.copy]p23: 8686 // -- a non-static data member of const non-class type (or array thereof) 8687 if (Diagnose) 8688 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8689 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8690 return true; 8691 } 8692 } 8693 8694 if (FieldRecord) { 8695 // Some additional restrictions exist on the variant members. 8696 if (!inUnion() && FieldRecord->isUnion() && 8697 FieldRecord->isAnonymousStructOrUnion()) { 8698 bool AllVariantFieldsAreConst = true; 8699 8700 // FIXME: Handle anonymous unions declared within anonymous unions. 8701 for (auto *UI : FieldRecord->fields()) { 8702 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 8703 8704 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 8705 return true; 8706 8707 if (!UnionFieldType.isConstQualified()) 8708 AllVariantFieldsAreConst = false; 8709 8710 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 8711 if (UnionFieldRecord && 8712 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 8713 UnionFieldType.getCVRQualifiers())) 8714 return true; 8715 } 8716 8717 // At least one member in each anonymous union must be non-const 8718 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 8719 !FieldRecord->field_empty()) { 8720 if (Diagnose) 8721 S.Diag(FieldRecord->getLocation(), 8722 diag::note_deleted_default_ctor_all_const) 8723 << !!ICI << MD->getParent() << /*anonymous union*/1; 8724 return true; 8725 } 8726 8727 // Don't check the implicit member of the anonymous union type. 8728 // This is technically non-conformant, but sanity demands it. 8729 return false; 8730 } 8731 8732 if (shouldDeleteForClassSubobject(FieldRecord, FD, 8733 FieldType.getCVRQualifiers())) 8734 return true; 8735 } 8736 8737 return false; 8738 } 8739 8740 /// C++11 [class.ctor] p5: 8741 /// A defaulted default constructor for a class X is defined as deleted if 8742 /// X is a union and all of its variant members are of const-qualified type. 8743 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 8744 // This is a silly definition, because it gives an empty union a deleted 8745 // default constructor. Don't do that. 8746 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 8747 bool AnyFields = false; 8748 for (auto *F : MD->getParent()->fields()) 8749 if ((AnyFields = !F->isUnnamedBitfield())) 8750 break; 8751 if (!AnyFields) 8752 return false; 8753 if (Diagnose) 8754 S.Diag(MD->getParent()->getLocation(), 8755 diag::note_deleted_default_ctor_all_const) 8756 << !!ICI << MD->getParent() << /*not anonymous union*/0; 8757 return true; 8758 } 8759 return false; 8760 } 8761 8762 /// Determine whether a defaulted special member function should be defined as 8763 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 8764 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 8765 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 8766 InheritedConstructorInfo *ICI, 8767 bool Diagnose) { 8768 if (MD->isInvalidDecl()) 8769 return false; 8770 CXXRecordDecl *RD = MD->getParent(); 8771 assert(!RD->isDependentType() && "do deletion after instantiation"); 8772 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 8773 return false; 8774 8775 // C++11 [expr.lambda.prim]p19: 8776 // The closure type associated with a lambda-expression has a 8777 // deleted (8.4.3) default constructor and a deleted copy 8778 // assignment operator. 8779 // C++2a adds back these operators if the lambda has no lambda-capture. 8780 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 8781 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 8782 if (Diagnose) 8783 Diag(RD->getLocation(), diag::note_lambda_decl); 8784 return true; 8785 } 8786 8787 // For an anonymous struct or union, the copy and assignment special members 8788 // will never be used, so skip the check. For an anonymous union declared at 8789 // namespace scope, the constructor and destructor are used. 8790 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 8791 RD->isAnonymousStructOrUnion()) 8792 return false; 8793 8794 // C++11 [class.copy]p7, p18: 8795 // If the class definition declares a move constructor or move assignment 8796 // operator, an implicitly declared copy constructor or copy assignment 8797 // operator is defined as deleted. 8798 if (MD->isImplicit() && 8799 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 8800 CXXMethodDecl *UserDeclaredMove = nullptr; 8801 8802 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 8803 // deletion of the corresponding copy operation, not both copy operations. 8804 // MSVC 2015 has adopted the standards conforming behavior. 8805 bool DeletesOnlyMatchingCopy = 8806 getLangOpts().MSVCCompat && 8807 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 8808 8809 if (RD->hasUserDeclaredMoveConstructor() && 8810 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 8811 if (!Diagnose) return true; 8812 8813 // Find any user-declared move constructor. 8814 for (auto *I : RD->ctors()) { 8815 if (I->isMoveConstructor()) { 8816 UserDeclaredMove = I; 8817 break; 8818 } 8819 } 8820 assert(UserDeclaredMove); 8821 } else if (RD->hasUserDeclaredMoveAssignment() && 8822 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 8823 if (!Diagnose) return true; 8824 8825 // Find any user-declared move assignment operator. 8826 for (auto *I : RD->methods()) { 8827 if (I->isMoveAssignmentOperator()) { 8828 UserDeclaredMove = I; 8829 break; 8830 } 8831 } 8832 assert(UserDeclaredMove); 8833 } 8834 8835 if (UserDeclaredMove) { 8836 Diag(UserDeclaredMove->getLocation(), 8837 diag::note_deleted_copy_user_declared_move) 8838 << (CSM == CXXCopyAssignment) << RD 8839 << UserDeclaredMove->isMoveAssignmentOperator(); 8840 return true; 8841 } 8842 } 8843 8844 // Do access control from the special member function 8845 ContextRAII MethodContext(*this, MD); 8846 8847 // C++11 [class.dtor]p5: 8848 // -- for a virtual destructor, lookup of the non-array deallocation function 8849 // results in an ambiguity or in a function that is deleted or inaccessible 8850 if (CSM == CXXDestructor && MD->isVirtual()) { 8851 FunctionDecl *OperatorDelete = nullptr; 8852 DeclarationName Name = 8853 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 8854 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 8855 OperatorDelete, /*Diagnose*/false)) { 8856 if (Diagnose) 8857 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 8858 return true; 8859 } 8860 } 8861 8862 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 8863 8864 // Per DR1611, do not consider virtual bases of constructors of abstract 8865 // classes, since we are not going to construct them. 8866 // Per DR1658, do not consider virtual bases of destructors of abstract 8867 // classes either. 8868 // Per DR2180, for assignment operators we only assign (and thus only 8869 // consider) direct bases. 8870 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 8871 : SMI.VisitPotentiallyConstructedBases)) 8872 return true; 8873 8874 if (SMI.shouldDeleteForAllConstMembers()) 8875 return true; 8876 8877 if (getLangOpts().CUDA) { 8878 // We should delete the special member in CUDA mode if target inference 8879 // failed. 8880 // For inherited constructors (non-null ICI), CSM may be passed so that MD 8881 // is treated as certain special member, which may not reflect what special 8882 // member MD really is. However inferCUDATargetForImplicitSpecialMember 8883 // expects CSM to match MD, therefore recalculate CSM. 8884 assert(ICI || CSM == getSpecialMember(MD)); 8885 auto RealCSM = CSM; 8886 if (ICI) 8887 RealCSM = getSpecialMember(MD); 8888 8889 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 8890 SMI.ConstArg, Diagnose); 8891 } 8892 8893 return false; 8894 } 8895 8896 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 8897 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 8898 assert(DFK && "not a defaultable function"); 8899 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 8900 8901 if (DFK.isSpecialMember()) { 8902 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 8903 nullptr, /*Diagnose=*/true); 8904 } else { 8905 DefaultedComparisonAnalyzer( 8906 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 8907 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 8908 .visit(); 8909 } 8910 } 8911 8912 /// Perform lookup for a special member of the specified kind, and determine 8913 /// whether it is trivial. If the triviality can be determined without the 8914 /// lookup, skip it. This is intended for use when determining whether a 8915 /// special member of a containing object is trivial, and thus does not ever 8916 /// perform overload resolution for default constructors. 8917 /// 8918 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 8919 /// member that was most likely to be intended to be trivial, if any. 8920 /// 8921 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 8922 /// determine whether the special member is trivial. 8923 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 8924 Sema::CXXSpecialMember CSM, unsigned Quals, 8925 bool ConstRHS, 8926 Sema::TrivialABIHandling TAH, 8927 CXXMethodDecl **Selected) { 8928 if (Selected) 8929 *Selected = nullptr; 8930 8931 switch (CSM) { 8932 case Sema::CXXInvalid: 8933 llvm_unreachable("not a special member"); 8934 8935 case Sema::CXXDefaultConstructor: 8936 // C++11 [class.ctor]p5: 8937 // A default constructor is trivial if: 8938 // - all the [direct subobjects] have trivial default constructors 8939 // 8940 // Note, no overload resolution is performed in this case. 8941 if (RD->hasTrivialDefaultConstructor()) 8942 return true; 8943 8944 if (Selected) { 8945 // If there's a default constructor which could have been trivial, dig it 8946 // out. Otherwise, if there's any user-provided default constructor, point 8947 // to that as an example of why there's not a trivial one. 8948 CXXConstructorDecl *DefCtor = nullptr; 8949 if (RD->needsImplicitDefaultConstructor()) 8950 S.DeclareImplicitDefaultConstructor(RD); 8951 for (auto *CI : RD->ctors()) { 8952 if (!CI->isDefaultConstructor()) 8953 continue; 8954 DefCtor = CI; 8955 if (!DefCtor->isUserProvided()) 8956 break; 8957 } 8958 8959 *Selected = DefCtor; 8960 } 8961 8962 return false; 8963 8964 case Sema::CXXDestructor: 8965 // C++11 [class.dtor]p5: 8966 // A destructor is trivial if: 8967 // - all the direct [subobjects] have trivial destructors 8968 if (RD->hasTrivialDestructor() || 8969 (TAH == Sema::TAH_ConsiderTrivialABI && 8970 RD->hasTrivialDestructorForCall())) 8971 return true; 8972 8973 if (Selected) { 8974 if (RD->needsImplicitDestructor()) 8975 S.DeclareImplicitDestructor(RD); 8976 *Selected = RD->getDestructor(); 8977 } 8978 8979 return false; 8980 8981 case Sema::CXXCopyConstructor: 8982 // C++11 [class.copy]p12: 8983 // A copy constructor is trivial if: 8984 // - the constructor selected to copy each direct [subobject] is trivial 8985 if (RD->hasTrivialCopyConstructor() || 8986 (TAH == Sema::TAH_ConsiderTrivialABI && 8987 RD->hasTrivialCopyConstructorForCall())) { 8988 if (Quals == Qualifiers::Const) 8989 // We must either select the trivial copy constructor or reach an 8990 // ambiguity; no need to actually perform overload resolution. 8991 return true; 8992 } else if (!Selected) { 8993 return false; 8994 } 8995 // In C++98, we are not supposed to perform overload resolution here, but we 8996 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 8997 // cases like B as having a non-trivial copy constructor: 8998 // struct A { template<typename T> A(T&); }; 8999 // struct B { mutable A a; }; 9000 goto NeedOverloadResolution; 9001 9002 case Sema::CXXCopyAssignment: 9003 // C++11 [class.copy]p25: 9004 // A copy assignment operator is trivial if: 9005 // - the assignment operator selected to copy each direct [subobject] is 9006 // trivial 9007 if (RD->hasTrivialCopyAssignment()) { 9008 if (Quals == Qualifiers::Const) 9009 return true; 9010 } else if (!Selected) { 9011 return false; 9012 } 9013 // In C++98, we are not supposed to perform overload resolution here, but we 9014 // treat that as a language defect. 9015 goto NeedOverloadResolution; 9016 9017 case Sema::CXXMoveConstructor: 9018 case Sema::CXXMoveAssignment: 9019 NeedOverloadResolution: 9020 Sema::SpecialMemberOverloadResult SMOR = 9021 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9022 9023 // The standard doesn't describe how to behave if the lookup is ambiguous. 9024 // We treat it as not making the member non-trivial, just like the standard 9025 // mandates for the default constructor. This should rarely matter, because 9026 // the member will also be deleted. 9027 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9028 return true; 9029 9030 if (!SMOR.getMethod()) { 9031 assert(SMOR.getKind() == 9032 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9033 return false; 9034 } 9035 9036 // We deliberately don't check if we found a deleted special member. We're 9037 // not supposed to! 9038 if (Selected) 9039 *Selected = SMOR.getMethod(); 9040 9041 if (TAH == Sema::TAH_ConsiderTrivialABI && 9042 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9043 return SMOR.getMethod()->isTrivialForCall(); 9044 return SMOR.getMethod()->isTrivial(); 9045 } 9046 9047 llvm_unreachable("unknown special method kind"); 9048 } 9049 9050 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9051 for (auto *CI : RD->ctors()) 9052 if (!CI->isImplicit()) 9053 return CI; 9054 9055 // Look for constructor templates. 9056 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9057 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9058 if (CXXConstructorDecl *CD = 9059 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9060 return CD; 9061 } 9062 9063 return nullptr; 9064 } 9065 9066 /// The kind of subobject we are checking for triviality. The values of this 9067 /// enumeration are used in diagnostics. 9068 enum TrivialSubobjectKind { 9069 /// The subobject is a base class. 9070 TSK_BaseClass, 9071 /// The subobject is a non-static data member. 9072 TSK_Field, 9073 /// The object is actually the complete object. 9074 TSK_CompleteObject 9075 }; 9076 9077 /// Check whether the special member selected for a given type would be trivial. 9078 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9079 QualType SubType, bool ConstRHS, 9080 Sema::CXXSpecialMember CSM, 9081 TrivialSubobjectKind Kind, 9082 Sema::TrivialABIHandling TAH, bool Diagnose) { 9083 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9084 if (!SubRD) 9085 return true; 9086 9087 CXXMethodDecl *Selected; 9088 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9089 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9090 return true; 9091 9092 if (Diagnose) { 9093 if (ConstRHS) 9094 SubType.addConst(); 9095 9096 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9097 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9098 << Kind << SubType.getUnqualifiedType(); 9099 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9100 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9101 } else if (!Selected) 9102 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9103 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9104 else if (Selected->isUserProvided()) { 9105 if (Kind == TSK_CompleteObject) 9106 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9107 << Kind << SubType.getUnqualifiedType() << CSM; 9108 else { 9109 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9110 << Kind << SubType.getUnqualifiedType() << CSM; 9111 S.Diag(Selected->getLocation(), diag::note_declared_at); 9112 } 9113 } else { 9114 if (Kind != TSK_CompleteObject) 9115 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9116 << Kind << SubType.getUnqualifiedType() << CSM; 9117 9118 // Explain why the defaulted or deleted special member isn't trivial. 9119 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9120 Diagnose); 9121 } 9122 } 9123 9124 return false; 9125 } 9126 9127 /// Check whether the members of a class type allow a special member to be 9128 /// trivial. 9129 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9130 Sema::CXXSpecialMember CSM, 9131 bool ConstArg, 9132 Sema::TrivialABIHandling TAH, 9133 bool Diagnose) { 9134 for (const auto *FI : RD->fields()) { 9135 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9136 continue; 9137 9138 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9139 9140 // Pretend anonymous struct or union members are members of this class. 9141 if (FI->isAnonymousStructOrUnion()) { 9142 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9143 CSM, ConstArg, TAH, Diagnose)) 9144 return false; 9145 continue; 9146 } 9147 9148 // C++11 [class.ctor]p5: 9149 // A default constructor is trivial if [...] 9150 // -- no non-static data member of its class has a 9151 // brace-or-equal-initializer 9152 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9153 if (Diagnose) 9154 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 9155 return false; 9156 } 9157 9158 // Objective C ARC 4.3.5: 9159 // [...] nontrivally ownership-qualified types are [...] not trivially 9160 // default constructible, copy constructible, move constructible, copy 9161 // assignable, move assignable, or destructible [...] 9162 if (FieldType.hasNonTrivialObjCLifetime()) { 9163 if (Diagnose) 9164 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9165 << RD << FieldType.getObjCLifetime(); 9166 return false; 9167 } 9168 9169 bool ConstRHS = ConstArg && !FI->isMutable(); 9170 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9171 CSM, TSK_Field, TAH, Diagnose)) 9172 return false; 9173 } 9174 9175 return true; 9176 } 9177 9178 /// Diagnose why the specified class does not have a trivial special member of 9179 /// the given kind. 9180 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9181 QualType Ty = Context.getRecordType(RD); 9182 9183 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9184 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9185 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9186 /*Diagnose*/true); 9187 } 9188 9189 /// Determine whether a defaulted or deleted special member function is trivial, 9190 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9191 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9192 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9193 TrivialABIHandling TAH, bool Diagnose) { 9194 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9195 9196 CXXRecordDecl *RD = MD->getParent(); 9197 9198 bool ConstArg = false; 9199 9200 // C++11 [class.copy]p12, p25: [DR1593] 9201 // A [special member] is trivial if [...] its parameter-type-list is 9202 // equivalent to the parameter-type-list of an implicit declaration [...] 9203 switch (CSM) { 9204 case CXXDefaultConstructor: 9205 case CXXDestructor: 9206 // Trivial default constructors and destructors cannot have parameters. 9207 break; 9208 9209 case CXXCopyConstructor: 9210 case CXXCopyAssignment: { 9211 // Trivial copy operations always have const, non-volatile parameter types. 9212 ConstArg = true; 9213 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9214 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9215 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9216 if (Diagnose) 9217 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9218 << Param0->getSourceRange() << Param0->getType() 9219 << Context.getLValueReferenceType( 9220 Context.getRecordType(RD).withConst()); 9221 return false; 9222 } 9223 break; 9224 } 9225 9226 case CXXMoveConstructor: 9227 case CXXMoveAssignment: { 9228 // Trivial move operations always have non-cv-qualified parameters. 9229 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9230 const RValueReferenceType *RT = 9231 Param0->getType()->getAs<RValueReferenceType>(); 9232 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9233 if (Diagnose) 9234 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9235 << Param0->getSourceRange() << Param0->getType() 9236 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9237 return false; 9238 } 9239 break; 9240 } 9241 9242 case CXXInvalid: 9243 llvm_unreachable("not a special member"); 9244 } 9245 9246 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9247 if (Diagnose) 9248 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9249 diag::note_nontrivial_default_arg) 9250 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9251 return false; 9252 } 9253 if (MD->isVariadic()) { 9254 if (Diagnose) 9255 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9256 return false; 9257 } 9258 9259 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9260 // A copy/move [constructor or assignment operator] is trivial if 9261 // -- the [member] selected to copy/move each direct base class subobject 9262 // is trivial 9263 // 9264 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9265 // A [default constructor or destructor] is trivial if 9266 // -- all the direct base classes have trivial [default constructors or 9267 // destructors] 9268 for (const auto &BI : RD->bases()) 9269 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9270 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9271 return false; 9272 9273 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9274 // A copy/move [constructor or assignment operator] for a class X is 9275 // trivial if 9276 // -- for each non-static data member of X that is of class type (or array 9277 // thereof), the constructor selected to copy/move that member is 9278 // trivial 9279 // 9280 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9281 // A [default constructor or destructor] is trivial if 9282 // -- for all of the non-static data members of its class that are of class 9283 // type (or array thereof), each such class has a trivial [default 9284 // constructor or destructor] 9285 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9286 return false; 9287 9288 // C++11 [class.dtor]p5: 9289 // A destructor is trivial if [...] 9290 // -- the destructor is not virtual 9291 if (CSM == CXXDestructor && MD->isVirtual()) { 9292 if (Diagnose) 9293 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9294 return false; 9295 } 9296 9297 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9298 // A [special member] for class X is trivial if [...] 9299 // -- class X has no virtual functions and no virtual base classes 9300 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9301 if (!Diagnose) 9302 return false; 9303 9304 if (RD->getNumVBases()) { 9305 // Check for virtual bases. We already know that the corresponding 9306 // member in all bases is trivial, so vbases must all be direct. 9307 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9308 assert(BS.isVirtual()); 9309 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9310 return false; 9311 } 9312 9313 // Must have a virtual method. 9314 for (const auto *MI : RD->methods()) { 9315 if (MI->isVirtual()) { 9316 SourceLocation MLoc = MI->getBeginLoc(); 9317 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9318 return false; 9319 } 9320 } 9321 9322 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9323 } 9324 9325 // Looks like it's trivial! 9326 return true; 9327 } 9328 9329 namespace { 9330 struct FindHiddenVirtualMethod { 9331 Sema *S; 9332 CXXMethodDecl *Method; 9333 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9334 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9335 9336 private: 9337 /// Check whether any most overridden method from MD in Methods 9338 static bool CheckMostOverridenMethods( 9339 const CXXMethodDecl *MD, 9340 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9341 if (MD->size_overridden_methods() == 0) 9342 return Methods.count(MD->getCanonicalDecl()); 9343 for (const CXXMethodDecl *O : MD->overridden_methods()) 9344 if (CheckMostOverridenMethods(O, Methods)) 9345 return true; 9346 return false; 9347 } 9348 9349 public: 9350 /// Member lookup function that determines whether a given C++ 9351 /// method overloads virtual methods in a base class without overriding any, 9352 /// to be used with CXXRecordDecl::lookupInBases(). 9353 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9354 RecordDecl *BaseRecord = 9355 Specifier->getType()->castAs<RecordType>()->getDecl(); 9356 9357 DeclarationName Name = Method->getDeclName(); 9358 assert(Name.getNameKind() == DeclarationName::Identifier); 9359 9360 bool foundSameNameMethod = false; 9361 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9362 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9363 Path.Decls = Path.Decls.slice(1)) { 9364 NamedDecl *D = Path.Decls.front(); 9365 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9366 MD = MD->getCanonicalDecl(); 9367 foundSameNameMethod = true; 9368 // Interested only in hidden virtual methods. 9369 if (!MD->isVirtual()) 9370 continue; 9371 // If the method we are checking overrides a method from its base 9372 // don't warn about the other overloaded methods. Clang deviates from 9373 // GCC by only diagnosing overloads of inherited virtual functions that 9374 // do not override any other virtual functions in the base. GCC's 9375 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9376 // function from a base class. These cases may be better served by a 9377 // warning (not specific to virtual functions) on call sites when the 9378 // call would select a different function from the base class, were it 9379 // visible. 9380 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9381 if (!S->IsOverload(Method, MD, false)) 9382 return true; 9383 // Collect the overload only if its hidden. 9384 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9385 overloadedMethods.push_back(MD); 9386 } 9387 } 9388 9389 if (foundSameNameMethod) 9390 OverloadedMethods.append(overloadedMethods.begin(), 9391 overloadedMethods.end()); 9392 return foundSameNameMethod; 9393 } 9394 }; 9395 } // end anonymous namespace 9396 9397 /// Add the most overriden methods from MD to Methods 9398 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9399 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9400 if (MD->size_overridden_methods() == 0) 9401 Methods.insert(MD->getCanonicalDecl()); 9402 else 9403 for (const CXXMethodDecl *O : MD->overridden_methods()) 9404 AddMostOverridenMethods(O, Methods); 9405 } 9406 9407 /// Check if a method overloads virtual methods in a base class without 9408 /// overriding any. 9409 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9410 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9411 if (!MD->getDeclName().isIdentifier()) 9412 return; 9413 9414 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9415 /*bool RecordPaths=*/false, 9416 /*bool DetectVirtual=*/false); 9417 FindHiddenVirtualMethod FHVM; 9418 FHVM.Method = MD; 9419 FHVM.S = this; 9420 9421 // Keep the base methods that were overridden or introduced in the subclass 9422 // by 'using' in a set. A base method not in this set is hidden. 9423 CXXRecordDecl *DC = MD->getParent(); 9424 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9425 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9426 NamedDecl *ND = *I; 9427 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9428 ND = shad->getTargetDecl(); 9429 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9430 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9431 } 9432 9433 if (DC->lookupInBases(FHVM, Paths)) 9434 OverloadedMethods = FHVM.OverloadedMethods; 9435 } 9436 9437 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9438 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9439 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9440 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9441 PartialDiagnostic PD = PDiag( 9442 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9443 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9444 Diag(overloadedMD->getLocation(), PD); 9445 } 9446 } 9447 9448 /// Diagnose methods which overload virtual methods in a base class 9449 /// without overriding any. 9450 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9451 if (MD->isInvalidDecl()) 9452 return; 9453 9454 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9455 return; 9456 9457 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9458 FindHiddenVirtualMethods(MD, OverloadedMethods); 9459 if (!OverloadedMethods.empty()) { 9460 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9461 << MD << (OverloadedMethods.size() > 1); 9462 9463 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9464 } 9465 } 9466 9467 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9468 auto PrintDiagAndRemoveAttr = [&]() { 9469 // No diagnostics if this is a template instantiation. 9470 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 9471 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9472 diag::ext_cannot_use_trivial_abi) << &RD; 9473 RD.dropAttr<TrivialABIAttr>(); 9474 }; 9475 9476 // Ill-formed if the struct has virtual functions. 9477 if (RD.isPolymorphic()) { 9478 PrintDiagAndRemoveAttr(); 9479 return; 9480 } 9481 9482 for (const auto &B : RD.bases()) { 9483 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9484 // virtual base. 9485 if ((!B.getType()->isDependentType() && 9486 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 9487 B.isVirtual()) { 9488 PrintDiagAndRemoveAttr(); 9489 return; 9490 } 9491 } 9492 9493 for (const auto *FD : RD.fields()) { 9494 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9495 // non-trivial for the purpose of calls. 9496 QualType FT = FD->getType(); 9497 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9498 PrintDiagAndRemoveAttr(); 9499 return; 9500 } 9501 9502 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9503 if (!RT->isDependentType() && 9504 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9505 PrintDiagAndRemoveAttr(); 9506 return; 9507 } 9508 } 9509 } 9510 9511 void Sema::ActOnFinishCXXMemberSpecification( 9512 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9513 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9514 if (!TagDecl) 9515 return; 9516 9517 AdjustDeclIfTemplate(TagDecl); 9518 9519 for (const ParsedAttr &AL : AttrList) { 9520 if (AL.getKind() != ParsedAttr::AT_Visibility) 9521 continue; 9522 AL.setInvalid(); 9523 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9524 } 9525 9526 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9527 // strict aliasing violation! 9528 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9529 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9530 9531 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9532 } 9533 9534 /// Find the equality comparison functions that should be implicitly declared 9535 /// in a given class definition, per C++2a [class.compare.default]p3. 9536 static void findImplicitlyDeclaredEqualityComparisons( 9537 ASTContext &Ctx, CXXRecordDecl *RD, 9538 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9539 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9540 if (!RD->lookup(EqEq).empty()) 9541 // Member operator== explicitly declared: no implicit operator==s. 9542 return; 9543 9544 // Traverse friends looking for an '==' or a '<=>'. 9545 for (FriendDecl *Friend : RD->friends()) { 9546 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9547 if (!FD) continue; 9548 9549 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9550 // Friend operator== explicitly declared: no implicit operator==s. 9551 Spaceships.clear(); 9552 return; 9553 } 9554 9555 if (FD->getOverloadedOperator() == OO_Spaceship && 9556 FD->isExplicitlyDefaulted()) 9557 Spaceships.push_back(FD); 9558 } 9559 9560 // Look for members named 'operator<=>'. 9561 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9562 for (NamedDecl *ND : RD->lookup(Cmp)) { 9563 // Note that we could find a non-function here (either a function template 9564 // or a using-declaration). Neither case results in an implicit 9565 // 'operator=='. 9566 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9567 if (FD->isExplicitlyDefaulted()) 9568 Spaceships.push_back(FD); 9569 } 9570 } 9571 9572 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9573 /// special functions, such as the default constructor, copy 9574 /// constructor, or destructor, to the given C++ class (C++ 9575 /// [special]p1). This routine can only be executed just before the 9576 /// definition of the class is complete. 9577 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9578 if (ClassDecl->needsImplicitDefaultConstructor()) { 9579 ++getASTContext().NumImplicitDefaultConstructors; 9580 9581 if (ClassDecl->hasInheritedConstructor()) 9582 DeclareImplicitDefaultConstructor(ClassDecl); 9583 } 9584 9585 if (ClassDecl->needsImplicitCopyConstructor()) { 9586 ++getASTContext().NumImplicitCopyConstructors; 9587 9588 // If the properties or semantics of the copy constructor couldn't be 9589 // determined while the class was being declared, force a declaration 9590 // of it now. 9591 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9592 ClassDecl->hasInheritedConstructor()) 9593 DeclareImplicitCopyConstructor(ClassDecl); 9594 // For the MS ABI we need to know whether the copy ctor is deleted. A 9595 // prerequisite for deleting the implicit copy ctor is that the class has a 9596 // move ctor or move assignment that is either user-declared or whose 9597 // semantics are inherited from a subobject. FIXME: We should provide a more 9598 // direct way for CodeGen to ask whether the constructor was deleted. 9599 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9600 (ClassDecl->hasUserDeclaredMoveConstructor() || 9601 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9602 ClassDecl->hasUserDeclaredMoveAssignment() || 9603 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9604 DeclareImplicitCopyConstructor(ClassDecl); 9605 } 9606 9607 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 9608 ++getASTContext().NumImplicitMoveConstructors; 9609 9610 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9611 ClassDecl->hasInheritedConstructor()) 9612 DeclareImplicitMoveConstructor(ClassDecl); 9613 } 9614 9615 if (ClassDecl->needsImplicitCopyAssignment()) { 9616 ++getASTContext().NumImplicitCopyAssignmentOperators; 9617 9618 // If we have a dynamic class, then the copy assignment operator may be 9619 // virtual, so we have to declare it immediately. This ensures that, e.g., 9620 // it shows up in the right place in the vtable and that we diagnose 9621 // problems with the implicit exception specification. 9622 if (ClassDecl->isDynamicClass() || 9623 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9624 ClassDecl->hasInheritedAssignment()) 9625 DeclareImplicitCopyAssignment(ClassDecl); 9626 } 9627 9628 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9629 ++getASTContext().NumImplicitMoveAssignmentOperators; 9630 9631 // Likewise for the move assignment operator. 9632 if (ClassDecl->isDynamicClass() || 9633 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9634 ClassDecl->hasInheritedAssignment()) 9635 DeclareImplicitMoveAssignment(ClassDecl); 9636 } 9637 9638 if (ClassDecl->needsImplicitDestructor()) { 9639 ++getASTContext().NumImplicitDestructors; 9640 9641 // If we have a dynamic class, then the destructor may be virtual, so we 9642 // have to declare the destructor immediately. This ensures that, e.g., it 9643 // shows up in the right place in the vtable and that we diagnose problems 9644 // with the implicit exception specification. 9645 if (ClassDecl->isDynamicClass() || 9646 ClassDecl->needsOverloadResolutionForDestructor()) 9647 DeclareImplicitDestructor(ClassDecl); 9648 } 9649 9650 // C++2a [class.compare.default]p3: 9651 // If the member-specification does not explicitly declare any member or 9652 // friend named operator==, an == operator function is declared implicitly 9653 // for each defaulted three-way comparison operator function defined in the 9654 // member-specification 9655 // FIXME: Consider doing this lazily. 9656 if (getLangOpts().CPlusPlus2a) { 9657 llvm::SmallVector<FunctionDecl*, 4> DefaultedSpaceships; 9658 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 9659 DefaultedSpaceships); 9660 for (auto *FD : DefaultedSpaceships) 9661 DeclareImplicitEqualityComparison(ClassDecl, FD); 9662 } 9663 } 9664 9665 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 9666 if (!D) 9667 return 0; 9668 9669 // The order of template parameters is not important here. All names 9670 // get added to the same scope. 9671 SmallVector<TemplateParameterList *, 4> ParameterLists; 9672 9673 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9674 D = TD->getTemplatedDecl(); 9675 9676 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 9677 ParameterLists.push_back(PSD->getTemplateParameters()); 9678 9679 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 9680 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 9681 ParameterLists.push_back(DD->getTemplateParameterList(i)); 9682 9683 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9684 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 9685 ParameterLists.push_back(FTD->getTemplateParameters()); 9686 } 9687 } 9688 9689 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9690 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 9691 ParameterLists.push_back(TD->getTemplateParameterList(i)); 9692 9693 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 9694 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 9695 ParameterLists.push_back(CTD->getTemplateParameters()); 9696 } 9697 } 9698 9699 unsigned Count = 0; 9700 for (TemplateParameterList *Params : ParameterLists) { 9701 if (Params->size() > 0) 9702 // Ignore explicit specializations; they don't contribute to the template 9703 // depth. 9704 ++Count; 9705 for (NamedDecl *Param : *Params) { 9706 if (Param->getDeclName()) { 9707 S->AddDecl(Param); 9708 IdResolver.AddDecl(Param); 9709 } 9710 } 9711 } 9712 9713 return Count; 9714 } 9715 9716 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 9717 if (!RecordD) return; 9718 AdjustDeclIfTemplate(RecordD); 9719 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 9720 PushDeclContext(S, Record); 9721 } 9722 9723 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 9724 if (!RecordD) return; 9725 PopDeclContext(); 9726 } 9727 9728 /// This is used to implement the constant expression evaluation part of the 9729 /// attribute enable_if extension. There is nothing in standard C++ which would 9730 /// require reentering parameters. 9731 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 9732 if (!Param) 9733 return; 9734 9735 S->AddDecl(Param); 9736 if (Param->getDeclName()) 9737 IdResolver.AddDecl(Param); 9738 } 9739 9740 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 9741 /// parsing a top-level (non-nested) C++ class, and we are now 9742 /// parsing those parts of the given Method declaration that could 9743 /// not be parsed earlier (C++ [class.mem]p2), such as default 9744 /// arguments. This action should enter the scope of the given 9745 /// Method declaration as if we had just parsed the qualified method 9746 /// name. However, it should not bring the parameters into scope; 9747 /// that will be performed by ActOnDelayedCXXMethodParameter. 9748 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 9749 } 9750 9751 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 9752 /// C++ method declaration. We're (re-)introducing the given 9753 /// function parameter into scope for use in parsing later parts of 9754 /// the method declaration. For example, we could see an 9755 /// ActOnParamDefaultArgument event for this parameter. 9756 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 9757 if (!ParamD) 9758 return; 9759 9760 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 9761 9762 // If this parameter has an unparsed default argument, clear it out 9763 // to make way for the parsed default argument. 9764 if (Param->hasUnparsedDefaultArg()) 9765 Param->setDefaultArg(nullptr); 9766 9767 S->AddDecl(Param); 9768 if (Param->getDeclName()) 9769 IdResolver.AddDecl(Param); 9770 } 9771 9772 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 9773 /// processing the delayed method declaration for Method. The method 9774 /// declaration is now considered finished. There may be a separate 9775 /// ActOnStartOfFunctionDef action later (not necessarily 9776 /// immediately!) for this method, if it was also defined inside the 9777 /// class body. 9778 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 9779 if (!MethodD) 9780 return; 9781 9782 AdjustDeclIfTemplate(MethodD); 9783 9784 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 9785 9786 // Now that we have our default arguments, check the constructor 9787 // again. It could produce additional diagnostics or affect whether 9788 // the class has implicitly-declared destructors, among other 9789 // things. 9790 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 9791 CheckConstructor(Constructor); 9792 9793 // Check the default arguments, which we may have added. 9794 if (!Method->isInvalidDecl()) 9795 CheckCXXDefaultArguments(Method); 9796 } 9797 9798 // Emit the given diagnostic for each non-address-space qualifier. 9799 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 9800 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 9801 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9802 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 9803 bool DiagOccured = false; 9804 FTI.MethodQualifiers->forEachQualifier( 9805 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 9806 SourceLocation SL) { 9807 // This diagnostic should be emitted on any qualifier except an addr 9808 // space qualifier. However, forEachQualifier currently doesn't visit 9809 // addr space qualifiers, so there's no way to write this condition 9810 // right now; we just diagnose on everything. 9811 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 9812 DiagOccured = true; 9813 }); 9814 if (DiagOccured) 9815 D.setInvalidType(); 9816 } 9817 } 9818 9819 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 9820 /// the well-formedness of the constructor declarator @p D with type @p 9821 /// R. If there are any errors in the declarator, this routine will 9822 /// emit diagnostics and set the invalid bit to true. In any case, the type 9823 /// will be updated to reflect a well-formed type for the constructor and 9824 /// returned. 9825 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 9826 StorageClass &SC) { 9827 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9828 9829 // C++ [class.ctor]p3: 9830 // A constructor shall not be virtual (10.3) or static (9.4). A 9831 // constructor can be invoked for a const, volatile or const 9832 // volatile object. A constructor shall not be declared const, 9833 // volatile, or const volatile (9.3.2). 9834 if (isVirtual) { 9835 if (!D.isInvalidType()) 9836 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 9837 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 9838 << SourceRange(D.getIdentifierLoc()); 9839 D.setInvalidType(); 9840 } 9841 if (SC == SC_Static) { 9842 if (!D.isInvalidType()) 9843 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 9844 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 9845 << SourceRange(D.getIdentifierLoc()); 9846 D.setInvalidType(); 9847 SC = SC_None; 9848 } 9849 9850 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 9851 diagnoseIgnoredQualifiers( 9852 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 9853 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 9854 D.getDeclSpec().getRestrictSpecLoc(), 9855 D.getDeclSpec().getAtomicSpecLoc()); 9856 D.setInvalidType(); 9857 } 9858 9859 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 9860 9861 // C++0x [class.ctor]p4: 9862 // A constructor shall not be declared with a ref-qualifier. 9863 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9864 if (FTI.hasRefQualifier()) { 9865 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 9866 << FTI.RefQualifierIsLValueRef 9867 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 9868 D.setInvalidType(); 9869 } 9870 9871 // Rebuild the function type "R" without any type qualifiers (in 9872 // case any of the errors above fired) and with "void" as the 9873 // return type, since constructors don't have return types. 9874 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 9875 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 9876 return R; 9877 9878 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 9879 EPI.TypeQuals = Qualifiers(); 9880 EPI.RefQualifier = RQ_None; 9881 9882 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 9883 } 9884 9885 /// CheckConstructor - Checks a fully-formed constructor for 9886 /// well-formedness, issuing any diagnostics required. Returns true if 9887 /// the constructor declarator is invalid. 9888 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 9889 CXXRecordDecl *ClassDecl 9890 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 9891 if (!ClassDecl) 9892 return Constructor->setInvalidDecl(); 9893 9894 // C++ [class.copy]p3: 9895 // A declaration of a constructor for a class X is ill-formed if 9896 // its first parameter is of type (optionally cv-qualified) X and 9897 // either there are no other parameters or else all other 9898 // parameters have default arguments. 9899 if (!Constructor->isInvalidDecl() && 9900 ((Constructor->getNumParams() == 1) || 9901 (Constructor->getNumParams() > 1 && 9902 Constructor->getParamDecl(1)->hasDefaultArg())) && 9903 Constructor->getTemplateSpecializationKind() 9904 != TSK_ImplicitInstantiation) { 9905 QualType ParamType = Constructor->getParamDecl(0)->getType(); 9906 QualType ClassTy = Context.getTagDeclType(ClassDecl); 9907 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 9908 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 9909 const char *ConstRef 9910 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 9911 : " const &"; 9912 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 9913 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 9914 9915 // FIXME: Rather that making the constructor invalid, we should endeavor 9916 // to fix the type. 9917 Constructor->setInvalidDecl(); 9918 } 9919 } 9920 } 9921 9922 /// CheckDestructor - Checks a fully-formed destructor definition for 9923 /// well-formedness, issuing any diagnostics required. Returns true 9924 /// on error. 9925 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 9926 CXXRecordDecl *RD = Destructor->getParent(); 9927 9928 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 9929 SourceLocation Loc; 9930 9931 if (!Destructor->isImplicit()) 9932 Loc = Destructor->getLocation(); 9933 else 9934 Loc = RD->getLocation(); 9935 9936 // If we have a virtual destructor, look up the deallocation function 9937 if (FunctionDecl *OperatorDelete = 9938 FindDeallocationFunctionForDestructor(Loc, RD)) { 9939 Expr *ThisArg = nullptr; 9940 9941 // If the notional 'delete this' expression requires a non-trivial 9942 // conversion from 'this' to the type of a destroying operator delete's 9943 // first parameter, perform that conversion now. 9944 if (OperatorDelete->isDestroyingOperatorDelete()) { 9945 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 9946 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 9947 // C++ [class.dtor]p13: 9948 // ... as if for the expression 'delete this' appearing in a 9949 // non-virtual destructor of the destructor's class. 9950 ContextRAII SwitchContext(*this, Destructor); 9951 ExprResult This = 9952 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 9953 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 9954 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 9955 if (This.isInvalid()) { 9956 // FIXME: Register this as a context note so that it comes out 9957 // in the right order. 9958 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 9959 return true; 9960 } 9961 ThisArg = This.get(); 9962 } 9963 } 9964 9965 DiagnoseUseOfDecl(OperatorDelete, Loc); 9966 MarkFunctionReferenced(Loc, OperatorDelete); 9967 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 9968 } 9969 } 9970 9971 return false; 9972 } 9973 9974 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 9975 /// the well-formednes of the destructor declarator @p D with type @p 9976 /// R. If there are any errors in the declarator, this routine will 9977 /// emit diagnostics and set the declarator to invalid. Even if this happens, 9978 /// will be updated to reflect a well-formed type for the destructor and 9979 /// returned. 9980 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 9981 StorageClass& SC) { 9982 // C++ [class.dtor]p1: 9983 // [...] A typedef-name that names a class is a class-name 9984 // (7.1.3); however, a typedef-name that names a class shall not 9985 // be used as the identifier in the declarator for a destructor 9986 // declaration. 9987 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 9988 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 9989 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 9990 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 9991 else if (const TemplateSpecializationType *TST = 9992 DeclaratorType->getAs<TemplateSpecializationType>()) 9993 if (TST->isTypeAlias()) 9994 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 9995 << DeclaratorType << 1; 9996 9997 // C++ [class.dtor]p2: 9998 // A destructor is used to destroy objects of its class type. A 9999 // destructor takes no parameters, and no return type can be 10000 // specified for it (not even void). The address of a destructor 10001 // shall not be taken. A destructor shall not be static. A 10002 // destructor can be invoked for a const, volatile or const 10003 // volatile object. A destructor shall not be declared const, 10004 // volatile or const volatile (9.3.2). 10005 if (SC == SC_Static) { 10006 if (!D.isInvalidType()) 10007 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10008 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10009 << SourceRange(D.getIdentifierLoc()) 10010 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10011 10012 SC = SC_None; 10013 } 10014 if (!D.isInvalidType()) { 10015 // Destructors don't have return types, but the parser will 10016 // happily parse something like: 10017 // 10018 // class X { 10019 // float ~X(); 10020 // }; 10021 // 10022 // The return type will be eliminated later. 10023 if (D.getDeclSpec().hasTypeSpecifier()) 10024 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10025 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10026 << SourceRange(D.getIdentifierLoc()); 10027 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10028 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10029 SourceLocation(), 10030 D.getDeclSpec().getConstSpecLoc(), 10031 D.getDeclSpec().getVolatileSpecLoc(), 10032 D.getDeclSpec().getRestrictSpecLoc(), 10033 D.getDeclSpec().getAtomicSpecLoc()); 10034 D.setInvalidType(); 10035 } 10036 } 10037 10038 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10039 10040 // C++0x [class.dtor]p2: 10041 // A destructor shall not be declared with a ref-qualifier. 10042 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10043 if (FTI.hasRefQualifier()) { 10044 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10045 << FTI.RefQualifierIsLValueRef 10046 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10047 D.setInvalidType(); 10048 } 10049 10050 // Make sure we don't have any parameters. 10051 if (FTIHasNonVoidParameters(FTI)) { 10052 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10053 10054 // Delete the parameters. 10055 FTI.freeParams(); 10056 D.setInvalidType(); 10057 } 10058 10059 // Make sure the destructor isn't variadic. 10060 if (FTI.isVariadic) { 10061 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10062 D.setInvalidType(); 10063 } 10064 10065 // Rebuild the function type "R" without any type qualifiers or 10066 // parameters (in case any of the errors above fired) and with 10067 // "void" as the return type, since destructors don't have return 10068 // types. 10069 if (!D.isInvalidType()) 10070 return R; 10071 10072 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10073 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10074 EPI.Variadic = false; 10075 EPI.TypeQuals = Qualifiers(); 10076 EPI.RefQualifier = RQ_None; 10077 return Context.getFunctionType(Context.VoidTy, None, EPI); 10078 } 10079 10080 static void extendLeft(SourceRange &R, SourceRange Before) { 10081 if (Before.isInvalid()) 10082 return; 10083 R.setBegin(Before.getBegin()); 10084 if (R.getEnd().isInvalid()) 10085 R.setEnd(Before.getEnd()); 10086 } 10087 10088 static void extendRight(SourceRange &R, SourceRange After) { 10089 if (After.isInvalid()) 10090 return; 10091 if (R.getBegin().isInvalid()) 10092 R.setBegin(After.getBegin()); 10093 R.setEnd(After.getEnd()); 10094 } 10095 10096 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10097 /// well-formednes of the conversion function declarator @p D with 10098 /// type @p R. If there are any errors in the declarator, this routine 10099 /// will emit diagnostics and return true. Otherwise, it will return 10100 /// false. Either way, the type @p R will be updated to reflect a 10101 /// well-formed type for the conversion operator. 10102 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10103 StorageClass& SC) { 10104 // C++ [class.conv.fct]p1: 10105 // Neither parameter types nor return type can be specified. The 10106 // type of a conversion function (8.3.5) is "function taking no 10107 // parameter returning conversion-type-id." 10108 if (SC == SC_Static) { 10109 if (!D.isInvalidType()) 10110 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10111 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10112 << D.getName().getSourceRange(); 10113 D.setInvalidType(); 10114 SC = SC_None; 10115 } 10116 10117 TypeSourceInfo *ConvTSI = nullptr; 10118 QualType ConvType = 10119 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10120 10121 const DeclSpec &DS = D.getDeclSpec(); 10122 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10123 // Conversion functions don't have return types, but the parser will 10124 // happily parse something like: 10125 // 10126 // class X { 10127 // float operator bool(); 10128 // }; 10129 // 10130 // The return type will be changed later anyway. 10131 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10132 << SourceRange(DS.getTypeSpecTypeLoc()) 10133 << SourceRange(D.getIdentifierLoc()); 10134 D.setInvalidType(); 10135 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10136 // It's also plausible that the user writes type qualifiers in the wrong 10137 // place, such as: 10138 // struct S { const operator int(); }; 10139 // FIXME: we could provide a fixit to move the qualifiers onto the 10140 // conversion type. 10141 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10142 << SourceRange(D.getIdentifierLoc()) << 0; 10143 D.setInvalidType(); 10144 } 10145 10146 const auto *Proto = R->castAs<FunctionProtoType>(); 10147 10148 // Make sure we don't have any parameters. 10149 if (Proto->getNumParams() > 0) { 10150 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10151 10152 // Delete the parameters. 10153 D.getFunctionTypeInfo().freeParams(); 10154 D.setInvalidType(); 10155 } else if (Proto->isVariadic()) { 10156 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10157 D.setInvalidType(); 10158 } 10159 10160 // Diagnose "&operator bool()" and other such nonsense. This 10161 // is actually a gcc extension which we don't support. 10162 if (Proto->getReturnType() != ConvType) { 10163 bool NeedsTypedef = false; 10164 SourceRange Before, After; 10165 10166 // Walk the chunks and extract information on them for our diagnostic. 10167 bool PastFunctionChunk = false; 10168 for (auto &Chunk : D.type_objects()) { 10169 switch (Chunk.Kind) { 10170 case DeclaratorChunk::Function: 10171 if (!PastFunctionChunk) { 10172 if (Chunk.Fun.HasTrailingReturnType) { 10173 TypeSourceInfo *TRT = nullptr; 10174 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10175 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10176 } 10177 PastFunctionChunk = true; 10178 break; 10179 } 10180 LLVM_FALLTHROUGH; 10181 case DeclaratorChunk::Array: 10182 NeedsTypedef = true; 10183 extendRight(After, Chunk.getSourceRange()); 10184 break; 10185 10186 case DeclaratorChunk::Pointer: 10187 case DeclaratorChunk::BlockPointer: 10188 case DeclaratorChunk::Reference: 10189 case DeclaratorChunk::MemberPointer: 10190 case DeclaratorChunk::Pipe: 10191 extendLeft(Before, Chunk.getSourceRange()); 10192 break; 10193 10194 case DeclaratorChunk::Paren: 10195 extendLeft(Before, Chunk.Loc); 10196 extendRight(After, Chunk.EndLoc); 10197 break; 10198 } 10199 } 10200 10201 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10202 After.isValid() ? After.getBegin() : 10203 D.getIdentifierLoc(); 10204 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10205 DB << Before << After; 10206 10207 if (!NeedsTypedef) { 10208 DB << /*don't need a typedef*/0; 10209 10210 // If we can provide a correct fix-it hint, do so. 10211 if (After.isInvalid() && ConvTSI) { 10212 SourceLocation InsertLoc = 10213 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10214 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10215 << FixItHint::CreateInsertionFromRange( 10216 InsertLoc, CharSourceRange::getTokenRange(Before)) 10217 << FixItHint::CreateRemoval(Before); 10218 } 10219 } else if (!Proto->getReturnType()->isDependentType()) { 10220 DB << /*typedef*/1 << Proto->getReturnType(); 10221 } else if (getLangOpts().CPlusPlus11) { 10222 DB << /*alias template*/2 << Proto->getReturnType(); 10223 } else { 10224 DB << /*might not be fixable*/3; 10225 } 10226 10227 // Recover by incorporating the other type chunks into the result type. 10228 // Note, this does *not* change the name of the function. This is compatible 10229 // with the GCC extension: 10230 // struct S { &operator int(); } s; 10231 // int &r = s.operator int(); // ok in GCC 10232 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10233 ConvType = Proto->getReturnType(); 10234 } 10235 10236 // C++ [class.conv.fct]p4: 10237 // The conversion-type-id shall not represent a function type nor 10238 // an array type. 10239 if (ConvType->isArrayType()) { 10240 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10241 ConvType = Context.getPointerType(ConvType); 10242 D.setInvalidType(); 10243 } else if (ConvType->isFunctionType()) { 10244 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10245 ConvType = Context.getPointerType(ConvType); 10246 D.setInvalidType(); 10247 } 10248 10249 // Rebuild the function type "R" without any parameters (in case any 10250 // of the errors above fired) and with the conversion type as the 10251 // return type. 10252 if (D.isInvalidType()) 10253 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10254 10255 // C++0x explicit conversion operators. 10256 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) 10257 Diag(DS.getExplicitSpecLoc(), 10258 getLangOpts().CPlusPlus11 10259 ? diag::warn_cxx98_compat_explicit_conversion_functions 10260 : diag::ext_explicit_conversion_functions) 10261 << SourceRange(DS.getExplicitSpecRange()); 10262 } 10263 10264 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10265 /// the declaration of the given C++ conversion function. This routine 10266 /// is responsible for recording the conversion function in the C++ 10267 /// class, if possible. 10268 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10269 assert(Conversion && "Expected to receive a conversion function declaration"); 10270 10271 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10272 10273 // Make sure we aren't redeclaring the conversion function. 10274 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10275 10276 // C++ [class.conv.fct]p1: 10277 // [...] A conversion function is never used to convert a 10278 // (possibly cv-qualified) object to the (possibly cv-qualified) 10279 // same object type (or a reference to it), to a (possibly 10280 // cv-qualified) base class of that type (or a reference to it), 10281 // or to (possibly cv-qualified) void. 10282 // FIXME: Suppress this warning if the conversion function ends up being a 10283 // virtual function that overrides a virtual function in a base class. 10284 QualType ClassType 10285 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10286 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10287 ConvType = ConvTypeRef->getPointeeType(); 10288 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10289 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10290 /* Suppress diagnostics for instantiations. */; 10291 else if (ConvType->isRecordType()) { 10292 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10293 if (ConvType == ClassType) 10294 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10295 << ClassType; 10296 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10297 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10298 << ClassType << ConvType; 10299 } else if (ConvType->isVoidType()) { 10300 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10301 << ClassType << ConvType; 10302 } 10303 10304 if (FunctionTemplateDecl *ConversionTemplate 10305 = Conversion->getDescribedFunctionTemplate()) 10306 return ConversionTemplate; 10307 10308 return Conversion; 10309 } 10310 10311 namespace { 10312 /// Utility class to accumulate and print a diagnostic listing the invalid 10313 /// specifier(s) on a declaration. 10314 struct BadSpecifierDiagnoser { 10315 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10316 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10317 ~BadSpecifierDiagnoser() { 10318 Diagnostic << Specifiers; 10319 } 10320 10321 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10322 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10323 } 10324 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10325 return check(SpecLoc, 10326 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10327 } 10328 void check(SourceLocation SpecLoc, const char *Spec) { 10329 if (SpecLoc.isInvalid()) return; 10330 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10331 if (!Specifiers.empty()) Specifiers += " "; 10332 Specifiers += Spec; 10333 } 10334 10335 Sema &S; 10336 Sema::SemaDiagnosticBuilder Diagnostic; 10337 std::string Specifiers; 10338 }; 10339 } 10340 10341 /// Check the validity of a declarator that we parsed for a deduction-guide. 10342 /// These aren't actually declarators in the grammar, so we need to check that 10343 /// the user didn't specify any pieces that are not part of the deduction-guide 10344 /// grammar. 10345 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10346 StorageClass &SC) { 10347 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10348 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10349 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10350 10351 // C++ [temp.deduct.guide]p3: 10352 // A deduction-gide shall be declared in the same scope as the 10353 // corresponding class template. 10354 if (!CurContext->getRedeclContext()->Equals( 10355 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10356 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10357 << GuidedTemplateDecl; 10358 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10359 } 10360 10361 auto &DS = D.getMutableDeclSpec(); 10362 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10363 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10364 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10365 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10366 BadSpecifierDiagnoser Diagnoser( 10367 *this, D.getIdentifierLoc(), 10368 diag::err_deduction_guide_invalid_specifier); 10369 10370 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10371 DS.ClearStorageClassSpecs(); 10372 SC = SC_None; 10373 10374 // 'explicit' is permitted. 10375 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10376 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10377 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10378 DS.ClearConstexprSpec(); 10379 10380 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10381 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10382 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10383 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10384 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10385 DS.ClearTypeQualifiers(); 10386 10387 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10388 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10389 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10390 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10391 DS.ClearTypeSpecType(); 10392 } 10393 10394 if (D.isInvalidType()) 10395 return; 10396 10397 // Check the declarator is simple enough. 10398 bool FoundFunction = false; 10399 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10400 if (Chunk.Kind == DeclaratorChunk::Paren) 10401 continue; 10402 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10403 Diag(D.getDeclSpec().getBeginLoc(), 10404 diag::err_deduction_guide_with_complex_decl) 10405 << D.getSourceRange(); 10406 break; 10407 } 10408 if (!Chunk.Fun.hasTrailingReturnType()) { 10409 Diag(D.getName().getBeginLoc(), 10410 diag::err_deduction_guide_no_trailing_return_type); 10411 break; 10412 } 10413 10414 // Check that the return type is written as a specialization of 10415 // the template specified as the deduction-guide's name. 10416 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10417 TypeSourceInfo *TSI = nullptr; 10418 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10419 assert(TSI && "deduction guide has valid type but invalid return type?"); 10420 bool AcceptableReturnType = false; 10421 bool MightInstantiateToSpecialization = false; 10422 if (auto RetTST = 10423 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10424 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10425 bool TemplateMatches = 10426 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10427 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10428 AcceptableReturnType = true; 10429 else { 10430 // This could still instantiate to the right type, unless we know it 10431 // names the wrong class template. 10432 auto *TD = SpecifiedName.getAsTemplateDecl(); 10433 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10434 !TemplateMatches); 10435 } 10436 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10437 MightInstantiateToSpecialization = true; 10438 } 10439 10440 if (!AcceptableReturnType) { 10441 Diag(TSI->getTypeLoc().getBeginLoc(), 10442 diag::err_deduction_guide_bad_trailing_return_type) 10443 << GuidedTemplate << TSI->getType() 10444 << MightInstantiateToSpecialization 10445 << TSI->getTypeLoc().getSourceRange(); 10446 } 10447 10448 // Keep going to check that we don't have any inner declarator pieces (we 10449 // could still have a function returning a pointer to a function). 10450 FoundFunction = true; 10451 } 10452 10453 if (D.isFunctionDefinition()) 10454 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10455 } 10456 10457 //===----------------------------------------------------------------------===// 10458 // Namespace Handling 10459 //===----------------------------------------------------------------------===// 10460 10461 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10462 /// reopened. 10463 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10464 SourceLocation Loc, 10465 IdentifierInfo *II, bool *IsInline, 10466 NamespaceDecl *PrevNS) { 10467 assert(*IsInline != PrevNS->isInline()); 10468 10469 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10470 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10471 // inline namespaces, with the intention of bringing names into namespace std. 10472 // 10473 // We support this just well enough to get that case working; this is not 10474 // sufficient to support reopening namespaces as inline in general. 10475 if (*IsInline && II && II->getName().startswith("__atomic") && 10476 S.getSourceManager().isInSystemHeader(Loc)) { 10477 // Mark all prior declarations of the namespace as inline. 10478 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10479 NS = NS->getPreviousDecl()) 10480 NS->setInline(*IsInline); 10481 // Patch up the lookup table for the containing namespace. This isn't really 10482 // correct, but it's good enough for this particular case. 10483 for (auto *I : PrevNS->decls()) 10484 if (auto *ND = dyn_cast<NamedDecl>(I)) 10485 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10486 return; 10487 } 10488 10489 if (PrevNS->isInline()) 10490 // The user probably just forgot the 'inline', so suggest that it 10491 // be added back. 10492 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10493 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10494 else 10495 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10496 10497 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10498 *IsInline = PrevNS->isInline(); 10499 } 10500 10501 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10502 /// definition. 10503 Decl *Sema::ActOnStartNamespaceDef( 10504 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10505 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10506 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10507 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10508 // For anonymous namespace, take the location of the left brace. 10509 SourceLocation Loc = II ? IdentLoc : LBrace; 10510 bool IsInline = InlineLoc.isValid(); 10511 bool IsInvalid = false; 10512 bool IsStd = false; 10513 bool AddToKnown = false; 10514 Scope *DeclRegionScope = NamespcScope->getParent(); 10515 10516 NamespaceDecl *PrevNS = nullptr; 10517 if (II) { 10518 // C++ [namespace.def]p2: 10519 // The identifier in an original-namespace-definition shall not 10520 // have been previously defined in the declarative region in 10521 // which the original-namespace-definition appears. The 10522 // identifier in an original-namespace-definition is the name of 10523 // the namespace. Subsequently in that declarative region, it is 10524 // treated as an original-namespace-name. 10525 // 10526 // Since namespace names are unique in their scope, and we don't 10527 // look through using directives, just look for any ordinary names 10528 // as if by qualified name lookup. 10529 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10530 ForExternalRedeclaration); 10531 LookupQualifiedName(R, CurContext->getRedeclContext()); 10532 NamedDecl *PrevDecl = 10533 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10534 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10535 10536 if (PrevNS) { 10537 // This is an extended namespace definition. 10538 if (IsInline != PrevNS->isInline()) 10539 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10540 &IsInline, PrevNS); 10541 } else if (PrevDecl) { 10542 // This is an invalid name redefinition. 10543 Diag(Loc, diag::err_redefinition_different_kind) 10544 << II; 10545 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10546 IsInvalid = true; 10547 // Continue on to push Namespc as current DeclContext and return it. 10548 } else if (II->isStr("std") && 10549 CurContext->getRedeclContext()->isTranslationUnit()) { 10550 // This is the first "real" definition of the namespace "std", so update 10551 // our cache of the "std" namespace to point at this definition. 10552 PrevNS = getStdNamespace(); 10553 IsStd = true; 10554 AddToKnown = !IsInline; 10555 } else { 10556 // We've seen this namespace for the first time. 10557 AddToKnown = !IsInline; 10558 } 10559 } else { 10560 // Anonymous namespaces. 10561 10562 // Determine whether the parent already has an anonymous namespace. 10563 DeclContext *Parent = CurContext->getRedeclContext(); 10564 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10565 PrevNS = TU->getAnonymousNamespace(); 10566 } else { 10567 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10568 PrevNS = ND->getAnonymousNamespace(); 10569 } 10570 10571 if (PrevNS && IsInline != PrevNS->isInline()) 10572 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10573 &IsInline, PrevNS); 10574 } 10575 10576 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10577 StartLoc, Loc, II, PrevNS); 10578 if (IsInvalid) 10579 Namespc->setInvalidDecl(); 10580 10581 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10582 AddPragmaAttributes(DeclRegionScope, Namespc); 10583 10584 // FIXME: Should we be merging attributes? 10585 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10586 PushNamespaceVisibilityAttr(Attr, Loc); 10587 10588 if (IsStd) 10589 StdNamespace = Namespc; 10590 if (AddToKnown) 10591 KnownNamespaces[Namespc] = false; 10592 10593 if (II) { 10594 PushOnScopeChains(Namespc, DeclRegionScope); 10595 } else { 10596 // Link the anonymous namespace into its parent. 10597 DeclContext *Parent = CurContext->getRedeclContext(); 10598 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10599 TU->setAnonymousNamespace(Namespc); 10600 } else { 10601 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10602 } 10603 10604 CurContext->addDecl(Namespc); 10605 10606 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10607 // behaves as if it were replaced by 10608 // namespace unique { /* empty body */ } 10609 // using namespace unique; 10610 // namespace unique { namespace-body } 10611 // where all occurrences of 'unique' in a translation unit are 10612 // replaced by the same identifier and this identifier differs 10613 // from all other identifiers in the entire program. 10614 10615 // We just create the namespace with an empty name and then add an 10616 // implicit using declaration, just like the standard suggests. 10617 // 10618 // CodeGen enforces the "universally unique" aspect by giving all 10619 // declarations semantically contained within an anonymous 10620 // namespace internal linkage. 10621 10622 if (!PrevNS) { 10623 UD = UsingDirectiveDecl::Create(Context, Parent, 10624 /* 'using' */ LBrace, 10625 /* 'namespace' */ SourceLocation(), 10626 /* qualifier */ NestedNameSpecifierLoc(), 10627 /* identifier */ SourceLocation(), 10628 Namespc, 10629 /* Ancestor */ Parent); 10630 UD->setImplicit(); 10631 Parent->addDecl(UD); 10632 } 10633 } 10634 10635 ActOnDocumentableDecl(Namespc); 10636 10637 // Although we could have an invalid decl (i.e. the namespace name is a 10638 // redefinition), push it as current DeclContext and try to continue parsing. 10639 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10640 // for the namespace has the declarations that showed up in that particular 10641 // namespace definition. 10642 PushDeclContext(NamespcScope, Namespc); 10643 return Namespc; 10644 } 10645 10646 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 10647 /// is a namespace alias, returns the namespace it points to. 10648 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 10649 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 10650 return AD->getNamespace(); 10651 return dyn_cast_or_null<NamespaceDecl>(D); 10652 } 10653 10654 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 10655 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 10656 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 10657 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 10658 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 10659 Namespc->setRBraceLoc(RBrace); 10660 PopDeclContext(); 10661 if (Namespc->hasAttr<VisibilityAttr>()) 10662 PopPragmaVisibility(true, RBrace); 10663 // If this namespace contains an export-declaration, export it now. 10664 if (DeferredExportedNamespaces.erase(Namespc)) 10665 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 10666 } 10667 10668 CXXRecordDecl *Sema::getStdBadAlloc() const { 10669 return cast_or_null<CXXRecordDecl>( 10670 StdBadAlloc.get(Context.getExternalSource())); 10671 } 10672 10673 EnumDecl *Sema::getStdAlignValT() const { 10674 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 10675 } 10676 10677 NamespaceDecl *Sema::getStdNamespace() const { 10678 return cast_or_null<NamespaceDecl>( 10679 StdNamespace.get(Context.getExternalSource())); 10680 } 10681 10682 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 10683 if (!StdExperimentalNamespaceCache) { 10684 if (auto Std = getStdNamespace()) { 10685 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 10686 SourceLocation(), LookupNamespaceName); 10687 if (!LookupQualifiedName(Result, Std) || 10688 !(StdExperimentalNamespaceCache = 10689 Result.getAsSingle<NamespaceDecl>())) 10690 Result.suppressDiagnostics(); 10691 } 10692 } 10693 return StdExperimentalNamespaceCache; 10694 } 10695 10696 namespace { 10697 10698 enum UnsupportedSTLSelect { 10699 USS_InvalidMember, 10700 USS_MissingMember, 10701 USS_NonTrivial, 10702 USS_Other 10703 }; 10704 10705 struct InvalidSTLDiagnoser { 10706 Sema &S; 10707 SourceLocation Loc; 10708 QualType TyForDiags; 10709 10710 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 10711 const VarDecl *VD = nullptr) { 10712 { 10713 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 10714 << TyForDiags << ((int)Sel); 10715 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 10716 assert(!Name.empty()); 10717 D << Name; 10718 } 10719 } 10720 if (Sel == USS_InvalidMember) { 10721 S.Diag(VD->getLocation(), diag::note_var_declared_here) 10722 << VD << VD->getSourceRange(); 10723 } 10724 return QualType(); 10725 } 10726 }; 10727 } // namespace 10728 10729 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 10730 SourceLocation Loc, 10731 ComparisonCategoryUsage Usage) { 10732 assert(getLangOpts().CPlusPlus && 10733 "Looking for comparison category type outside of C++."); 10734 10735 // Use an elaborated type for diagnostics which has a name containing the 10736 // prepended 'std' namespace but not any inline namespace names. 10737 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 10738 auto *NNS = 10739 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 10740 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 10741 }; 10742 10743 // Check if we've already successfully checked the comparison category type 10744 // before. If so, skip checking it again. 10745 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 10746 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 10747 // The only thing we need to check is that the type has a reachable 10748 // definition in the current context. 10749 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 10750 return QualType(); 10751 10752 return Info->getType(); 10753 } 10754 10755 // If lookup failed 10756 if (!Info) { 10757 std::string NameForDiags = "std::"; 10758 NameForDiags += ComparisonCategories::getCategoryString(Kind); 10759 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 10760 << NameForDiags << (int)Usage; 10761 return QualType(); 10762 } 10763 10764 assert(Info->Kind == Kind); 10765 assert(Info->Record); 10766 10767 // Update the Record decl in case we encountered a forward declaration on our 10768 // first pass. FIXME: This is a bit of a hack. 10769 if (Info->Record->hasDefinition()) 10770 Info->Record = Info->Record->getDefinition(); 10771 10772 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 10773 return QualType(); 10774 10775 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 10776 10777 if (!Info->Record->isTriviallyCopyable()) 10778 return UnsupportedSTLError(USS_NonTrivial); 10779 10780 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 10781 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 10782 // Tolerate empty base classes. 10783 if (Base->isEmpty()) 10784 continue; 10785 // Reject STL implementations which have at least one non-empty base. 10786 return UnsupportedSTLError(); 10787 } 10788 10789 // Check that the STL has implemented the types using a single integer field. 10790 // This expectation allows better codegen for builtin operators. We require: 10791 // (1) The class has exactly one field. 10792 // (2) The field is an integral or enumeration type. 10793 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 10794 if (std::distance(FIt, FEnd) != 1 || 10795 !FIt->getType()->isIntegralOrEnumerationType()) { 10796 return UnsupportedSTLError(); 10797 } 10798 10799 // Build each of the require values and store them in Info. 10800 for (ComparisonCategoryResult CCR : 10801 ComparisonCategories::getPossibleResultsForType(Kind)) { 10802 StringRef MemName = ComparisonCategories::getResultString(CCR); 10803 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 10804 10805 if (!ValInfo) 10806 return UnsupportedSTLError(USS_MissingMember, MemName); 10807 10808 VarDecl *VD = ValInfo->VD; 10809 assert(VD && "should not be null!"); 10810 10811 // Attempt to diagnose reasons why the STL definition of this type 10812 // might be foobar, including it failing to be a constant expression. 10813 // TODO Handle more ways the lookup or result can be invalid. 10814 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 10815 !VD->checkInitIsICE()) 10816 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 10817 10818 // Attempt to evaluate the var decl as a constant expression and extract 10819 // the value of its first field as a ICE. If this fails, the STL 10820 // implementation is not supported. 10821 if (!ValInfo->hasValidIntValue()) 10822 return UnsupportedSTLError(); 10823 10824 MarkVariableReferenced(Loc, VD); 10825 } 10826 10827 // We've successfully built the required types and expressions. Update 10828 // the cache and return the newly cached value. 10829 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 10830 return Info->getType(); 10831 } 10832 10833 /// Retrieve the special "std" namespace, which may require us to 10834 /// implicitly define the namespace. 10835 NamespaceDecl *Sema::getOrCreateStdNamespace() { 10836 if (!StdNamespace) { 10837 // The "std" namespace has not yet been defined, so build one implicitly. 10838 StdNamespace = NamespaceDecl::Create(Context, 10839 Context.getTranslationUnitDecl(), 10840 /*Inline=*/false, 10841 SourceLocation(), SourceLocation(), 10842 &PP.getIdentifierTable().get("std"), 10843 /*PrevDecl=*/nullptr); 10844 getStdNamespace()->setImplicit(true); 10845 } 10846 10847 return getStdNamespace(); 10848 } 10849 10850 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 10851 assert(getLangOpts().CPlusPlus && 10852 "Looking for std::initializer_list outside of C++."); 10853 10854 // We're looking for implicit instantiations of 10855 // template <typename E> class std::initializer_list. 10856 10857 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 10858 return false; 10859 10860 ClassTemplateDecl *Template = nullptr; 10861 const TemplateArgument *Arguments = nullptr; 10862 10863 if (const RecordType *RT = Ty->getAs<RecordType>()) { 10864 10865 ClassTemplateSpecializationDecl *Specialization = 10866 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 10867 if (!Specialization) 10868 return false; 10869 10870 Template = Specialization->getSpecializedTemplate(); 10871 Arguments = Specialization->getTemplateArgs().data(); 10872 } else if (const TemplateSpecializationType *TST = 10873 Ty->getAs<TemplateSpecializationType>()) { 10874 Template = dyn_cast_or_null<ClassTemplateDecl>( 10875 TST->getTemplateName().getAsTemplateDecl()); 10876 Arguments = TST->getArgs(); 10877 } 10878 if (!Template) 10879 return false; 10880 10881 if (!StdInitializerList) { 10882 // Haven't recognized std::initializer_list yet, maybe this is it. 10883 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 10884 if (TemplateClass->getIdentifier() != 10885 &PP.getIdentifierTable().get("initializer_list") || 10886 !getStdNamespace()->InEnclosingNamespaceSetOf( 10887 TemplateClass->getDeclContext())) 10888 return false; 10889 // This is a template called std::initializer_list, but is it the right 10890 // template? 10891 TemplateParameterList *Params = Template->getTemplateParameters(); 10892 if (Params->getMinRequiredArguments() != 1) 10893 return false; 10894 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 10895 return false; 10896 10897 // It's the right template. 10898 StdInitializerList = Template; 10899 } 10900 10901 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 10902 return false; 10903 10904 // This is an instance of std::initializer_list. Find the argument type. 10905 if (Element) 10906 *Element = Arguments[0].getAsType(); 10907 return true; 10908 } 10909 10910 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 10911 NamespaceDecl *Std = S.getStdNamespace(); 10912 if (!Std) { 10913 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 10914 return nullptr; 10915 } 10916 10917 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 10918 Loc, Sema::LookupOrdinaryName); 10919 if (!S.LookupQualifiedName(Result, Std)) { 10920 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 10921 return nullptr; 10922 } 10923 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 10924 if (!Template) { 10925 Result.suppressDiagnostics(); 10926 // We found something weird. Complain about the first thing we found. 10927 NamedDecl *Found = *Result.begin(); 10928 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 10929 return nullptr; 10930 } 10931 10932 // We found some template called std::initializer_list. Now verify that it's 10933 // correct. 10934 TemplateParameterList *Params = Template->getTemplateParameters(); 10935 if (Params->getMinRequiredArguments() != 1 || 10936 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 10937 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 10938 return nullptr; 10939 } 10940 10941 return Template; 10942 } 10943 10944 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 10945 if (!StdInitializerList) { 10946 StdInitializerList = LookupStdInitializerList(*this, Loc); 10947 if (!StdInitializerList) 10948 return QualType(); 10949 } 10950 10951 TemplateArgumentListInfo Args(Loc, Loc); 10952 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 10953 Context.getTrivialTypeSourceInfo(Element, 10954 Loc))); 10955 return Context.getCanonicalType( 10956 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 10957 } 10958 10959 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 10960 // C++ [dcl.init.list]p2: 10961 // A constructor is an initializer-list constructor if its first parameter 10962 // is of type std::initializer_list<E> or reference to possibly cv-qualified 10963 // std::initializer_list<E> for some type E, and either there are no other 10964 // parameters or else all other parameters have default arguments. 10965 if (Ctor->getNumParams() < 1 || 10966 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 10967 return false; 10968 10969 QualType ArgType = Ctor->getParamDecl(0)->getType(); 10970 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 10971 ArgType = RT->getPointeeType().getUnqualifiedType(); 10972 10973 return isStdInitializerList(ArgType, nullptr); 10974 } 10975 10976 /// Determine whether a using statement is in a context where it will be 10977 /// apply in all contexts. 10978 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 10979 switch (CurContext->getDeclKind()) { 10980 case Decl::TranslationUnit: 10981 return true; 10982 case Decl::LinkageSpec: 10983 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 10984 default: 10985 return false; 10986 } 10987 } 10988 10989 namespace { 10990 10991 // Callback to only accept typo corrections that are namespaces. 10992 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 10993 public: 10994 bool ValidateCandidate(const TypoCorrection &candidate) override { 10995 if (NamedDecl *ND = candidate.getCorrectionDecl()) 10996 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 10997 return false; 10998 } 10999 11000 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11001 return std::make_unique<NamespaceValidatorCCC>(*this); 11002 } 11003 }; 11004 11005 } 11006 11007 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11008 CXXScopeSpec &SS, 11009 SourceLocation IdentLoc, 11010 IdentifierInfo *Ident) { 11011 R.clear(); 11012 NamespaceValidatorCCC CCC{}; 11013 if (TypoCorrection Corrected = 11014 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11015 Sema::CTK_ErrorRecovery)) { 11016 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11017 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11018 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11019 Ident->getName().equals(CorrectedStr); 11020 S.diagnoseTypo(Corrected, 11021 S.PDiag(diag::err_using_directive_member_suggest) 11022 << Ident << DC << DroppedSpecifier << SS.getRange(), 11023 S.PDiag(diag::note_namespace_defined_here)); 11024 } else { 11025 S.diagnoseTypo(Corrected, 11026 S.PDiag(diag::err_using_directive_suggest) << Ident, 11027 S.PDiag(diag::note_namespace_defined_here)); 11028 } 11029 R.addDecl(Corrected.getFoundDecl()); 11030 return true; 11031 } 11032 return false; 11033 } 11034 11035 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11036 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11037 SourceLocation IdentLoc, 11038 IdentifierInfo *NamespcName, 11039 const ParsedAttributesView &AttrList) { 11040 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11041 assert(NamespcName && "Invalid NamespcName."); 11042 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11043 11044 // This can only happen along a recovery path. 11045 while (S->isTemplateParamScope()) 11046 S = S->getParent(); 11047 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11048 11049 UsingDirectiveDecl *UDir = nullptr; 11050 NestedNameSpecifier *Qualifier = nullptr; 11051 if (SS.isSet()) 11052 Qualifier = SS.getScopeRep(); 11053 11054 // Lookup namespace name. 11055 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11056 LookupParsedName(R, S, &SS); 11057 if (R.isAmbiguous()) 11058 return nullptr; 11059 11060 if (R.empty()) { 11061 R.clear(); 11062 // Allow "using namespace std;" or "using namespace ::std;" even if 11063 // "std" hasn't been defined yet, for GCC compatibility. 11064 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11065 NamespcName->isStr("std")) { 11066 Diag(IdentLoc, diag::ext_using_undefined_std); 11067 R.addDecl(getOrCreateStdNamespace()); 11068 R.resolveKind(); 11069 } 11070 // Otherwise, attempt typo correction. 11071 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11072 } 11073 11074 if (!R.empty()) { 11075 NamedDecl *Named = R.getRepresentativeDecl(); 11076 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11077 assert(NS && "expected namespace decl"); 11078 11079 // The use of a nested name specifier may trigger deprecation warnings. 11080 DiagnoseUseOfDecl(Named, IdentLoc); 11081 11082 // C++ [namespace.udir]p1: 11083 // A using-directive specifies that the names in the nominated 11084 // namespace can be used in the scope in which the 11085 // using-directive appears after the using-directive. During 11086 // unqualified name lookup (3.4.1), the names appear as if they 11087 // were declared in the nearest enclosing namespace which 11088 // contains both the using-directive and the nominated 11089 // namespace. [Note: in this context, "contains" means "contains 11090 // directly or indirectly". ] 11091 11092 // Find enclosing context containing both using-directive and 11093 // nominated namespace. 11094 DeclContext *CommonAncestor = NS; 11095 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11096 CommonAncestor = CommonAncestor->getParent(); 11097 11098 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11099 SS.getWithLocInContext(Context), 11100 IdentLoc, Named, CommonAncestor); 11101 11102 if (IsUsingDirectiveInToplevelContext(CurContext) && 11103 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11104 Diag(IdentLoc, diag::warn_using_directive_in_header); 11105 } 11106 11107 PushUsingDirective(S, UDir); 11108 } else { 11109 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11110 } 11111 11112 if (UDir) 11113 ProcessDeclAttributeList(S, UDir, AttrList); 11114 11115 return UDir; 11116 } 11117 11118 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11119 // If the scope has an associated entity and the using directive is at 11120 // namespace or translation unit scope, add the UsingDirectiveDecl into 11121 // its lookup structure so qualified name lookup can find it. 11122 DeclContext *Ctx = S->getEntity(); 11123 if (Ctx && !Ctx->isFunctionOrMethod()) 11124 Ctx->addDecl(UDir); 11125 else 11126 // Otherwise, it is at block scope. The using-directives will affect lookup 11127 // only to the end of the scope. 11128 S->PushUsingDirective(UDir); 11129 } 11130 11131 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11132 SourceLocation UsingLoc, 11133 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11134 UnqualifiedId &Name, 11135 SourceLocation EllipsisLoc, 11136 const ParsedAttributesView &AttrList) { 11137 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11138 11139 if (SS.isEmpty()) { 11140 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11141 return nullptr; 11142 } 11143 11144 switch (Name.getKind()) { 11145 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11146 case UnqualifiedIdKind::IK_Identifier: 11147 case UnqualifiedIdKind::IK_OperatorFunctionId: 11148 case UnqualifiedIdKind::IK_LiteralOperatorId: 11149 case UnqualifiedIdKind::IK_ConversionFunctionId: 11150 break; 11151 11152 case UnqualifiedIdKind::IK_ConstructorName: 11153 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11154 // C++11 inheriting constructors. 11155 Diag(Name.getBeginLoc(), 11156 getLangOpts().CPlusPlus11 11157 ? diag::warn_cxx98_compat_using_decl_constructor 11158 : diag::err_using_decl_constructor) 11159 << SS.getRange(); 11160 11161 if (getLangOpts().CPlusPlus11) break; 11162 11163 return nullptr; 11164 11165 case UnqualifiedIdKind::IK_DestructorName: 11166 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11167 return nullptr; 11168 11169 case UnqualifiedIdKind::IK_TemplateId: 11170 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11171 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11172 return nullptr; 11173 11174 case UnqualifiedIdKind::IK_DeductionGuideName: 11175 llvm_unreachable("cannot parse qualified deduction guide name"); 11176 } 11177 11178 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11179 DeclarationName TargetName = TargetNameInfo.getName(); 11180 if (!TargetName) 11181 return nullptr; 11182 11183 // Warn about access declarations. 11184 if (UsingLoc.isInvalid()) { 11185 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11186 ? diag::err_access_decl 11187 : diag::warn_access_decl_deprecated) 11188 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11189 } 11190 11191 if (EllipsisLoc.isInvalid()) { 11192 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11193 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11194 return nullptr; 11195 } else { 11196 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11197 !TargetNameInfo.containsUnexpandedParameterPack()) { 11198 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11199 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11200 EllipsisLoc = SourceLocation(); 11201 } 11202 } 11203 11204 NamedDecl *UD = 11205 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11206 SS, TargetNameInfo, EllipsisLoc, AttrList, 11207 /*IsInstantiation*/false); 11208 if (UD) 11209 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11210 11211 return UD; 11212 } 11213 11214 /// Determine whether a using declaration considers the given 11215 /// declarations as "equivalent", e.g., if they are redeclarations of 11216 /// the same entity or are both typedefs of the same type. 11217 static bool 11218 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11219 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11220 return true; 11221 11222 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11223 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11224 return Context.hasSameType(TD1->getUnderlyingType(), 11225 TD2->getUnderlyingType()); 11226 11227 return false; 11228 } 11229 11230 11231 /// Determines whether to create a using shadow decl for a particular 11232 /// decl, given the set of decls existing prior to this using lookup. 11233 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11234 const LookupResult &Previous, 11235 UsingShadowDecl *&PrevShadow) { 11236 // Diagnose finding a decl which is not from a base class of the 11237 // current class. We do this now because there are cases where this 11238 // function will silently decide not to build a shadow decl, which 11239 // will pre-empt further diagnostics. 11240 // 11241 // We don't need to do this in C++11 because we do the check once on 11242 // the qualifier. 11243 // 11244 // FIXME: diagnose the following if we care enough: 11245 // struct A { int foo; }; 11246 // struct B : A { using A::foo; }; 11247 // template <class T> struct C : A {}; 11248 // template <class T> struct D : C<T> { using B::foo; } // <--- 11249 // This is invalid (during instantiation) in C++03 because B::foo 11250 // resolves to the using decl in B, which is not a base class of D<T>. 11251 // We can't diagnose it immediately because C<T> is an unknown 11252 // specialization. The UsingShadowDecl in D<T> then points directly 11253 // to A::foo, which will look well-formed when we instantiate. 11254 // The right solution is to not collapse the shadow-decl chain. 11255 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11256 DeclContext *OrigDC = Orig->getDeclContext(); 11257 11258 // Handle enums and anonymous structs. 11259 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11260 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11261 while (OrigRec->isAnonymousStructOrUnion()) 11262 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11263 11264 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11265 if (OrigDC == CurContext) { 11266 Diag(Using->getLocation(), 11267 diag::err_using_decl_nested_name_specifier_is_current_class) 11268 << Using->getQualifierLoc().getSourceRange(); 11269 Diag(Orig->getLocation(), diag::note_using_decl_target); 11270 Using->setInvalidDecl(); 11271 return true; 11272 } 11273 11274 Diag(Using->getQualifierLoc().getBeginLoc(), 11275 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11276 << Using->getQualifier() 11277 << cast<CXXRecordDecl>(CurContext) 11278 << Using->getQualifierLoc().getSourceRange(); 11279 Diag(Orig->getLocation(), diag::note_using_decl_target); 11280 Using->setInvalidDecl(); 11281 return true; 11282 } 11283 } 11284 11285 if (Previous.empty()) return false; 11286 11287 NamedDecl *Target = Orig; 11288 if (isa<UsingShadowDecl>(Target)) 11289 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11290 11291 // If the target happens to be one of the previous declarations, we 11292 // don't have a conflict. 11293 // 11294 // FIXME: but we might be increasing its access, in which case we 11295 // should redeclare it. 11296 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11297 bool FoundEquivalentDecl = false; 11298 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11299 I != E; ++I) { 11300 NamedDecl *D = (*I)->getUnderlyingDecl(); 11301 // We can have UsingDecls in our Previous results because we use the same 11302 // LookupResult for checking whether the UsingDecl itself is a valid 11303 // redeclaration. 11304 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11305 continue; 11306 11307 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11308 // C++ [class.mem]p19: 11309 // If T is the name of a class, then [every named member other than 11310 // a non-static data member] shall have a name different from T 11311 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11312 !isa<IndirectFieldDecl>(Target) && 11313 !isa<UnresolvedUsingValueDecl>(Target) && 11314 DiagnoseClassNameShadow( 11315 CurContext, 11316 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11317 return true; 11318 } 11319 11320 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11321 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11322 PrevShadow = Shadow; 11323 FoundEquivalentDecl = true; 11324 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11325 // We don't conflict with an existing using shadow decl of an equivalent 11326 // declaration, but we're not a redeclaration of it. 11327 FoundEquivalentDecl = true; 11328 } 11329 11330 if (isVisible(D)) 11331 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11332 } 11333 11334 if (FoundEquivalentDecl) 11335 return false; 11336 11337 if (FunctionDecl *FD = Target->getAsFunction()) { 11338 NamedDecl *OldDecl = nullptr; 11339 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11340 /*IsForUsingDecl*/ true)) { 11341 case Ovl_Overload: 11342 return false; 11343 11344 case Ovl_NonFunction: 11345 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11346 break; 11347 11348 // We found a decl with the exact signature. 11349 case Ovl_Match: 11350 // If we're in a record, we want to hide the target, so we 11351 // return true (without a diagnostic) to tell the caller not to 11352 // build a shadow decl. 11353 if (CurContext->isRecord()) 11354 return true; 11355 11356 // If we're not in a record, this is an error. 11357 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11358 break; 11359 } 11360 11361 Diag(Target->getLocation(), diag::note_using_decl_target); 11362 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11363 Using->setInvalidDecl(); 11364 return true; 11365 } 11366 11367 // Target is not a function. 11368 11369 if (isa<TagDecl>(Target)) { 11370 // No conflict between a tag and a non-tag. 11371 if (!Tag) return false; 11372 11373 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11374 Diag(Target->getLocation(), diag::note_using_decl_target); 11375 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11376 Using->setInvalidDecl(); 11377 return true; 11378 } 11379 11380 // No conflict between a tag and a non-tag. 11381 if (!NonTag) return false; 11382 11383 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11384 Diag(Target->getLocation(), diag::note_using_decl_target); 11385 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11386 Using->setInvalidDecl(); 11387 return true; 11388 } 11389 11390 /// Determine whether a direct base class is a virtual base class. 11391 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11392 if (!Derived->getNumVBases()) 11393 return false; 11394 for (auto &B : Derived->bases()) 11395 if (B.getType()->getAsCXXRecordDecl() == Base) 11396 return B.isVirtual(); 11397 llvm_unreachable("not a direct base class"); 11398 } 11399 11400 /// Builds a shadow declaration corresponding to a 'using' declaration. 11401 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11402 UsingDecl *UD, 11403 NamedDecl *Orig, 11404 UsingShadowDecl *PrevDecl) { 11405 // If we resolved to another shadow declaration, just coalesce them. 11406 NamedDecl *Target = Orig; 11407 if (isa<UsingShadowDecl>(Target)) { 11408 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11409 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11410 } 11411 11412 NamedDecl *NonTemplateTarget = Target; 11413 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11414 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11415 11416 UsingShadowDecl *Shadow; 11417 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11418 bool IsVirtualBase = 11419 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11420 UD->getQualifier()->getAsRecordDecl()); 11421 Shadow = ConstructorUsingShadowDecl::Create( 11422 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11423 } else { 11424 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11425 Target); 11426 } 11427 UD->addShadowDecl(Shadow); 11428 11429 Shadow->setAccess(UD->getAccess()); 11430 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11431 Shadow->setInvalidDecl(); 11432 11433 Shadow->setPreviousDecl(PrevDecl); 11434 11435 if (S) 11436 PushOnScopeChains(Shadow, S); 11437 else 11438 CurContext->addDecl(Shadow); 11439 11440 11441 return Shadow; 11442 } 11443 11444 /// Hides a using shadow declaration. This is required by the current 11445 /// using-decl implementation when a resolvable using declaration in a 11446 /// class is followed by a declaration which would hide or override 11447 /// one or more of the using decl's targets; for example: 11448 /// 11449 /// struct Base { void foo(int); }; 11450 /// struct Derived : Base { 11451 /// using Base::foo; 11452 /// void foo(int); 11453 /// }; 11454 /// 11455 /// The governing language is C++03 [namespace.udecl]p12: 11456 /// 11457 /// When a using-declaration brings names from a base class into a 11458 /// derived class scope, member functions in the derived class 11459 /// override and/or hide member functions with the same name and 11460 /// parameter types in a base class (rather than conflicting). 11461 /// 11462 /// There are two ways to implement this: 11463 /// (1) optimistically create shadow decls when they're not hidden 11464 /// by existing declarations, or 11465 /// (2) don't create any shadow decls (or at least don't make them 11466 /// visible) until we've fully parsed/instantiated the class. 11467 /// The problem with (1) is that we might have to retroactively remove 11468 /// a shadow decl, which requires several O(n) operations because the 11469 /// decl structures are (very reasonably) not designed for removal. 11470 /// (2) avoids this but is very fiddly and phase-dependent. 11471 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11472 if (Shadow->getDeclName().getNameKind() == 11473 DeclarationName::CXXConversionFunctionName) 11474 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11475 11476 // Remove it from the DeclContext... 11477 Shadow->getDeclContext()->removeDecl(Shadow); 11478 11479 // ...and the scope, if applicable... 11480 if (S) { 11481 S->RemoveDecl(Shadow); 11482 IdResolver.RemoveDecl(Shadow); 11483 } 11484 11485 // ...and the using decl. 11486 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11487 11488 // TODO: complain somehow if Shadow was used. It shouldn't 11489 // be possible for this to happen, because...? 11490 } 11491 11492 /// Find the base specifier for a base class with the given type. 11493 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11494 QualType DesiredBase, 11495 bool &AnyDependentBases) { 11496 // Check whether the named type is a direct base class. 11497 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11498 .getUnqualifiedType(); 11499 for (auto &Base : Derived->bases()) { 11500 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11501 if (CanonicalDesiredBase == BaseType) 11502 return &Base; 11503 if (BaseType->isDependentType()) 11504 AnyDependentBases = true; 11505 } 11506 return nullptr; 11507 } 11508 11509 namespace { 11510 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11511 public: 11512 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11513 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11514 : HasTypenameKeyword(HasTypenameKeyword), 11515 IsInstantiation(IsInstantiation), OldNNS(NNS), 11516 RequireMemberOf(RequireMemberOf) {} 11517 11518 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11519 NamedDecl *ND = Candidate.getCorrectionDecl(); 11520 11521 // Keywords are not valid here. 11522 if (!ND || isa<NamespaceDecl>(ND)) 11523 return false; 11524 11525 // Completely unqualified names are invalid for a 'using' declaration. 11526 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11527 return false; 11528 11529 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11530 // reject. 11531 11532 if (RequireMemberOf) { 11533 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11534 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11535 // No-one ever wants a using-declaration to name an injected-class-name 11536 // of a base class, unless they're declaring an inheriting constructor. 11537 ASTContext &Ctx = ND->getASTContext(); 11538 if (!Ctx.getLangOpts().CPlusPlus11) 11539 return false; 11540 QualType FoundType = Ctx.getRecordType(FoundRecord); 11541 11542 // Check that the injected-class-name is named as a member of its own 11543 // type; we don't want to suggest 'using Derived::Base;', since that 11544 // means something else. 11545 NestedNameSpecifier *Specifier = 11546 Candidate.WillReplaceSpecifier() 11547 ? Candidate.getCorrectionSpecifier() 11548 : OldNNS; 11549 if (!Specifier->getAsType() || 11550 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11551 return false; 11552 11553 // Check that this inheriting constructor declaration actually names a 11554 // direct base class of the current class. 11555 bool AnyDependentBases = false; 11556 if (!findDirectBaseWithType(RequireMemberOf, 11557 Ctx.getRecordType(FoundRecord), 11558 AnyDependentBases) && 11559 !AnyDependentBases) 11560 return false; 11561 } else { 11562 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11563 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11564 return false; 11565 11566 // FIXME: Check that the base class member is accessible? 11567 } 11568 } else { 11569 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11570 if (FoundRecord && FoundRecord->isInjectedClassName()) 11571 return false; 11572 } 11573 11574 if (isa<TypeDecl>(ND)) 11575 return HasTypenameKeyword || !IsInstantiation; 11576 11577 return !HasTypenameKeyword; 11578 } 11579 11580 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11581 return std::make_unique<UsingValidatorCCC>(*this); 11582 } 11583 11584 private: 11585 bool HasTypenameKeyword; 11586 bool IsInstantiation; 11587 NestedNameSpecifier *OldNNS; 11588 CXXRecordDecl *RequireMemberOf; 11589 }; 11590 } // end anonymous namespace 11591 11592 /// Builds a using declaration. 11593 /// 11594 /// \param IsInstantiation - Whether this call arises from an 11595 /// instantiation of an unresolved using declaration. We treat 11596 /// the lookup differently for these declarations. 11597 NamedDecl *Sema::BuildUsingDeclaration( 11598 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11599 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11600 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11601 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11602 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11603 SourceLocation IdentLoc = NameInfo.getLoc(); 11604 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11605 11606 // FIXME: We ignore attributes for now. 11607 11608 // For an inheriting constructor declaration, the name of the using 11609 // declaration is the name of a constructor in this class, not in the 11610 // base class. 11611 DeclarationNameInfo UsingName = NameInfo; 11612 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11613 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11614 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11615 Context.getCanonicalType(Context.getRecordType(RD)))); 11616 11617 // Do the redeclaration lookup in the current scope. 11618 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11619 ForVisibleRedeclaration); 11620 Previous.setHideTags(false); 11621 if (S) { 11622 LookupName(Previous, S); 11623 11624 // It is really dumb that we have to do this. 11625 LookupResult::Filter F = Previous.makeFilter(); 11626 while (F.hasNext()) { 11627 NamedDecl *D = F.next(); 11628 if (!isDeclInScope(D, CurContext, S)) 11629 F.erase(); 11630 // If we found a local extern declaration that's not ordinarily visible, 11631 // and this declaration is being added to a non-block scope, ignore it. 11632 // We're only checking for scope conflicts here, not also for violations 11633 // of the linkage rules. 11634 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11635 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11636 F.erase(); 11637 } 11638 F.done(); 11639 } else { 11640 assert(IsInstantiation && "no scope in non-instantiation"); 11641 if (CurContext->isRecord()) 11642 LookupQualifiedName(Previous, CurContext); 11643 else { 11644 // No redeclaration check is needed here; in non-member contexts we 11645 // diagnosed all possible conflicts with other using-declarations when 11646 // building the template: 11647 // 11648 // For a dependent non-type using declaration, the only valid case is 11649 // if we instantiate to a single enumerator. We check for conflicts 11650 // between shadow declarations we introduce, and we check in the template 11651 // definition for conflicts between a non-type using declaration and any 11652 // other declaration, which together covers all cases. 11653 // 11654 // A dependent typename using declaration will never successfully 11655 // instantiate, since it will always name a class member, so we reject 11656 // that in the template definition. 11657 } 11658 } 11659 11660 // Check for invalid redeclarations. 11661 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 11662 SS, IdentLoc, Previous)) 11663 return nullptr; 11664 11665 // Check for bad qualifiers. 11666 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 11667 IdentLoc)) 11668 return nullptr; 11669 11670 DeclContext *LookupContext = computeDeclContext(SS); 11671 NamedDecl *D; 11672 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11673 if (!LookupContext || EllipsisLoc.isValid()) { 11674 if (HasTypenameKeyword) { 11675 // FIXME: not all declaration name kinds are legal here 11676 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 11677 UsingLoc, TypenameLoc, 11678 QualifierLoc, 11679 IdentLoc, NameInfo.getName(), 11680 EllipsisLoc); 11681 } else { 11682 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 11683 QualifierLoc, NameInfo, EllipsisLoc); 11684 } 11685 D->setAccess(AS); 11686 CurContext->addDecl(D); 11687 return D; 11688 } 11689 11690 auto Build = [&](bool Invalid) { 11691 UsingDecl *UD = 11692 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 11693 UsingName, HasTypenameKeyword); 11694 UD->setAccess(AS); 11695 CurContext->addDecl(UD); 11696 UD->setInvalidDecl(Invalid); 11697 return UD; 11698 }; 11699 auto BuildInvalid = [&]{ return Build(true); }; 11700 auto BuildValid = [&]{ return Build(false); }; 11701 11702 if (RequireCompleteDeclContext(SS, LookupContext)) 11703 return BuildInvalid(); 11704 11705 // Look up the target name. 11706 LookupResult R(*this, NameInfo, LookupOrdinaryName); 11707 11708 // Unlike most lookups, we don't always want to hide tag 11709 // declarations: tag names are visible through the using declaration 11710 // even if hidden by ordinary names, *except* in a dependent context 11711 // where it's important for the sanity of two-phase lookup. 11712 if (!IsInstantiation) 11713 R.setHideTags(false); 11714 11715 // For the purposes of this lookup, we have a base object type 11716 // equal to that of the current context. 11717 if (CurContext->isRecord()) { 11718 R.setBaseObjectType( 11719 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 11720 } 11721 11722 LookupQualifiedName(R, LookupContext); 11723 11724 // Try to correct typos if possible. If constructor name lookup finds no 11725 // results, that means the named class has no explicit constructors, and we 11726 // suppressed declaring implicit ones (probably because it's dependent or 11727 // invalid). 11728 if (R.empty() && 11729 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 11730 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 11731 // it will believe that glibc provides a ::gets in cases where it does not, 11732 // and will try to pull it into namespace std with a using-declaration. 11733 // Just ignore the using-declaration in that case. 11734 auto *II = NameInfo.getName().getAsIdentifierInfo(); 11735 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 11736 CurContext->isStdNamespace() && 11737 isa<TranslationUnitDecl>(LookupContext) && 11738 getSourceManager().isInSystemHeader(UsingLoc)) 11739 return nullptr; 11740 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 11741 dyn_cast<CXXRecordDecl>(CurContext)); 11742 if (TypoCorrection Corrected = 11743 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 11744 CTK_ErrorRecovery)) { 11745 // We reject candidates where DroppedSpecifier == true, hence the 11746 // literal '0' below. 11747 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 11748 << NameInfo.getName() << LookupContext << 0 11749 << SS.getRange()); 11750 11751 // If we picked a correction with no attached Decl we can't do anything 11752 // useful with it, bail out. 11753 NamedDecl *ND = Corrected.getCorrectionDecl(); 11754 if (!ND) 11755 return BuildInvalid(); 11756 11757 // If we corrected to an inheriting constructor, handle it as one. 11758 auto *RD = dyn_cast<CXXRecordDecl>(ND); 11759 if (RD && RD->isInjectedClassName()) { 11760 // The parent of the injected class name is the class itself. 11761 RD = cast<CXXRecordDecl>(RD->getParent()); 11762 11763 // Fix up the information we'll use to build the using declaration. 11764 if (Corrected.WillReplaceSpecifier()) { 11765 NestedNameSpecifierLocBuilder Builder; 11766 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 11767 QualifierLoc.getSourceRange()); 11768 QualifierLoc = Builder.getWithLocInContext(Context); 11769 } 11770 11771 // In this case, the name we introduce is the name of a derived class 11772 // constructor. 11773 auto *CurClass = cast<CXXRecordDecl>(CurContext); 11774 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11775 Context.getCanonicalType(Context.getRecordType(CurClass)))); 11776 UsingName.setNamedTypeInfo(nullptr); 11777 for (auto *Ctor : LookupConstructors(RD)) 11778 R.addDecl(Ctor); 11779 R.resolveKind(); 11780 } else { 11781 // FIXME: Pick up all the declarations if we found an overloaded 11782 // function. 11783 UsingName.setName(ND->getDeclName()); 11784 R.addDecl(ND); 11785 } 11786 } else { 11787 Diag(IdentLoc, diag::err_no_member) 11788 << NameInfo.getName() << LookupContext << SS.getRange(); 11789 return BuildInvalid(); 11790 } 11791 } 11792 11793 if (R.isAmbiguous()) 11794 return BuildInvalid(); 11795 11796 if (HasTypenameKeyword) { 11797 // If we asked for a typename and got a non-type decl, error out. 11798 if (!R.getAsSingle<TypeDecl>()) { 11799 Diag(IdentLoc, diag::err_using_typename_non_type); 11800 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11801 Diag((*I)->getUnderlyingDecl()->getLocation(), 11802 diag::note_using_decl_target); 11803 return BuildInvalid(); 11804 } 11805 } else { 11806 // If we asked for a non-typename and we got a type, error out, 11807 // but only if this is an instantiation of an unresolved using 11808 // decl. Otherwise just silently find the type name. 11809 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 11810 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 11811 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 11812 return BuildInvalid(); 11813 } 11814 } 11815 11816 // C++14 [namespace.udecl]p6: 11817 // A using-declaration shall not name a namespace. 11818 if (R.getAsSingle<NamespaceDecl>()) { 11819 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 11820 << SS.getRange(); 11821 return BuildInvalid(); 11822 } 11823 11824 // C++14 [namespace.udecl]p7: 11825 // A using-declaration shall not name a scoped enumerator. 11826 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 11827 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 11828 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 11829 << SS.getRange(); 11830 return BuildInvalid(); 11831 } 11832 } 11833 11834 UsingDecl *UD = BuildValid(); 11835 11836 // Some additional rules apply to inheriting constructors. 11837 if (UsingName.getName().getNameKind() == 11838 DeclarationName::CXXConstructorName) { 11839 // Suppress access diagnostics; the access check is instead performed at the 11840 // point of use for an inheriting constructor. 11841 R.suppressDiagnostics(); 11842 if (CheckInheritingConstructorUsingDecl(UD)) 11843 return UD; 11844 } 11845 11846 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 11847 UsingShadowDecl *PrevDecl = nullptr; 11848 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 11849 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 11850 } 11851 11852 return UD; 11853 } 11854 11855 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 11856 ArrayRef<NamedDecl *> Expansions) { 11857 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 11858 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 11859 isa<UsingPackDecl>(InstantiatedFrom)); 11860 11861 auto *UPD = 11862 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 11863 UPD->setAccess(InstantiatedFrom->getAccess()); 11864 CurContext->addDecl(UPD); 11865 return UPD; 11866 } 11867 11868 /// Additional checks for a using declaration referring to a constructor name. 11869 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 11870 assert(!UD->hasTypename() && "expecting a constructor name"); 11871 11872 const Type *SourceType = UD->getQualifier()->getAsType(); 11873 assert(SourceType && 11874 "Using decl naming constructor doesn't have type in scope spec."); 11875 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 11876 11877 // Check whether the named type is a direct base class. 11878 bool AnyDependentBases = false; 11879 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 11880 AnyDependentBases); 11881 if (!Base && !AnyDependentBases) { 11882 Diag(UD->getUsingLoc(), 11883 diag::err_using_decl_constructor_not_in_direct_base) 11884 << UD->getNameInfo().getSourceRange() 11885 << QualType(SourceType, 0) << TargetClass; 11886 UD->setInvalidDecl(); 11887 return true; 11888 } 11889 11890 if (Base) 11891 Base->setInheritConstructors(); 11892 11893 return false; 11894 } 11895 11896 /// Checks that the given using declaration is not an invalid 11897 /// redeclaration. Note that this is checking only for the using decl 11898 /// itself, not for any ill-formedness among the UsingShadowDecls. 11899 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 11900 bool HasTypenameKeyword, 11901 const CXXScopeSpec &SS, 11902 SourceLocation NameLoc, 11903 const LookupResult &Prev) { 11904 NestedNameSpecifier *Qual = SS.getScopeRep(); 11905 11906 // C++03 [namespace.udecl]p8: 11907 // C++0x [namespace.udecl]p10: 11908 // A using-declaration is a declaration and can therefore be used 11909 // repeatedly where (and only where) multiple declarations are 11910 // allowed. 11911 // 11912 // That's in non-member contexts. 11913 if (!CurContext->getRedeclContext()->isRecord()) { 11914 // A dependent qualifier outside a class can only ever resolve to an 11915 // enumeration type. Therefore it conflicts with any other non-type 11916 // declaration in the same scope. 11917 // FIXME: How should we check for dependent type-type conflicts at block 11918 // scope? 11919 if (Qual->isDependent() && !HasTypenameKeyword) { 11920 for (auto *D : Prev) { 11921 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 11922 bool OldCouldBeEnumerator = 11923 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 11924 Diag(NameLoc, 11925 OldCouldBeEnumerator ? diag::err_redefinition 11926 : diag::err_redefinition_different_kind) 11927 << Prev.getLookupName(); 11928 Diag(D->getLocation(), diag::note_previous_definition); 11929 return true; 11930 } 11931 } 11932 } 11933 return false; 11934 } 11935 11936 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 11937 NamedDecl *D = *I; 11938 11939 bool DTypename; 11940 NestedNameSpecifier *DQual; 11941 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 11942 DTypename = UD->hasTypename(); 11943 DQual = UD->getQualifier(); 11944 } else if (UnresolvedUsingValueDecl *UD 11945 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 11946 DTypename = false; 11947 DQual = UD->getQualifier(); 11948 } else if (UnresolvedUsingTypenameDecl *UD 11949 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 11950 DTypename = true; 11951 DQual = UD->getQualifier(); 11952 } else continue; 11953 11954 // using decls differ if one says 'typename' and the other doesn't. 11955 // FIXME: non-dependent using decls? 11956 if (HasTypenameKeyword != DTypename) continue; 11957 11958 // using decls differ if they name different scopes (but note that 11959 // template instantiation can cause this check to trigger when it 11960 // didn't before instantiation). 11961 if (Context.getCanonicalNestedNameSpecifier(Qual) != 11962 Context.getCanonicalNestedNameSpecifier(DQual)) 11963 continue; 11964 11965 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 11966 Diag(D->getLocation(), diag::note_using_decl) << 1; 11967 return true; 11968 } 11969 11970 return false; 11971 } 11972 11973 11974 /// Checks that the given nested-name qualifier used in a using decl 11975 /// in the current context is appropriately related to the current 11976 /// scope. If an error is found, diagnoses it and returns true. 11977 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 11978 bool HasTypename, 11979 const CXXScopeSpec &SS, 11980 const DeclarationNameInfo &NameInfo, 11981 SourceLocation NameLoc) { 11982 DeclContext *NamedContext = computeDeclContext(SS); 11983 11984 if (!CurContext->isRecord()) { 11985 // C++03 [namespace.udecl]p3: 11986 // C++0x [namespace.udecl]p8: 11987 // A using-declaration for a class member shall be a member-declaration. 11988 11989 // If we weren't able to compute a valid scope, it might validly be a 11990 // dependent class scope or a dependent enumeration unscoped scope. If 11991 // we have a 'typename' keyword, the scope must resolve to a class type. 11992 if ((HasTypename && !NamedContext) || 11993 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 11994 auto *RD = NamedContext 11995 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 11996 : nullptr; 11997 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 11998 RD = nullptr; 11999 12000 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12001 << SS.getRange(); 12002 12003 // If we have a complete, non-dependent source type, try to suggest a 12004 // way to get the same effect. 12005 if (!RD) 12006 return true; 12007 12008 // Find what this using-declaration was referring to. 12009 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12010 R.setHideTags(false); 12011 R.suppressDiagnostics(); 12012 LookupQualifiedName(R, RD); 12013 12014 if (R.getAsSingle<TypeDecl>()) { 12015 if (getLangOpts().CPlusPlus11) { 12016 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12017 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12018 << 0 // alias declaration 12019 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12020 NameInfo.getName().getAsString() + 12021 " = "); 12022 } else { 12023 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12024 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12025 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12026 << 1 // typedef declaration 12027 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12028 << FixItHint::CreateInsertion( 12029 InsertLoc, " " + NameInfo.getName().getAsString()); 12030 } 12031 } else if (R.getAsSingle<VarDecl>()) { 12032 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12033 // repeating the type of the static data member here. 12034 FixItHint FixIt; 12035 if (getLangOpts().CPlusPlus11) { 12036 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12037 FixIt = FixItHint::CreateReplacement( 12038 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12039 } 12040 12041 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12042 << 2 // reference declaration 12043 << FixIt; 12044 } else if (R.getAsSingle<EnumConstantDecl>()) { 12045 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12046 // repeating the type of the enumeration here, and we can't do so if 12047 // the type is anonymous. 12048 FixItHint FixIt; 12049 if (getLangOpts().CPlusPlus11) { 12050 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12051 FixIt = FixItHint::CreateReplacement( 12052 UsingLoc, 12053 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12054 } 12055 12056 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12057 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12058 << FixIt; 12059 } 12060 return true; 12061 } 12062 12063 // Otherwise, this might be valid. 12064 return false; 12065 } 12066 12067 // The current scope is a record. 12068 12069 // If the named context is dependent, we can't decide much. 12070 if (!NamedContext) { 12071 // FIXME: in C++0x, we can diagnose if we can prove that the 12072 // nested-name-specifier does not refer to a base class, which is 12073 // still possible in some cases. 12074 12075 // Otherwise we have to conservatively report that things might be 12076 // okay. 12077 return false; 12078 } 12079 12080 if (!NamedContext->isRecord()) { 12081 // Ideally this would point at the last name in the specifier, 12082 // but we don't have that level of source info. 12083 Diag(SS.getRange().getBegin(), 12084 diag::err_using_decl_nested_name_specifier_is_not_class) 12085 << SS.getScopeRep() << SS.getRange(); 12086 return true; 12087 } 12088 12089 if (!NamedContext->isDependentContext() && 12090 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12091 return true; 12092 12093 if (getLangOpts().CPlusPlus11) { 12094 // C++11 [namespace.udecl]p3: 12095 // In a using-declaration used as a member-declaration, the 12096 // nested-name-specifier shall name a base class of the class 12097 // being defined. 12098 12099 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12100 cast<CXXRecordDecl>(NamedContext))) { 12101 if (CurContext == NamedContext) { 12102 Diag(NameLoc, 12103 diag::err_using_decl_nested_name_specifier_is_current_class) 12104 << SS.getRange(); 12105 return true; 12106 } 12107 12108 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12109 Diag(SS.getRange().getBegin(), 12110 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12111 << SS.getScopeRep() 12112 << cast<CXXRecordDecl>(CurContext) 12113 << SS.getRange(); 12114 } 12115 return true; 12116 } 12117 12118 return false; 12119 } 12120 12121 // C++03 [namespace.udecl]p4: 12122 // A using-declaration used as a member-declaration shall refer 12123 // to a member of a base class of the class being defined [etc.]. 12124 12125 // Salient point: SS doesn't have to name a base class as long as 12126 // lookup only finds members from base classes. Therefore we can 12127 // diagnose here only if we can prove that that can't happen, 12128 // i.e. if the class hierarchies provably don't intersect. 12129 12130 // TODO: it would be nice if "definitely valid" results were cached 12131 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12132 // need to be repeated. 12133 12134 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12135 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12136 Bases.insert(Base); 12137 return true; 12138 }; 12139 12140 // Collect all bases. Return false if we find a dependent base. 12141 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12142 return false; 12143 12144 // Returns true if the base is dependent or is one of the accumulated base 12145 // classes. 12146 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12147 return !Bases.count(Base); 12148 }; 12149 12150 // Return false if the class has a dependent base or if it or one 12151 // of its bases is present in the base set of the current context. 12152 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12153 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12154 return false; 12155 12156 Diag(SS.getRange().getBegin(), 12157 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12158 << SS.getScopeRep() 12159 << cast<CXXRecordDecl>(CurContext) 12160 << SS.getRange(); 12161 12162 return true; 12163 } 12164 12165 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12166 MultiTemplateParamsArg TemplateParamLists, 12167 SourceLocation UsingLoc, UnqualifiedId &Name, 12168 const ParsedAttributesView &AttrList, 12169 TypeResult Type, Decl *DeclFromDeclSpec) { 12170 // Skip up to the relevant declaration scope. 12171 while (S->isTemplateParamScope()) 12172 S = S->getParent(); 12173 assert((S->getFlags() & Scope::DeclScope) && 12174 "got alias-declaration outside of declaration scope"); 12175 12176 if (Type.isInvalid()) 12177 return nullptr; 12178 12179 bool Invalid = false; 12180 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12181 TypeSourceInfo *TInfo = nullptr; 12182 GetTypeFromParser(Type.get(), &TInfo); 12183 12184 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12185 return nullptr; 12186 12187 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12188 UPPC_DeclarationType)) { 12189 Invalid = true; 12190 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12191 TInfo->getTypeLoc().getBeginLoc()); 12192 } 12193 12194 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12195 TemplateParamLists.size() 12196 ? forRedeclarationInCurContext() 12197 : ForVisibleRedeclaration); 12198 LookupName(Previous, S); 12199 12200 // Warn about shadowing the name of a template parameter. 12201 if (Previous.isSingleResult() && 12202 Previous.getFoundDecl()->isTemplateParameter()) { 12203 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12204 Previous.clear(); 12205 } 12206 12207 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12208 "name in alias declaration must be an identifier"); 12209 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12210 Name.StartLocation, 12211 Name.Identifier, TInfo); 12212 12213 NewTD->setAccess(AS); 12214 12215 if (Invalid) 12216 NewTD->setInvalidDecl(); 12217 12218 ProcessDeclAttributeList(S, NewTD, AttrList); 12219 AddPragmaAttributes(S, NewTD); 12220 12221 CheckTypedefForVariablyModifiedType(S, NewTD); 12222 Invalid |= NewTD->isInvalidDecl(); 12223 12224 bool Redeclaration = false; 12225 12226 NamedDecl *NewND; 12227 if (TemplateParamLists.size()) { 12228 TypeAliasTemplateDecl *OldDecl = nullptr; 12229 TemplateParameterList *OldTemplateParams = nullptr; 12230 12231 if (TemplateParamLists.size() != 1) { 12232 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12233 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12234 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12235 } 12236 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12237 12238 // Check that we can declare a template here. 12239 if (CheckTemplateDeclScope(S, TemplateParams)) 12240 return nullptr; 12241 12242 // Only consider previous declarations in the same scope. 12243 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12244 /*ExplicitInstantiationOrSpecialization*/false); 12245 if (!Previous.empty()) { 12246 Redeclaration = true; 12247 12248 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12249 if (!OldDecl && !Invalid) { 12250 Diag(UsingLoc, diag::err_redefinition_different_kind) 12251 << Name.Identifier; 12252 12253 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12254 if (OldD->getLocation().isValid()) 12255 Diag(OldD->getLocation(), diag::note_previous_definition); 12256 12257 Invalid = true; 12258 } 12259 12260 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12261 if (TemplateParameterListsAreEqual(TemplateParams, 12262 OldDecl->getTemplateParameters(), 12263 /*Complain=*/true, 12264 TPL_TemplateMatch)) 12265 OldTemplateParams = 12266 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12267 else 12268 Invalid = true; 12269 12270 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12271 if (!Invalid && 12272 !Context.hasSameType(OldTD->getUnderlyingType(), 12273 NewTD->getUnderlyingType())) { 12274 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12275 // but we can't reasonably accept it. 12276 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12277 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12278 if (OldTD->getLocation().isValid()) 12279 Diag(OldTD->getLocation(), diag::note_previous_definition); 12280 Invalid = true; 12281 } 12282 } 12283 } 12284 12285 // Merge any previous default template arguments into our parameters, 12286 // and check the parameter list. 12287 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12288 TPC_TypeAliasTemplate)) 12289 return nullptr; 12290 12291 TypeAliasTemplateDecl *NewDecl = 12292 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12293 Name.Identifier, TemplateParams, 12294 NewTD); 12295 NewTD->setDescribedAliasTemplate(NewDecl); 12296 12297 NewDecl->setAccess(AS); 12298 12299 if (Invalid) 12300 NewDecl->setInvalidDecl(); 12301 else if (OldDecl) { 12302 NewDecl->setPreviousDecl(OldDecl); 12303 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12304 } 12305 12306 NewND = NewDecl; 12307 } else { 12308 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12309 setTagNameForLinkagePurposes(TD, NewTD); 12310 handleTagNumbering(TD, S); 12311 } 12312 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12313 NewND = NewTD; 12314 } 12315 12316 PushOnScopeChains(NewND, S); 12317 ActOnDocumentableDecl(NewND); 12318 return NewND; 12319 } 12320 12321 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12322 SourceLocation AliasLoc, 12323 IdentifierInfo *Alias, CXXScopeSpec &SS, 12324 SourceLocation IdentLoc, 12325 IdentifierInfo *Ident) { 12326 12327 // Lookup the namespace name. 12328 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12329 LookupParsedName(R, S, &SS); 12330 12331 if (R.isAmbiguous()) 12332 return nullptr; 12333 12334 if (R.empty()) { 12335 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12336 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12337 return nullptr; 12338 } 12339 } 12340 assert(!R.isAmbiguous() && !R.empty()); 12341 NamedDecl *ND = R.getRepresentativeDecl(); 12342 12343 // Check if we have a previous declaration with the same name. 12344 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12345 ForVisibleRedeclaration); 12346 LookupName(PrevR, S); 12347 12348 // Check we're not shadowing a template parameter. 12349 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12350 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12351 PrevR.clear(); 12352 } 12353 12354 // Filter out any other lookup result from an enclosing scope. 12355 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12356 /*AllowInlineNamespace*/false); 12357 12358 // Find the previous declaration and check that we can redeclare it. 12359 NamespaceAliasDecl *Prev = nullptr; 12360 if (PrevR.isSingleResult()) { 12361 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12362 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12363 // We already have an alias with the same name that points to the same 12364 // namespace; check that it matches. 12365 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12366 Prev = AD; 12367 } else if (isVisible(PrevDecl)) { 12368 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12369 << Alias; 12370 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12371 << AD->getNamespace(); 12372 return nullptr; 12373 } 12374 } else if (isVisible(PrevDecl)) { 12375 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12376 ? diag::err_redefinition 12377 : diag::err_redefinition_different_kind; 12378 Diag(AliasLoc, DiagID) << Alias; 12379 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12380 return nullptr; 12381 } 12382 } 12383 12384 // The use of a nested name specifier may trigger deprecation warnings. 12385 DiagnoseUseOfDecl(ND, IdentLoc); 12386 12387 NamespaceAliasDecl *AliasDecl = 12388 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12389 Alias, SS.getWithLocInContext(Context), 12390 IdentLoc, ND); 12391 if (Prev) 12392 AliasDecl->setPreviousDecl(Prev); 12393 12394 PushOnScopeChains(AliasDecl, S); 12395 return AliasDecl; 12396 } 12397 12398 namespace { 12399 struct SpecialMemberExceptionSpecInfo 12400 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12401 SourceLocation Loc; 12402 Sema::ImplicitExceptionSpecification ExceptSpec; 12403 12404 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12405 Sema::CXXSpecialMember CSM, 12406 Sema::InheritedConstructorInfo *ICI, 12407 SourceLocation Loc) 12408 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12409 12410 bool visitBase(CXXBaseSpecifier *Base); 12411 bool visitField(FieldDecl *FD); 12412 12413 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12414 unsigned Quals); 12415 12416 void visitSubobjectCall(Subobject Subobj, 12417 Sema::SpecialMemberOverloadResult SMOR); 12418 }; 12419 } 12420 12421 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12422 auto *RT = Base->getType()->getAs<RecordType>(); 12423 if (!RT) 12424 return false; 12425 12426 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12427 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12428 if (auto *BaseCtor = SMOR.getMethod()) { 12429 visitSubobjectCall(Base, BaseCtor); 12430 return false; 12431 } 12432 12433 visitClassSubobject(BaseClass, Base, 0); 12434 return false; 12435 } 12436 12437 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12438 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12439 Expr *E = FD->getInClassInitializer(); 12440 if (!E) 12441 // FIXME: It's a little wasteful to build and throw away a 12442 // CXXDefaultInitExpr here. 12443 // FIXME: We should have a single context note pointing at Loc, and 12444 // this location should be MD->getLocation() instead, since that's 12445 // the location where we actually use the default init expression. 12446 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12447 if (E) 12448 ExceptSpec.CalledExpr(E); 12449 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12450 ->getAs<RecordType>()) { 12451 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12452 FD->getType().getCVRQualifiers()); 12453 } 12454 return false; 12455 } 12456 12457 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12458 Subobject Subobj, 12459 unsigned Quals) { 12460 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12461 bool IsMutable = Field && Field->isMutable(); 12462 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12463 } 12464 12465 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12466 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12467 // Note, if lookup fails, it doesn't matter what exception specification we 12468 // choose because the special member will be deleted. 12469 if (CXXMethodDecl *MD = SMOR.getMethod()) 12470 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12471 } 12472 12473 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12474 llvm::APSInt Result; 12475 ExprResult Converted = CheckConvertedConstantExpression( 12476 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12477 ExplicitSpec.setExpr(Converted.get()); 12478 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12479 ExplicitSpec.setKind(Result.getBoolValue() 12480 ? ExplicitSpecKind::ResolvedTrue 12481 : ExplicitSpecKind::ResolvedFalse); 12482 return true; 12483 } 12484 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12485 return false; 12486 } 12487 12488 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12489 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12490 if (!ExplicitExpr->isTypeDependent()) 12491 tryResolveExplicitSpecifier(ES); 12492 return ES; 12493 } 12494 12495 static Sema::ImplicitExceptionSpecification 12496 ComputeDefaultedSpecialMemberExceptionSpec( 12497 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12498 Sema::InheritedConstructorInfo *ICI) { 12499 ComputingExceptionSpec CES(S, MD, Loc); 12500 12501 CXXRecordDecl *ClassDecl = MD->getParent(); 12502 12503 // C++ [except.spec]p14: 12504 // An implicitly declared special member function (Clause 12) shall have an 12505 // exception-specification. [...] 12506 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12507 if (ClassDecl->isInvalidDecl()) 12508 return Info.ExceptSpec; 12509 12510 // FIXME: If this diagnostic fires, we're probably missing a check for 12511 // attempting to resolve an exception specification before it's known 12512 // at a higher level. 12513 if (S.RequireCompleteType(MD->getLocation(), 12514 S.Context.getRecordType(ClassDecl), 12515 diag::err_exception_spec_incomplete_type)) 12516 return Info.ExceptSpec; 12517 12518 // C++1z [except.spec]p7: 12519 // [Look for exceptions thrown by] a constructor selected [...] to 12520 // initialize a potentially constructed subobject, 12521 // C++1z [except.spec]p8: 12522 // The exception specification for an implicitly-declared destructor, or a 12523 // destructor without a noexcept-specifier, is potentially-throwing if and 12524 // only if any of the destructors for any of its potentially constructed 12525 // subojects is potentially throwing. 12526 // FIXME: We respect the first rule but ignore the "potentially constructed" 12527 // in the second rule to resolve a core issue (no number yet) that would have 12528 // us reject: 12529 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12530 // struct B : A {}; 12531 // struct C : B { void f(); }; 12532 // ... due to giving B::~B() a non-throwing exception specification. 12533 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12534 : Info.VisitAllBases); 12535 12536 return Info.ExceptSpec; 12537 } 12538 12539 namespace { 12540 /// RAII object to register a special member as being currently declared. 12541 struct DeclaringSpecialMember { 12542 Sema &S; 12543 Sema::SpecialMemberDecl D; 12544 Sema::ContextRAII SavedContext; 12545 bool WasAlreadyBeingDeclared; 12546 12547 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12548 : S(S), D(RD, CSM), SavedContext(S, RD) { 12549 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12550 if (WasAlreadyBeingDeclared) 12551 // This almost never happens, but if it does, ensure that our cache 12552 // doesn't contain a stale result. 12553 S.SpecialMemberCache.clear(); 12554 else { 12555 // Register a note to be produced if we encounter an error while 12556 // declaring the special member. 12557 Sema::CodeSynthesisContext Ctx; 12558 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12559 // FIXME: We don't have a location to use here. Using the class's 12560 // location maintains the fiction that we declare all special members 12561 // with the class, but (1) it's not clear that lying about that helps our 12562 // users understand what's going on, and (2) there may be outer contexts 12563 // on the stack (some of which are relevant) and printing them exposes 12564 // our lies. 12565 Ctx.PointOfInstantiation = RD->getLocation(); 12566 Ctx.Entity = RD; 12567 Ctx.SpecialMember = CSM; 12568 S.pushCodeSynthesisContext(Ctx); 12569 } 12570 } 12571 ~DeclaringSpecialMember() { 12572 if (!WasAlreadyBeingDeclared) { 12573 S.SpecialMembersBeingDeclared.erase(D); 12574 S.popCodeSynthesisContext(); 12575 } 12576 } 12577 12578 /// Are we already trying to declare this special member? 12579 bool isAlreadyBeingDeclared() const { 12580 return WasAlreadyBeingDeclared; 12581 } 12582 }; 12583 } 12584 12585 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12586 // Look up any existing declarations, but don't trigger declaration of all 12587 // implicit special members with this name. 12588 DeclarationName Name = FD->getDeclName(); 12589 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12590 ForExternalRedeclaration); 12591 for (auto *D : FD->getParent()->lookup(Name)) 12592 if (auto *Acceptable = R.getAcceptableDecl(D)) 12593 R.addDecl(Acceptable); 12594 R.resolveKind(); 12595 R.suppressDiagnostics(); 12596 12597 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12598 } 12599 12600 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12601 QualType ResultTy, 12602 ArrayRef<QualType> Args) { 12603 // Build an exception specification pointing back at this constructor. 12604 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12605 12606 LangAS AS = getDefaultCXXMethodAddrSpace(); 12607 if (AS != LangAS::Default) { 12608 EPI.TypeQuals.addAddressSpace(AS); 12609 } 12610 12611 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12612 SpecialMem->setType(QT); 12613 } 12614 12615 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12616 CXXRecordDecl *ClassDecl) { 12617 // C++ [class.ctor]p5: 12618 // A default constructor for a class X is a constructor of class X 12619 // that can be called without an argument. If there is no 12620 // user-declared constructor for class X, a default constructor is 12621 // implicitly declared. An implicitly-declared default constructor 12622 // is an inline public member of its class. 12623 assert(ClassDecl->needsImplicitDefaultConstructor() && 12624 "Should not build implicit default constructor!"); 12625 12626 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12627 if (DSM.isAlreadyBeingDeclared()) 12628 return nullptr; 12629 12630 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12631 CXXDefaultConstructor, 12632 false); 12633 12634 // Create the actual constructor declaration. 12635 CanQualType ClassType 12636 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12637 SourceLocation ClassLoc = ClassDecl->getLocation(); 12638 DeclarationName Name 12639 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12640 DeclarationNameInfo NameInfo(Name, ClassLoc); 12641 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12642 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12643 /*TInfo=*/nullptr, ExplicitSpecifier(), 12644 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12645 Constexpr ? CSK_constexpr : CSK_unspecified); 12646 DefaultCon->setAccess(AS_public); 12647 DefaultCon->setDefaulted(); 12648 12649 if (getLangOpts().CUDA) { 12650 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 12651 DefaultCon, 12652 /* ConstRHS */ false, 12653 /* Diagnose */ false); 12654 } 12655 12656 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 12657 12658 // We don't need to use SpecialMemberIsTrivial here; triviality for default 12659 // constructors is easy to compute. 12660 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 12661 12662 // Note that we have declared this constructor. 12663 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 12664 12665 Scope *S = getScopeForContext(ClassDecl); 12666 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 12667 12668 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 12669 SetDeclDeleted(DefaultCon, ClassLoc); 12670 12671 if (S) 12672 PushOnScopeChains(DefaultCon, S, false); 12673 ClassDecl->addDecl(DefaultCon); 12674 12675 return DefaultCon; 12676 } 12677 12678 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 12679 CXXConstructorDecl *Constructor) { 12680 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 12681 !Constructor->doesThisDeclarationHaveABody() && 12682 !Constructor->isDeleted()) && 12683 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 12684 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12685 return; 12686 12687 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12688 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 12689 12690 SynthesizedFunctionScope Scope(*this, Constructor); 12691 12692 // The exception specification is needed because we are defining the 12693 // function. 12694 ResolveExceptionSpec(CurrentLocation, 12695 Constructor->getType()->castAs<FunctionProtoType>()); 12696 MarkVTableUsed(CurrentLocation, ClassDecl); 12697 12698 // Add a context note for diagnostics produced after this point. 12699 Scope.addContextNote(CurrentLocation); 12700 12701 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 12702 Constructor->setInvalidDecl(); 12703 return; 12704 } 12705 12706 SourceLocation Loc = Constructor->getEndLoc().isValid() 12707 ? Constructor->getEndLoc() 12708 : Constructor->getLocation(); 12709 Constructor->setBody(new (Context) CompoundStmt(Loc)); 12710 Constructor->markUsed(Context); 12711 12712 if (ASTMutationListener *L = getASTMutationListener()) { 12713 L->CompletedImplicitDefinition(Constructor); 12714 } 12715 12716 DiagnoseUninitializedFields(*this, Constructor); 12717 } 12718 12719 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 12720 // Perform any delayed checks on exception specifications. 12721 CheckDelayedMemberExceptionSpecs(); 12722 } 12723 12724 /// Find or create the fake constructor we synthesize to model constructing an 12725 /// object of a derived class via a constructor of a base class. 12726 CXXConstructorDecl * 12727 Sema::findInheritingConstructor(SourceLocation Loc, 12728 CXXConstructorDecl *BaseCtor, 12729 ConstructorUsingShadowDecl *Shadow) { 12730 CXXRecordDecl *Derived = Shadow->getParent(); 12731 SourceLocation UsingLoc = Shadow->getLocation(); 12732 12733 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 12734 // For now we use the name of the base class constructor as a member of the 12735 // derived class to indicate a (fake) inherited constructor name. 12736 DeclarationName Name = BaseCtor->getDeclName(); 12737 12738 // Check to see if we already have a fake constructor for this inherited 12739 // constructor call. 12740 for (NamedDecl *Ctor : Derived->lookup(Name)) 12741 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 12742 ->getInheritedConstructor() 12743 .getConstructor(), 12744 BaseCtor)) 12745 return cast<CXXConstructorDecl>(Ctor); 12746 12747 DeclarationNameInfo NameInfo(Name, UsingLoc); 12748 TypeSourceInfo *TInfo = 12749 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 12750 FunctionProtoTypeLoc ProtoLoc = 12751 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 12752 12753 // Check the inherited constructor is valid and find the list of base classes 12754 // from which it was inherited. 12755 InheritedConstructorInfo ICI(*this, Loc, Shadow); 12756 12757 bool Constexpr = 12758 BaseCtor->isConstexpr() && 12759 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 12760 false, BaseCtor, &ICI); 12761 12762 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 12763 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 12764 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 12765 /*isImplicitlyDeclared=*/true, 12766 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 12767 InheritedConstructor(Shadow, BaseCtor), 12768 BaseCtor->getTrailingRequiresClause()); 12769 if (Shadow->isInvalidDecl()) 12770 DerivedCtor->setInvalidDecl(); 12771 12772 // Build an unevaluated exception specification for this fake constructor. 12773 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 12774 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12775 EPI.ExceptionSpec.Type = EST_Unevaluated; 12776 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 12777 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 12778 FPT->getParamTypes(), EPI)); 12779 12780 // Build the parameter declarations. 12781 SmallVector<ParmVarDecl *, 16> ParamDecls; 12782 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 12783 TypeSourceInfo *TInfo = 12784 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 12785 ParmVarDecl *PD = ParmVarDecl::Create( 12786 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 12787 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 12788 PD->setScopeInfo(0, I); 12789 PD->setImplicit(); 12790 // Ensure attributes are propagated onto parameters (this matters for 12791 // format, pass_object_size, ...). 12792 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 12793 ParamDecls.push_back(PD); 12794 ProtoLoc.setParam(I, PD); 12795 } 12796 12797 // Set up the new constructor. 12798 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 12799 DerivedCtor->setAccess(BaseCtor->getAccess()); 12800 DerivedCtor->setParams(ParamDecls); 12801 Derived->addDecl(DerivedCtor); 12802 12803 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 12804 SetDeclDeleted(DerivedCtor, UsingLoc); 12805 12806 return DerivedCtor; 12807 } 12808 12809 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 12810 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 12811 Ctor->getInheritedConstructor().getShadowDecl()); 12812 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 12813 /*Diagnose*/true); 12814 } 12815 12816 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 12817 CXXConstructorDecl *Constructor) { 12818 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12819 assert(Constructor->getInheritedConstructor() && 12820 !Constructor->doesThisDeclarationHaveABody() && 12821 !Constructor->isDeleted()); 12822 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12823 return; 12824 12825 // Initializations are performed "as if by a defaulted default constructor", 12826 // so enter the appropriate scope. 12827 SynthesizedFunctionScope Scope(*this, Constructor); 12828 12829 // The exception specification is needed because we are defining the 12830 // function. 12831 ResolveExceptionSpec(CurrentLocation, 12832 Constructor->getType()->castAs<FunctionProtoType>()); 12833 MarkVTableUsed(CurrentLocation, ClassDecl); 12834 12835 // Add a context note for diagnostics produced after this point. 12836 Scope.addContextNote(CurrentLocation); 12837 12838 ConstructorUsingShadowDecl *Shadow = 12839 Constructor->getInheritedConstructor().getShadowDecl(); 12840 CXXConstructorDecl *InheritedCtor = 12841 Constructor->getInheritedConstructor().getConstructor(); 12842 12843 // [class.inhctor.init]p1: 12844 // initialization proceeds as if a defaulted default constructor is used to 12845 // initialize the D object and each base class subobject from which the 12846 // constructor was inherited 12847 12848 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 12849 CXXRecordDecl *RD = Shadow->getParent(); 12850 SourceLocation InitLoc = Shadow->getLocation(); 12851 12852 // Build explicit initializers for all base classes from which the 12853 // constructor was inherited. 12854 SmallVector<CXXCtorInitializer*, 8> Inits; 12855 for (bool VBase : {false, true}) { 12856 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 12857 if (B.isVirtual() != VBase) 12858 continue; 12859 12860 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 12861 if (!BaseRD) 12862 continue; 12863 12864 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 12865 if (!BaseCtor.first) 12866 continue; 12867 12868 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 12869 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 12870 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 12871 12872 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 12873 Inits.push_back(new (Context) CXXCtorInitializer( 12874 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 12875 SourceLocation())); 12876 } 12877 } 12878 12879 // We now proceed as if for a defaulted default constructor, with the relevant 12880 // initializers replaced. 12881 12882 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 12883 Constructor->setInvalidDecl(); 12884 return; 12885 } 12886 12887 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 12888 Constructor->markUsed(Context); 12889 12890 if (ASTMutationListener *L = getASTMutationListener()) { 12891 L->CompletedImplicitDefinition(Constructor); 12892 } 12893 12894 DiagnoseUninitializedFields(*this, Constructor); 12895 } 12896 12897 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 12898 // C++ [class.dtor]p2: 12899 // If a class has no user-declared destructor, a destructor is 12900 // declared implicitly. An implicitly-declared destructor is an 12901 // inline public member of its class. 12902 assert(ClassDecl->needsImplicitDestructor()); 12903 12904 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 12905 if (DSM.isAlreadyBeingDeclared()) 12906 return nullptr; 12907 12908 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12909 CXXDestructor, 12910 false); 12911 12912 // Create the actual destructor declaration. 12913 CanQualType ClassType 12914 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12915 SourceLocation ClassLoc = ClassDecl->getLocation(); 12916 DeclarationName Name 12917 = Context.DeclarationNames.getCXXDestructorName(ClassType); 12918 DeclarationNameInfo NameInfo(Name, ClassLoc); 12919 CXXDestructorDecl *Destructor = 12920 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 12921 QualType(), nullptr, /*isInline=*/true, 12922 /*isImplicitlyDeclared=*/true, 12923 Constexpr ? CSK_constexpr : CSK_unspecified); 12924 Destructor->setAccess(AS_public); 12925 Destructor->setDefaulted(); 12926 12927 if (getLangOpts().CUDA) { 12928 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 12929 Destructor, 12930 /* ConstRHS */ false, 12931 /* Diagnose */ false); 12932 } 12933 12934 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 12935 12936 // We don't need to use SpecialMemberIsTrivial here; triviality for 12937 // destructors is easy to compute. 12938 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 12939 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 12940 ClassDecl->hasTrivialDestructorForCall()); 12941 12942 // Note that we have declared this destructor. 12943 ++getASTContext().NumImplicitDestructorsDeclared; 12944 12945 Scope *S = getScopeForContext(ClassDecl); 12946 CheckImplicitSpecialMemberDeclaration(S, Destructor); 12947 12948 // We can't check whether an implicit destructor is deleted before we complete 12949 // the definition of the class, because its validity depends on the alignment 12950 // of the class. We'll check this from ActOnFields once the class is complete. 12951 if (ClassDecl->isCompleteDefinition() && 12952 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 12953 SetDeclDeleted(Destructor, ClassLoc); 12954 12955 // Introduce this destructor into its scope. 12956 if (S) 12957 PushOnScopeChains(Destructor, S, false); 12958 ClassDecl->addDecl(Destructor); 12959 12960 return Destructor; 12961 } 12962 12963 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 12964 CXXDestructorDecl *Destructor) { 12965 assert((Destructor->isDefaulted() && 12966 !Destructor->doesThisDeclarationHaveABody() && 12967 !Destructor->isDeleted()) && 12968 "DefineImplicitDestructor - call it for implicit default dtor"); 12969 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 12970 return; 12971 12972 CXXRecordDecl *ClassDecl = Destructor->getParent(); 12973 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 12974 12975 SynthesizedFunctionScope Scope(*this, Destructor); 12976 12977 // The exception specification is needed because we are defining the 12978 // function. 12979 ResolveExceptionSpec(CurrentLocation, 12980 Destructor->getType()->castAs<FunctionProtoType>()); 12981 MarkVTableUsed(CurrentLocation, ClassDecl); 12982 12983 // Add a context note for diagnostics produced after this point. 12984 Scope.addContextNote(CurrentLocation); 12985 12986 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12987 Destructor->getParent()); 12988 12989 if (CheckDestructor(Destructor)) { 12990 Destructor->setInvalidDecl(); 12991 return; 12992 } 12993 12994 SourceLocation Loc = Destructor->getEndLoc().isValid() 12995 ? Destructor->getEndLoc() 12996 : Destructor->getLocation(); 12997 Destructor->setBody(new (Context) CompoundStmt(Loc)); 12998 Destructor->markUsed(Context); 12999 13000 if (ASTMutationListener *L = getASTMutationListener()) { 13001 L->CompletedImplicitDefinition(Destructor); 13002 } 13003 } 13004 13005 /// Perform any semantic analysis which needs to be delayed until all 13006 /// pending class member declarations have been parsed. 13007 void Sema::ActOnFinishCXXMemberDecls() { 13008 // If the context is an invalid C++ class, just suppress these checks. 13009 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13010 if (Record->isInvalidDecl()) { 13011 DelayedOverridingExceptionSpecChecks.clear(); 13012 DelayedEquivalentExceptionSpecChecks.clear(); 13013 return; 13014 } 13015 checkForMultipleExportedDefaultConstructors(*this, Record); 13016 } 13017 } 13018 13019 void Sema::ActOnFinishCXXNonNestedClass() { 13020 referenceDLLExportedClassMethods(); 13021 13022 if (!DelayedDllExportMemberFunctions.empty()) { 13023 SmallVector<CXXMethodDecl*, 4> WorkList; 13024 std::swap(DelayedDllExportMemberFunctions, WorkList); 13025 for (CXXMethodDecl *M : WorkList) { 13026 DefineImplicitSpecialMember(*this, M, M->getLocation()); 13027 13028 // Pass the method to the consumer to get emitted. This is not necessary 13029 // for explicit instantiation definitions, as they will get emitted 13030 // anyway. 13031 if (M->getParent()->getTemplateSpecializationKind() != 13032 TSK_ExplicitInstantiationDefinition) 13033 ActOnFinishInlineFunctionDef(M); 13034 } 13035 } 13036 } 13037 13038 void Sema::referenceDLLExportedClassMethods() { 13039 if (!DelayedDllExportClasses.empty()) { 13040 // Calling ReferenceDllExportedMembers might cause the current function to 13041 // be called again, so use a local copy of DelayedDllExportClasses. 13042 SmallVector<CXXRecordDecl *, 4> WorkList; 13043 std::swap(DelayedDllExportClasses, WorkList); 13044 for (CXXRecordDecl *Class : WorkList) 13045 ReferenceDllExportedMembers(*this, Class); 13046 } 13047 } 13048 13049 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13050 assert(getLangOpts().CPlusPlus11 && 13051 "adjusting dtor exception specs was introduced in c++11"); 13052 13053 if (Destructor->isDependentContext()) 13054 return; 13055 13056 // C++11 [class.dtor]p3: 13057 // A declaration of a destructor that does not have an exception- 13058 // specification is implicitly considered to have the same exception- 13059 // specification as an implicit declaration. 13060 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13061 if (DtorType->hasExceptionSpec()) 13062 return; 13063 13064 // Replace the destructor's type, building off the existing one. Fortunately, 13065 // the only thing of interest in the destructor type is its extended info. 13066 // The return and arguments are fixed. 13067 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13068 EPI.ExceptionSpec.Type = EST_Unevaluated; 13069 EPI.ExceptionSpec.SourceDecl = Destructor; 13070 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13071 13072 // FIXME: If the destructor has a body that could throw, and the newly created 13073 // spec doesn't allow exceptions, we should emit a warning, because this 13074 // change in behavior can break conforming C++03 programs at runtime. 13075 // However, we don't have a body or an exception specification yet, so it 13076 // needs to be done somewhere else. 13077 } 13078 13079 namespace { 13080 /// An abstract base class for all helper classes used in building the 13081 // copy/move operators. These classes serve as factory functions and help us 13082 // avoid using the same Expr* in the AST twice. 13083 class ExprBuilder { 13084 ExprBuilder(const ExprBuilder&) = delete; 13085 ExprBuilder &operator=(const ExprBuilder&) = delete; 13086 13087 protected: 13088 static Expr *assertNotNull(Expr *E) { 13089 assert(E && "Expression construction must not fail."); 13090 return E; 13091 } 13092 13093 public: 13094 ExprBuilder() {} 13095 virtual ~ExprBuilder() {} 13096 13097 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13098 }; 13099 13100 class RefBuilder: public ExprBuilder { 13101 VarDecl *Var; 13102 QualType VarType; 13103 13104 public: 13105 Expr *build(Sema &S, SourceLocation Loc) const override { 13106 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13107 } 13108 13109 RefBuilder(VarDecl *Var, QualType VarType) 13110 : Var(Var), VarType(VarType) {} 13111 }; 13112 13113 class ThisBuilder: public ExprBuilder { 13114 public: 13115 Expr *build(Sema &S, SourceLocation Loc) const override { 13116 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13117 } 13118 }; 13119 13120 class CastBuilder: public ExprBuilder { 13121 const ExprBuilder &Builder; 13122 QualType Type; 13123 ExprValueKind Kind; 13124 const CXXCastPath &Path; 13125 13126 public: 13127 Expr *build(Sema &S, SourceLocation Loc) const override { 13128 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13129 CK_UncheckedDerivedToBase, Kind, 13130 &Path).get()); 13131 } 13132 13133 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13134 const CXXCastPath &Path) 13135 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13136 }; 13137 13138 class DerefBuilder: public ExprBuilder { 13139 const ExprBuilder &Builder; 13140 13141 public: 13142 Expr *build(Sema &S, SourceLocation Loc) const override { 13143 return assertNotNull( 13144 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13145 } 13146 13147 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13148 }; 13149 13150 class MemberBuilder: public ExprBuilder { 13151 const ExprBuilder &Builder; 13152 QualType Type; 13153 CXXScopeSpec SS; 13154 bool IsArrow; 13155 LookupResult &MemberLookup; 13156 13157 public: 13158 Expr *build(Sema &S, SourceLocation Loc) const override { 13159 return assertNotNull(S.BuildMemberReferenceExpr( 13160 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13161 nullptr, MemberLookup, nullptr, nullptr).get()); 13162 } 13163 13164 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13165 LookupResult &MemberLookup) 13166 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13167 MemberLookup(MemberLookup) {} 13168 }; 13169 13170 class MoveCastBuilder: public ExprBuilder { 13171 const ExprBuilder &Builder; 13172 13173 public: 13174 Expr *build(Sema &S, SourceLocation Loc) const override { 13175 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13176 } 13177 13178 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13179 }; 13180 13181 class LvalueConvBuilder: public ExprBuilder { 13182 const ExprBuilder &Builder; 13183 13184 public: 13185 Expr *build(Sema &S, SourceLocation Loc) const override { 13186 return assertNotNull( 13187 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13188 } 13189 13190 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13191 }; 13192 13193 class SubscriptBuilder: public ExprBuilder { 13194 const ExprBuilder &Base; 13195 const ExprBuilder &Index; 13196 13197 public: 13198 Expr *build(Sema &S, SourceLocation Loc) const override { 13199 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13200 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13201 } 13202 13203 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13204 : Base(Base), Index(Index) {} 13205 }; 13206 13207 } // end anonymous namespace 13208 13209 /// When generating a defaulted copy or move assignment operator, if a field 13210 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13211 /// do so. This optimization only applies for arrays of scalars, and for arrays 13212 /// of class type where the selected copy/move-assignment operator is trivial. 13213 static StmtResult 13214 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13215 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13216 // Compute the size of the memory buffer to be copied. 13217 QualType SizeType = S.Context.getSizeType(); 13218 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13219 S.Context.getTypeSizeInChars(T).getQuantity()); 13220 13221 // Take the address of the field references for "from" and "to". We 13222 // directly construct UnaryOperators here because semantic analysis 13223 // does not permit us to take the address of an xvalue. 13224 Expr *From = FromB.build(S, Loc); 13225 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 13226 S.Context.getPointerType(From->getType()), 13227 VK_RValue, OK_Ordinary, Loc, false); 13228 Expr *To = ToB.build(S, Loc); 13229 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 13230 S.Context.getPointerType(To->getType()), 13231 VK_RValue, OK_Ordinary, Loc, false); 13232 13233 const Type *E = T->getBaseElementTypeUnsafe(); 13234 bool NeedsCollectableMemCpy = 13235 E->isRecordType() && 13236 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13237 13238 // Create a reference to the __builtin_objc_memmove_collectable function 13239 StringRef MemCpyName = NeedsCollectableMemCpy ? 13240 "__builtin_objc_memmove_collectable" : 13241 "__builtin_memcpy"; 13242 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13243 Sema::LookupOrdinaryName); 13244 S.LookupName(R, S.TUScope, true); 13245 13246 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13247 if (!MemCpy) 13248 // Something went horribly wrong earlier, and we will have complained 13249 // about it. 13250 return StmtError(); 13251 13252 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13253 VK_RValue, Loc, nullptr); 13254 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13255 13256 Expr *CallArgs[] = { 13257 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13258 }; 13259 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13260 Loc, CallArgs, Loc); 13261 13262 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13263 return Call.getAs<Stmt>(); 13264 } 13265 13266 /// Builds a statement that copies/moves the given entity from \p From to 13267 /// \c To. 13268 /// 13269 /// This routine is used to copy/move the members of a class with an 13270 /// implicitly-declared copy/move assignment operator. When the entities being 13271 /// copied are arrays, this routine builds for loops to copy them. 13272 /// 13273 /// \param S The Sema object used for type-checking. 13274 /// 13275 /// \param Loc The location where the implicit copy/move is being generated. 13276 /// 13277 /// \param T The type of the expressions being copied/moved. Both expressions 13278 /// must have this type. 13279 /// 13280 /// \param To The expression we are copying/moving to. 13281 /// 13282 /// \param From The expression we are copying/moving from. 13283 /// 13284 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13285 /// Otherwise, it's a non-static member subobject. 13286 /// 13287 /// \param Copying Whether we're copying or moving. 13288 /// 13289 /// \param Depth Internal parameter recording the depth of the recursion. 13290 /// 13291 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13292 /// if a memcpy should be used instead. 13293 static StmtResult 13294 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13295 const ExprBuilder &To, const ExprBuilder &From, 13296 bool CopyingBaseSubobject, bool Copying, 13297 unsigned Depth = 0) { 13298 // C++11 [class.copy]p28: 13299 // Each subobject is assigned in the manner appropriate to its type: 13300 // 13301 // - if the subobject is of class type, as if by a call to operator= with 13302 // the subobject as the object expression and the corresponding 13303 // subobject of x as a single function argument (as if by explicit 13304 // qualification; that is, ignoring any possible virtual overriding 13305 // functions in more derived classes); 13306 // 13307 // C++03 [class.copy]p13: 13308 // - if the subobject is of class type, the copy assignment operator for 13309 // the class is used (as if by explicit qualification; that is, 13310 // ignoring any possible virtual overriding functions in more derived 13311 // classes); 13312 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13313 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13314 13315 // Look for operator=. 13316 DeclarationName Name 13317 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13318 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13319 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13320 13321 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13322 // operator. 13323 if (!S.getLangOpts().CPlusPlus11) { 13324 LookupResult::Filter F = OpLookup.makeFilter(); 13325 while (F.hasNext()) { 13326 NamedDecl *D = F.next(); 13327 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13328 if (Method->isCopyAssignmentOperator() || 13329 (!Copying && Method->isMoveAssignmentOperator())) 13330 continue; 13331 13332 F.erase(); 13333 } 13334 F.done(); 13335 } 13336 13337 // Suppress the protected check (C++ [class.protected]) for each of the 13338 // assignment operators we found. This strange dance is required when 13339 // we're assigning via a base classes's copy-assignment operator. To 13340 // ensure that we're getting the right base class subobject (without 13341 // ambiguities), we need to cast "this" to that subobject type; to 13342 // ensure that we don't go through the virtual call mechanism, we need 13343 // to qualify the operator= name with the base class (see below). However, 13344 // this means that if the base class has a protected copy assignment 13345 // operator, the protected member access check will fail. So, we 13346 // rewrite "protected" access to "public" access in this case, since we 13347 // know by construction that we're calling from a derived class. 13348 if (CopyingBaseSubobject) { 13349 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13350 L != LEnd; ++L) { 13351 if (L.getAccess() == AS_protected) 13352 L.setAccess(AS_public); 13353 } 13354 } 13355 13356 // Create the nested-name-specifier that will be used to qualify the 13357 // reference to operator=; this is required to suppress the virtual 13358 // call mechanism. 13359 CXXScopeSpec SS; 13360 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13361 SS.MakeTrivial(S.Context, 13362 NestedNameSpecifier::Create(S.Context, nullptr, false, 13363 CanonicalT), 13364 Loc); 13365 13366 // Create the reference to operator=. 13367 ExprResult OpEqualRef 13368 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13369 SS, /*TemplateKWLoc=*/SourceLocation(), 13370 /*FirstQualifierInScope=*/nullptr, 13371 OpLookup, 13372 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13373 /*SuppressQualifierCheck=*/true); 13374 if (OpEqualRef.isInvalid()) 13375 return StmtError(); 13376 13377 // Build the call to the assignment operator. 13378 13379 Expr *FromInst = From.build(S, Loc); 13380 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13381 OpEqualRef.getAs<Expr>(), 13382 Loc, FromInst, Loc); 13383 if (Call.isInvalid()) 13384 return StmtError(); 13385 13386 // If we built a call to a trivial 'operator=' while copying an array, 13387 // bail out. We'll replace the whole shebang with a memcpy. 13388 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13389 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13390 return StmtResult((Stmt*)nullptr); 13391 13392 // Convert to an expression-statement, and clean up any produced 13393 // temporaries. 13394 return S.ActOnExprStmt(Call); 13395 } 13396 13397 // - if the subobject is of scalar type, the built-in assignment 13398 // operator is used. 13399 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13400 if (!ArrayTy) { 13401 ExprResult Assignment = S.CreateBuiltinBinOp( 13402 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13403 if (Assignment.isInvalid()) 13404 return StmtError(); 13405 return S.ActOnExprStmt(Assignment); 13406 } 13407 13408 // - if the subobject is an array, each element is assigned, in the 13409 // manner appropriate to the element type; 13410 13411 // Construct a loop over the array bounds, e.g., 13412 // 13413 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13414 // 13415 // that will copy each of the array elements. 13416 QualType SizeType = S.Context.getSizeType(); 13417 13418 // Create the iteration variable. 13419 IdentifierInfo *IterationVarName = nullptr; 13420 { 13421 SmallString<8> Str; 13422 llvm::raw_svector_ostream OS(Str); 13423 OS << "__i" << Depth; 13424 IterationVarName = &S.Context.Idents.get(OS.str()); 13425 } 13426 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13427 IterationVarName, SizeType, 13428 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13429 SC_None); 13430 13431 // Initialize the iteration variable to zero. 13432 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13433 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13434 13435 // Creates a reference to the iteration variable. 13436 RefBuilder IterationVarRef(IterationVar, SizeType); 13437 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13438 13439 // Create the DeclStmt that holds the iteration variable. 13440 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13441 13442 // Subscript the "from" and "to" expressions with the iteration variable. 13443 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13444 MoveCastBuilder FromIndexMove(FromIndexCopy); 13445 const ExprBuilder *FromIndex; 13446 if (Copying) 13447 FromIndex = &FromIndexCopy; 13448 else 13449 FromIndex = &FromIndexMove; 13450 13451 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13452 13453 // Build the copy/move for an individual element of the array. 13454 StmtResult Copy = 13455 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13456 ToIndex, *FromIndex, CopyingBaseSubobject, 13457 Copying, Depth + 1); 13458 // Bail out if copying fails or if we determined that we should use memcpy. 13459 if (Copy.isInvalid() || !Copy.get()) 13460 return Copy; 13461 13462 // Create the comparison against the array bound. 13463 llvm::APInt Upper 13464 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13465 Expr *Comparison 13466 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 13467 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 13468 BO_NE, S.Context.BoolTy, 13469 VK_RValue, OK_Ordinary, Loc, FPOptions()); 13470 13471 // Create the pre-increment of the iteration variable. We can determine 13472 // whether the increment will overflow based on the value of the array 13473 // bound. 13474 Expr *Increment = new (S.Context) 13475 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 13476 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 13477 13478 // Construct the loop that copies all elements of this array. 13479 return S.ActOnForStmt( 13480 Loc, Loc, InitStmt, 13481 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13482 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13483 } 13484 13485 static StmtResult 13486 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13487 const ExprBuilder &To, const ExprBuilder &From, 13488 bool CopyingBaseSubobject, bool Copying) { 13489 // Maybe we should use a memcpy? 13490 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13491 T.isTriviallyCopyableType(S.Context)) 13492 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13493 13494 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13495 CopyingBaseSubobject, 13496 Copying, 0)); 13497 13498 // If we ended up picking a trivial assignment operator for an array of a 13499 // non-trivially-copyable class type, just emit a memcpy. 13500 if (!Result.isInvalid() && !Result.get()) 13501 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13502 13503 return Result; 13504 } 13505 13506 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13507 // Note: The following rules are largely analoguous to the copy 13508 // constructor rules. Note that virtual bases are not taken into account 13509 // for determining the argument type of the operator. Note also that 13510 // operators taking an object instead of a reference are allowed. 13511 assert(ClassDecl->needsImplicitCopyAssignment()); 13512 13513 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13514 if (DSM.isAlreadyBeingDeclared()) 13515 return nullptr; 13516 13517 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13518 LangAS AS = getDefaultCXXMethodAddrSpace(); 13519 if (AS != LangAS::Default) 13520 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13521 QualType RetType = Context.getLValueReferenceType(ArgType); 13522 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13523 if (Const) 13524 ArgType = ArgType.withConst(); 13525 13526 ArgType = Context.getLValueReferenceType(ArgType); 13527 13528 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13529 CXXCopyAssignment, 13530 Const); 13531 13532 // An implicitly-declared copy assignment operator is an inline public 13533 // member of its class. 13534 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13535 SourceLocation ClassLoc = ClassDecl->getLocation(); 13536 DeclarationNameInfo NameInfo(Name, ClassLoc); 13537 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13538 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13539 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13540 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13541 SourceLocation()); 13542 CopyAssignment->setAccess(AS_public); 13543 CopyAssignment->setDefaulted(); 13544 CopyAssignment->setImplicit(); 13545 13546 if (getLangOpts().CUDA) { 13547 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13548 CopyAssignment, 13549 /* ConstRHS */ Const, 13550 /* Diagnose */ false); 13551 } 13552 13553 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13554 13555 // Add the parameter to the operator. 13556 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13557 ClassLoc, ClassLoc, 13558 /*Id=*/nullptr, ArgType, 13559 /*TInfo=*/nullptr, SC_None, 13560 nullptr); 13561 CopyAssignment->setParams(FromParam); 13562 13563 CopyAssignment->setTrivial( 13564 ClassDecl->needsOverloadResolutionForCopyAssignment() 13565 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13566 : ClassDecl->hasTrivialCopyAssignment()); 13567 13568 // Note that we have added this copy-assignment operator. 13569 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13570 13571 Scope *S = getScopeForContext(ClassDecl); 13572 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13573 13574 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 13575 SetDeclDeleted(CopyAssignment, ClassLoc); 13576 13577 if (S) 13578 PushOnScopeChains(CopyAssignment, S, false); 13579 ClassDecl->addDecl(CopyAssignment); 13580 13581 return CopyAssignment; 13582 } 13583 13584 /// Diagnose an implicit copy operation for a class which is odr-used, but 13585 /// which is deprecated because the class has a user-declared copy constructor, 13586 /// copy assignment operator, or destructor. 13587 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13588 assert(CopyOp->isImplicit()); 13589 13590 CXXRecordDecl *RD = CopyOp->getParent(); 13591 CXXMethodDecl *UserDeclaredOperation = nullptr; 13592 13593 // In Microsoft mode, assignment operations don't affect constructors and 13594 // vice versa. 13595 if (RD->hasUserDeclaredDestructor()) { 13596 UserDeclaredOperation = RD->getDestructor(); 13597 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13598 RD->hasUserDeclaredCopyConstructor() && 13599 !S.getLangOpts().MSVCCompat) { 13600 // Find any user-declared copy constructor. 13601 for (auto *I : RD->ctors()) { 13602 if (I->isCopyConstructor()) { 13603 UserDeclaredOperation = I; 13604 break; 13605 } 13606 } 13607 assert(UserDeclaredOperation); 13608 } else if (isa<CXXConstructorDecl>(CopyOp) && 13609 RD->hasUserDeclaredCopyAssignment() && 13610 !S.getLangOpts().MSVCCompat) { 13611 // Find any user-declared move assignment operator. 13612 for (auto *I : RD->methods()) { 13613 if (I->isCopyAssignmentOperator()) { 13614 UserDeclaredOperation = I; 13615 break; 13616 } 13617 } 13618 assert(UserDeclaredOperation); 13619 } 13620 13621 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13622 S.Diag(UserDeclaredOperation->getLocation(), 13623 isa<CXXDestructorDecl>(UserDeclaredOperation) 13624 ? diag::warn_deprecated_copy_dtor_operation 13625 : diag::warn_deprecated_copy_operation) 13626 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 13627 } 13628 } 13629 13630 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 13631 CXXMethodDecl *CopyAssignOperator) { 13632 assert((CopyAssignOperator->isDefaulted() && 13633 CopyAssignOperator->isOverloadedOperator() && 13634 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 13635 !CopyAssignOperator->doesThisDeclarationHaveABody() && 13636 !CopyAssignOperator->isDeleted()) && 13637 "DefineImplicitCopyAssignment called for wrong function"); 13638 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 13639 return; 13640 13641 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 13642 if (ClassDecl->isInvalidDecl()) { 13643 CopyAssignOperator->setInvalidDecl(); 13644 return; 13645 } 13646 13647 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 13648 13649 // The exception specification is needed because we are defining the 13650 // function. 13651 ResolveExceptionSpec(CurrentLocation, 13652 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 13653 13654 // Add a context note for diagnostics produced after this point. 13655 Scope.addContextNote(CurrentLocation); 13656 13657 // C++11 [class.copy]p18: 13658 // The [definition of an implicitly declared copy assignment operator] is 13659 // deprecated if the class has a user-declared copy constructor or a 13660 // user-declared destructor. 13661 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 13662 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 13663 13664 // C++0x [class.copy]p30: 13665 // The implicitly-defined or explicitly-defaulted copy assignment operator 13666 // for a non-union class X performs memberwise copy assignment of its 13667 // subobjects. The direct base classes of X are assigned first, in the 13668 // order of their declaration in the base-specifier-list, and then the 13669 // immediate non-static data members of X are assigned, in the order in 13670 // which they were declared in the class definition. 13671 13672 // The statements that form the synthesized function body. 13673 SmallVector<Stmt*, 8> Statements; 13674 13675 // The parameter for the "other" object, which we are copying from. 13676 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 13677 Qualifiers OtherQuals = Other->getType().getQualifiers(); 13678 QualType OtherRefType = Other->getType(); 13679 if (const LValueReferenceType *OtherRef 13680 = OtherRefType->getAs<LValueReferenceType>()) { 13681 OtherRefType = OtherRef->getPointeeType(); 13682 OtherQuals = OtherRefType.getQualifiers(); 13683 } 13684 13685 // Our location for everything implicitly-generated. 13686 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 13687 ? CopyAssignOperator->getEndLoc() 13688 : CopyAssignOperator->getLocation(); 13689 13690 // Builds a DeclRefExpr for the "other" object. 13691 RefBuilder OtherRef(Other, OtherRefType); 13692 13693 // Builds the "this" pointer. 13694 ThisBuilder This; 13695 13696 // Assign base classes. 13697 bool Invalid = false; 13698 for (auto &Base : ClassDecl->bases()) { 13699 // Form the assignment: 13700 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 13701 QualType BaseType = Base.getType().getUnqualifiedType(); 13702 if (!BaseType->isRecordType()) { 13703 Invalid = true; 13704 continue; 13705 } 13706 13707 CXXCastPath BasePath; 13708 BasePath.push_back(&Base); 13709 13710 // Construct the "from" expression, which is an implicit cast to the 13711 // appropriately-qualified base type. 13712 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 13713 VK_LValue, BasePath); 13714 13715 // Dereference "this". 13716 DerefBuilder DerefThis(This); 13717 CastBuilder To(DerefThis, 13718 Context.getQualifiedType( 13719 BaseType, CopyAssignOperator->getMethodQualifiers()), 13720 VK_LValue, BasePath); 13721 13722 // Build the copy. 13723 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 13724 To, From, 13725 /*CopyingBaseSubobject=*/true, 13726 /*Copying=*/true); 13727 if (Copy.isInvalid()) { 13728 CopyAssignOperator->setInvalidDecl(); 13729 return; 13730 } 13731 13732 // Success! Record the copy. 13733 Statements.push_back(Copy.getAs<Expr>()); 13734 } 13735 13736 // Assign non-static members. 13737 for (auto *Field : ClassDecl->fields()) { 13738 // FIXME: We should form some kind of AST representation for the implied 13739 // memcpy in a union copy operation. 13740 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 13741 continue; 13742 13743 if (Field->isInvalidDecl()) { 13744 Invalid = true; 13745 continue; 13746 } 13747 13748 // Check for members of reference type; we can't copy those. 13749 if (Field->getType()->isReferenceType()) { 13750 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 13751 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 13752 Diag(Field->getLocation(), diag::note_declared_at); 13753 Invalid = true; 13754 continue; 13755 } 13756 13757 // Check for members of const-qualified, non-class type. 13758 QualType BaseType = Context.getBaseElementType(Field->getType()); 13759 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 13760 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 13761 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 13762 Diag(Field->getLocation(), diag::note_declared_at); 13763 Invalid = true; 13764 continue; 13765 } 13766 13767 // Suppress assigning zero-width bitfields. 13768 if (Field->isZeroLengthBitField(Context)) 13769 continue; 13770 13771 QualType FieldType = Field->getType().getNonReferenceType(); 13772 if (FieldType->isIncompleteArrayType()) { 13773 assert(ClassDecl->hasFlexibleArrayMember() && 13774 "Incomplete array type is not valid"); 13775 continue; 13776 } 13777 13778 // Build references to the field in the object we're copying from and to. 13779 CXXScopeSpec SS; // Intentionally empty 13780 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 13781 LookupMemberName); 13782 MemberLookup.addDecl(Field); 13783 MemberLookup.resolveKind(); 13784 13785 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 13786 13787 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 13788 13789 // Build the copy of this field. 13790 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 13791 To, From, 13792 /*CopyingBaseSubobject=*/false, 13793 /*Copying=*/true); 13794 if (Copy.isInvalid()) { 13795 CopyAssignOperator->setInvalidDecl(); 13796 return; 13797 } 13798 13799 // Success! Record the copy. 13800 Statements.push_back(Copy.getAs<Stmt>()); 13801 } 13802 13803 if (!Invalid) { 13804 // Add a "return *this;" 13805 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 13806 13807 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 13808 if (Return.isInvalid()) 13809 Invalid = true; 13810 else 13811 Statements.push_back(Return.getAs<Stmt>()); 13812 } 13813 13814 if (Invalid) { 13815 CopyAssignOperator->setInvalidDecl(); 13816 return; 13817 } 13818 13819 StmtResult Body; 13820 { 13821 CompoundScopeRAII CompoundScope(*this); 13822 Body = ActOnCompoundStmt(Loc, Loc, Statements, 13823 /*isStmtExpr=*/false); 13824 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 13825 } 13826 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 13827 CopyAssignOperator->markUsed(Context); 13828 13829 if (ASTMutationListener *L = getASTMutationListener()) { 13830 L->CompletedImplicitDefinition(CopyAssignOperator); 13831 } 13832 } 13833 13834 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 13835 assert(ClassDecl->needsImplicitMoveAssignment()); 13836 13837 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 13838 if (DSM.isAlreadyBeingDeclared()) 13839 return nullptr; 13840 13841 // Note: The following rules are largely analoguous to the move 13842 // constructor rules. 13843 13844 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13845 LangAS AS = getDefaultCXXMethodAddrSpace(); 13846 if (AS != LangAS::Default) 13847 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13848 QualType RetType = Context.getLValueReferenceType(ArgType); 13849 ArgType = Context.getRValueReferenceType(ArgType); 13850 13851 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13852 CXXMoveAssignment, 13853 false); 13854 13855 // An implicitly-declared move assignment operator is an inline public 13856 // member of its class. 13857 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13858 SourceLocation ClassLoc = ClassDecl->getLocation(); 13859 DeclarationNameInfo NameInfo(Name, ClassLoc); 13860 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 13861 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13862 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13863 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13864 SourceLocation()); 13865 MoveAssignment->setAccess(AS_public); 13866 MoveAssignment->setDefaulted(); 13867 MoveAssignment->setImplicit(); 13868 13869 if (getLangOpts().CUDA) { 13870 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 13871 MoveAssignment, 13872 /* ConstRHS */ false, 13873 /* Diagnose */ false); 13874 } 13875 13876 // Build an exception specification pointing back at this member. 13877 FunctionProtoType::ExtProtoInfo EPI = 13878 getImplicitMethodEPI(*this, MoveAssignment); 13879 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 13880 13881 // Add the parameter to the operator. 13882 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 13883 ClassLoc, ClassLoc, 13884 /*Id=*/nullptr, ArgType, 13885 /*TInfo=*/nullptr, SC_None, 13886 nullptr); 13887 MoveAssignment->setParams(FromParam); 13888 13889 MoveAssignment->setTrivial( 13890 ClassDecl->needsOverloadResolutionForMoveAssignment() 13891 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 13892 : ClassDecl->hasTrivialMoveAssignment()); 13893 13894 // Note that we have added this copy-assignment operator. 13895 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 13896 13897 Scope *S = getScopeForContext(ClassDecl); 13898 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 13899 13900 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 13901 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 13902 SetDeclDeleted(MoveAssignment, ClassLoc); 13903 } 13904 13905 if (S) 13906 PushOnScopeChains(MoveAssignment, S, false); 13907 ClassDecl->addDecl(MoveAssignment); 13908 13909 return MoveAssignment; 13910 } 13911 13912 /// Check if we're implicitly defining a move assignment operator for a class 13913 /// with virtual bases. Such a move assignment might move-assign the virtual 13914 /// base multiple times. 13915 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 13916 SourceLocation CurrentLocation) { 13917 assert(!Class->isDependentContext() && "should not define dependent move"); 13918 13919 // Only a virtual base could get implicitly move-assigned multiple times. 13920 // Only a non-trivial move assignment can observe this. We only want to 13921 // diagnose if we implicitly define an assignment operator that assigns 13922 // two base classes, both of which move-assign the same virtual base. 13923 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 13924 Class->getNumBases() < 2) 13925 return; 13926 13927 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 13928 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 13929 VBaseMap VBases; 13930 13931 for (auto &BI : Class->bases()) { 13932 Worklist.push_back(&BI); 13933 while (!Worklist.empty()) { 13934 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 13935 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 13936 13937 // If the base has no non-trivial move assignment operators, 13938 // we don't care about moves from it. 13939 if (!Base->hasNonTrivialMoveAssignment()) 13940 continue; 13941 13942 // If there's nothing virtual here, skip it. 13943 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 13944 continue; 13945 13946 // If we're not actually going to call a move assignment for this base, 13947 // or the selected move assignment is trivial, skip it. 13948 Sema::SpecialMemberOverloadResult SMOR = 13949 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 13950 /*ConstArg*/false, /*VolatileArg*/false, 13951 /*RValueThis*/true, /*ConstThis*/false, 13952 /*VolatileThis*/false); 13953 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 13954 !SMOR.getMethod()->isMoveAssignmentOperator()) 13955 continue; 13956 13957 if (BaseSpec->isVirtual()) { 13958 // We're going to move-assign this virtual base, and its move 13959 // assignment operator is not trivial. If this can happen for 13960 // multiple distinct direct bases of Class, diagnose it. (If it 13961 // only happens in one base, we'll diagnose it when synthesizing 13962 // that base class's move assignment operator.) 13963 CXXBaseSpecifier *&Existing = 13964 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 13965 .first->second; 13966 if (Existing && Existing != &BI) { 13967 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 13968 << Class << Base; 13969 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 13970 << (Base->getCanonicalDecl() == 13971 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 13972 << Base << Existing->getType() << Existing->getSourceRange(); 13973 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 13974 << (Base->getCanonicalDecl() == 13975 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 13976 << Base << BI.getType() << BaseSpec->getSourceRange(); 13977 13978 // Only diagnose each vbase once. 13979 Existing = nullptr; 13980 } 13981 } else { 13982 // Only walk over bases that have defaulted move assignment operators. 13983 // We assume that any user-provided move assignment operator handles 13984 // the multiple-moves-of-vbase case itself somehow. 13985 if (!SMOR.getMethod()->isDefaulted()) 13986 continue; 13987 13988 // We're going to move the base classes of Base. Add them to the list. 13989 for (auto &BI : Base->bases()) 13990 Worklist.push_back(&BI); 13991 } 13992 } 13993 } 13994 } 13995 13996 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 13997 CXXMethodDecl *MoveAssignOperator) { 13998 assert((MoveAssignOperator->isDefaulted() && 13999 MoveAssignOperator->isOverloadedOperator() && 14000 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14001 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14002 !MoveAssignOperator->isDeleted()) && 14003 "DefineImplicitMoveAssignment called for wrong function"); 14004 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14005 return; 14006 14007 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14008 if (ClassDecl->isInvalidDecl()) { 14009 MoveAssignOperator->setInvalidDecl(); 14010 return; 14011 } 14012 14013 // C++0x [class.copy]p28: 14014 // The implicitly-defined or move assignment operator for a non-union class 14015 // X performs memberwise move assignment of its subobjects. The direct base 14016 // classes of X are assigned first, in the order of their declaration in the 14017 // base-specifier-list, and then the immediate non-static data members of X 14018 // are assigned, in the order in which they were declared in the class 14019 // definition. 14020 14021 // Issue a warning if our implicit move assignment operator will move 14022 // from a virtual base more than once. 14023 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14024 14025 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14026 14027 // The exception specification is needed because we are defining the 14028 // function. 14029 ResolveExceptionSpec(CurrentLocation, 14030 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14031 14032 // Add a context note for diagnostics produced after this point. 14033 Scope.addContextNote(CurrentLocation); 14034 14035 // The statements that form the synthesized function body. 14036 SmallVector<Stmt*, 8> Statements; 14037 14038 // The parameter for the "other" object, which we are move from. 14039 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14040 QualType OtherRefType = 14041 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14042 14043 // Our location for everything implicitly-generated. 14044 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14045 ? MoveAssignOperator->getEndLoc() 14046 : MoveAssignOperator->getLocation(); 14047 14048 // Builds a reference to the "other" object. 14049 RefBuilder OtherRef(Other, OtherRefType); 14050 // Cast to rvalue. 14051 MoveCastBuilder MoveOther(OtherRef); 14052 14053 // Builds the "this" pointer. 14054 ThisBuilder This; 14055 14056 // Assign base classes. 14057 bool Invalid = false; 14058 for (auto &Base : ClassDecl->bases()) { 14059 // C++11 [class.copy]p28: 14060 // It is unspecified whether subobjects representing virtual base classes 14061 // are assigned more than once by the implicitly-defined copy assignment 14062 // operator. 14063 // FIXME: Do not assign to a vbase that will be assigned by some other base 14064 // class. For a move-assignment, this can result in the vbase being moved 14065 // multiple times. 14066 14067 // Form the assignment: 14068 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14069 QualType BaseType = Base.getType().getUnqualifiedType(); 14070 if (!BaseType->isRecordType()) { 14071 Invalid = true; 14072 continue; 14073 } 14074 14075 CXXCastPath BasePath; 14076 BasePath.push_back(&Base); 14077 14078 // Construct the "from" expression, which is an implicit cast to the 14079 // appropriately-qualified base type. 14080 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14081 14082 // Dereference "this". 14083 DerefBuilder DerefThis(This); 14084 14085 // Implicitly cast "this" to the appropriately-qualified base type. 14086 CastBuilder To(DerefThis, 14087 Context.getQualifiedType( 14088 BaseType, MoveAssignOperator->getMethodQualifiers()), 14089 VK_LValue, BasePath); 14090 14091 // Build the move. 14092 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14093 To, From, 14094 /*CopyingBaseSubobject=*/true, 14095 /*Copying=*/false); 14096 if (Move.isInvalid()) { 14097 MoveAssignOperator->setInvalidDecl(); 14098 return; 14099 } 14100 14101 // Success! Record the move. 14102 Statements.push_back(Move.getAs<Expr>()); 14103 } 14104 14105 // Assign non-static members. 14106 for (auto *Field : ClassDecl->fields()) { 14107 // FIXME: We should form some kind of AST representation for the implied 14108 // memcpy in a union copy operation. 14109 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14110 continue; 14111 14112 if (Field->isInvalidDecl()) { 14113 Invalid = true; 14114 continue; 14115 } 14116 14117 // Check for members of reference type; we can't move those. 14118 if (Field->getType()->isReferenceType()) { 14119 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14120 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14121 Diag(Field->getLocation(), diag::note_declared_at); 14122 Invalid = true; 14123 continue; 14124 } 14125 14126 // Check for members of const-qualified, non-class type. 14127 QualType BaseType = Context.getBaseElementType(Field->getType()); 14128 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14129 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14130 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14131 Diag(Field->getLocation(), diag::note_declared_at); 14132 Invalid = true; 14133 continue; 14134 } 14135 14136 // Suppress assigning zero-width bitfields. 14137 if (Field->isZeroLengthBitField(Context)) 14138 continue; 14139 14140 QualType FieldType = Field->getType().getNonReferenceType(); 14141 if (FieldType->isIncompleteArrayType()) { 14142 assert(ClassDecl->hasFlexibleArrayMember() && 14143 "Incomplete array type is not valid"); 14144 continue; 14145 } 14146 14147 // Build references to the field in the object we're copying from and to. 14148 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14149 LookupMemberName); 14150 MemberLookup.addDecl(Field); 14151 MemberLookup.resolveKind(); 14152 MemberBuilder From(MoveOther, OtherRefType, 14153 /*IsArrow=*/false, MemberLookup); 14154 MemberBuilder To(This, getCurrentThisType(), 14155 /*IsArrow=*/true, MemberLookup); 14156 14157 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14158 "Member reference with rvalue base must be rvalue except for reference " 14159 "members, which aren't allowed for move assignment."); 14160 14161 // Build the move of this field. 14162 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14163 To, From, 14164 /*CopyingBaseSubobject=*/false, 14165 /*Copying=*/false); 14166 if (Move.isInvalid()) { 14167 MoveAssignOperator->setInvalidDecl(); 14168 return; 14169 } 14170 14171 // Success! Record the copy. 14172 Statements.push_back(Move.getAs<Stmt>()); 14173 } 14174 14175 if (!Invalid) { 14176 // Add a "return *this;" 14177 ExprResult ThisObj = 14178 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14179 14180 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14181 if (Return.isInvalid()) 14182 Invalid = true; 14183 else 14184 Statements.push_back(Return.getAs<Stmt>()); 14185 } 14186 14187 if (Invalid) { 14188 MoveAssignOperator->setInvalidDecl(); 14189 return; 14190 } 14191 14192 StmtResult Body; 14193 { 14194 CompoundScopeRAII CompoundScope(*this); 14195 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14196 /*isStmtExpr=*/false); 14197 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14198 } 14199 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14200 MoveAssignOperator->markUsed(Context); 14201 14202 if (ASTMutationListener *L = getASTMutationListener()) { 14203 L->CompletedImplicitDefinition(MoveAssignOperator); 14204 } 14205 } 14206 14207 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14208 CXXRecordDecl *ClassDecl) { 14209 // C++ [class.copy]p4: 14210 // If the class definition does not explicitly declare a copy 14211 // constructor, one is declared implicitly. 14212 assert(ClassDecl->needsImplicitCopyConstructor()); 14213 14214 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14215 if (DSM.isAlreadyBeingDeclared()) 14216 return nullptr; 14217 14218 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14219 QualType ArgType = ClassType; 14220 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14221 if (Const) 14222 ArgType = ArgType.withConst(); 14223 14224 LangAS AS = getDefaultCXXMethodAddrSpace(); 14225 if (AS != LangAS::Default) 14226 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14227 14228 ArgType = Context.getLValueReferenceType(ArgType); 14229 14230 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14231 CXXCopyConstructor, 14232 Const); 14233 14234 DeclarationName Name 14235 = Context.DeclarationNames.getCXXConstructorName( 14236 Context.getCanonicalType(ClassType)); 14237 SourceLocation ClassLoc = ClassDecl->getLocation(); 14238 DeclarationNameInfo NameInfo(Name, ClassLoc); 14239 14240 // An implicitly-declared copy constructor is an inline public 14241 // member of its class. 14242 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14243 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14244 ExplicitSpecifier(), 14245 /*isInline=*/true, 14246 /*isImplicitlyDeclared=*/true, 14247 Constexpr ? CSK_constexpr : CSK_unspecified); 14248 CopyConstructor->setAccess(AS_public); 14249 CopyConstructor->setDefaulted(); 14250 14251 if (getLangOpts().CUDA) { 14252 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14253 CopyConstructor, 14254 /* ConstRHS */ Const, 14255 /* Diagnose */ false); 14256 } 14257 14258 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14259 14260 // Add the parameter to the constructor. 14261 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14262 ClassLoc, ClassLoc, 14263 /*IdentifierInfo=*/nullptr, 14264 ArgType, /*TInfo=*/nullptr, 14265 SC_None, nullptr); 14266 CopyConstructor->setParams(FromParam); 14267 14268 CopyConstructor->setTrivial( 14269 ClassDecl->needsOverloadResolutionForCopyConstructor() 14270 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14271 : ClassDecl->hasTrivialCopyConstructor()); 14272 14273 CopyConstructor->setTrivialForCall( 14274 ClassDecl->hasAttr<TrivialABIAttr>() || 14275 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14276 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14277 TAH_ConsiderTrivialABI) 14278 : ClassDecl->hasTrivialCopyConstructorForCall())); 14279 14280 // Note that we have declared this constructor. 14281 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14282 14283 Scope *S = getScopeForContext(ClassDecl); 14284 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14285 14286 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14287 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14288 SetDeclDeleted(CopyConstructor, ClassLoc); 14289 } 14290 14291 if (S) 14292 PushOnScopeChains(CopyConstructor, S, false); 14293 ClassDecl->addDecl(CopyConstructor); 14294 14295 return CopyConstructor; 14296 } 14297 14298 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14299 CXXConstructorDecl *CopyConstructor) { 14300 assert((CopyConstructor->isDefaulted() && 14301 CopyConstructor->isCopyConstructor() && 14302 !CopyConstructor->doesThisDeclarationHaveABody() && 14303 !CopyConstructor->isDeleted()) && 14304 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14305 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14306 return; 14307 14308 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14309 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14310 14311 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14312 14313 // The exception specification is needed because we are defining the 14314 // function. 14315 ResolveExceptionSpec(CurrentLocation, 14316 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14317 MarkVTableUsed(CurrentLocation, ClassDecl); 14318 14319 // Add a context note for diagnostics produced after this point. 14320 Scope.addContextNote(CurrentLocation); 14321 14322 // C++11 [class.copy]p7: 14323 // The [definition of an implicitly declared copy constructor] is 14324 // deprecated if the class has a user-declared copy assignment operator 14325 // or a user-declared destructor. 14326 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14327 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14328 14329 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14330 CopyConstructor->setInvalidDecl(); 14331 } else { 14332 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14333 ? CopyConstructor->getEndLoc() 14334 : CopyConstructor->getLocation(); 14335 Sema::CompoundScopeRAII CompoundScope(*this); 14336 CopyConstructor->setBody( 14337 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14338 CopyConstructor->markUsed(Context); 14339 } 14340 14341 if (ASTMutationListener *L = getASTMutationListener()) { 14342 L->CompletedImplicitDefinition(CopyConstructor); 14343 } 14344 } 14345 14346 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14347 CXXRecordDecl *ClassDecl) { 14348 assert(ClassDecl->needsImplicitMoveConstructor()); 14349 14350 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14351 if (DSM.isAlreadyBeingDeclared()) 14352 return nullptr; 14353 14354 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14355 14356 QualType ArgType = ClassType; 14357 LangAS AS = getDefaultCXXMethodAddrSpace(); 14358 if (AS != LangAS::Default) 14359 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14360 ArgType = Context.getRValueReferenceType(ArgType); 14361 14362 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14363 CXXMoveConstructor, 14364 false); 14365 14366 DeclarationName Name 14367 = Context.DeclarationNames.getCXXConstructorName( 14368 Context.getCanonicalType(ClassType)); 14369 SourceLocation ClassLoc = ClassDecl->getLocation(); 14370 DeclarationNameInfo NameInfo(Name, ClassLoc); 14371 14372 // C++11 [class.copy]p11: 14373 // An implicitly-declared copy/move constructor is an inline public 14374 // member of its class. 14375 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14376 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14377 ExplicitSpecifier(), 14378 /*isInline=*/true, 14379 /*isImplicitlyDeclared=*/true, 14380 Constexpr ? CSK_constexpr : CSK_unspecified); 14381 MoveConstructor->setAccess(AS_public); 14382 MoveConstructor->setDefaulted(); 14383 14384 if (getLangOpts().CUDA) { 14385 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14386 MoveConstructor, 14387 /* ConstRHS */ false, 14388 /* Diagnose */ false); 14389 } 14390 14391 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14392 14393 // Add the parameter to the constructor. 14394 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14395 ClassLoc, ClassLoc, 14396 /*IdentifierInfo=*/nullptr, 14397 ArgType, /*TInfo=*/nullptr, 14398 SC_None, nullptr); 14399 MoveConstructor->setParams(FromParam); 14400 14401 MoveConstructor->setTrivial( 14402 ClassDecl->needsOverloadResolutionForMoveConstructor() 14403 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14404 : ClassDecl->hasTrivialMoveConstructor()); 14405 14406 MoveConstructor->setTrivialForCall( 14407 ClassDecl->hasAttr<TrivialABIAttr>() || 14408 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14409 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14410 TAH_ConsiderTrivialABI) 14411 : ClassDecl->hasTrivialMoveConstructorForCall())); 14412 14413 // Note that we have declared this constructor. 14414 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14415 14416 Scope *S = getScopeForContext(ClassDecl); 14417 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14418 14419 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14420 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14421 SetDeclDeleted(MoveConstructor, ClassLoc); 14422 } 14423 14424 if (S) 14425 PushOnScopeChains(MoveConstructor, S, false); 14426 ClassDecl->addDecl(MoveConstructor); 14427 14428 return MoveConstructor; 14429 } 14430 14431 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14432 CXXConstructorDecl *MoveConstructor) { 14433 assert((MoveConstructor->isDefaulted() && 14434 MoveConstructor->isMoveConstructor() && 14435 !MoveConstructor->doesThisDeclarationHaveABody() && 14436 !MoveConstructor->isDeleted()) && 14437 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14438 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14439 return; 14440 14441 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14442 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14443 14444 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14445 14446 // The exception specification is needed because we are defining the 14447 // function. 14448 ResolveExceptionSpec(CurrentLocation, 14449 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14450 MarkVTableUsed(CurrentLocation, ClassDecl); 14451 14452 // Add a context note for diagnostics produced after this point. 14453 Scope.addContextNote(CurrentLocation); 14454 14455 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14456 MoveConstructor->setInvalidDecl(); 14457 } else { 14458 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14459 ? MoveConstructor->getEndLoc() 14460 : MoveConstructor->getLocation(); 14461 Sema::CompoundScopeRAII CompoundScope(*this); 14462 MoveConstructor->setBody(ActOnCompoundStmt( 14463 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14464 MoveConstructor->markUsed(Context); 14465 } 14466 14467 if (ASTMutationListener *L = getASTMutationListener()) { 14468 L->CompletedImplicitDefinition(MoveConstructor); 14469 } 14470 } 14471 14472 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14473 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14474 } 14475 14476 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14477 SourceLocation CurrentLocation, 14478 CXXConversionDecl *Conv) { 14479 SynthesizedFunctionScope Scope(*this, Conv); 14480 assert(!Conv->getReturnType()->isUndeducedType()); 14481 14482 CXXRecordDecl *Lambda = Conv->getParent(); 14483 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14484 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 14485 14486 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14487 CallOp = InstantiateFunctionDeclaration( 14488 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14489 if (!CallOp) 14490 return; 14491 14492 Invoker = InstantiateFunctionDeclaration( 14493 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14494 if (!Invoker) 14495 return; 14496 } 14497 14498 if (CallOp->isInvalidDecl()) 14499 return; 14500 14501 // Mark the call operator referenced (and add to pending instantiations 14502 // if necessary). 14503 // For both the conversion and static-invoker template specializations 14504 // we construct their body's in this function, so no need to add them 14505 // to the PendingInstantiations. 14506 MarkFunctionReferenced(CurrentLocation, CallOp); 14507 14508 // Fill in the __invoke function with a dummy implementation. IR generation 14509 // will fill in the actual details. Update its type in case it contained 14510 // an 'auto'. 14511 Invoker->markUsed(Context); 14512 Invoker->setReferenced(); 14513 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14514 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14515 14516 // Construct the body of the conversion function { return __invoke; }. 14517 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14518 VK_LValue, Conv->getLocation()); 14519 assert(FunctionRef && "Can't refer to __invoke function?"); 14520 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14521 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14522 Conv->getLocation())); 14523 Conv->markUsed(Context); 14524 Conv->setReferenced(); 14525 14526 if (ASTMutationListener *L = getASTMutationListener()) { 14527 L->CompletedImplicitDefinition(Conv); 14528 L->CompletedImplicitDefinition(Invoker); 14529 } 14530 } 14531 14532 14533 14534 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14535 SourceLocation CurrentLocation, 14536 CXXConversionDecl *Conv) 14537 { 14538 assert(!Conv->getParent()->isGenericLambda()); 14539 14540 SynthesizedFunctionScope Scope(*this, Conv); 14541 14542 // Copy-initialize the lambda object as needed to capture it. 14543 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14544 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14545 14546 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14547 Conv->getLocation(), 14548 Conv, DerefThis); 14549 14550 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14551 // behavior. Note that only the general conversion function does this 14552 // (since it's unusable otherwise); in the case where we inline the 14553 // block literal, it has block literal lifetime semantics. 14554 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14555 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 14556 CK_CopyAndAutoreleaseBlockObject, 14557 BuildBlock.get(), nullptr, VK_RValue); 14558 14559 if (BuildBlock.isInvalid()) { 14560 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14561 Conv->setInvalidDecl(); 14562 return; 14563 } 14564 14565 // Create the return statement that returns the block from the conversion 14566 // function. 14567 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14568 if (Return.isInvalid()) { 14569 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14570 Conv->setInvalidDecl(); 14571 return; 14572 } 14573 14574 // Set the body of the conversion function. 14575 Stmt *ReturnS = Return.get(); 14576 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14577 Conv->getLocation())); 14578 Conv->markUsed(Context); 14579 14580 // We're done; notify the mutation listener, if any. 14581 if (ASTMutationListener *L = getASTMutationListener()) { 14582 L->CompletedImplicitDefinition(Conv); 14583 } 14584 } 14585 14586 /// Determine whether the given list arguments contains exactly one 14587 /// "real" (non-default) argument. 14588 static bool hasOneRealArgument(MultiExprArg Args) { 14589 switch (Args.size()) { 14590 case 0: 14591 return false; 14592 14593 default: 14594 if (!Args[1]->isDefaultArgument()) 14595 return false; 14596 14597 LLVM_FALLTHROUGH; 14598 case 1: 14599 return !Args[0]->isDefaultArgument(); 14600 } 14601 14602 return false; 14603 } 14604 14605 ExprResult 14606 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14607 NamedDecl *FoundDecl, 14608 CXXConstructorDecl *Constructor, 14609 MultiExprArg ExprArgs, 14610 bool HadMultipleCandidates, 14611 bool IsListInitialization, 14612 bool IsStdInitListInitialization, 14613 bool RequiresZeroInit, 14614 unsigned ConstructKind, 14615 SourceRange ParenRange) { 14616 bool Elidable = false; 14617 14618 // C++0x [class.copy]p34: 14619 // When certain criteria are met, an implementation is allowed to 14620 // omit the copy/move construction of a class object, even if the 14621 // copy/move constructor and/or destructor for the object have 14622 // side effects. [...] 14623 // - when a temporary class object that has not been bound to a 14624 // reference (12.2) would be copied/moved to a class object 14625 // with the same cv-unqualified type, the copy/move operation 14626 // can be omitted by constructing the temporary object 14627 // directly into the target of the omitted copy/move 14628 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 14629 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 14630 Expr *SubExpr = ExprArgs[0]; 14631 Elidable = SubExpr->isTemporaryObject( 14632 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 14633 } 14634 14635 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 14636 FoundDecl, Constructor, 14637 Elidable, ExprArgs, HadMultipleCandidates, 14638 IsListInitialization, 14639 IsStdInitListInitialization, RequiresZeroInit, 14640 ConstructKind, ParenRange); 14641 } 14642 14643 ExprResult 14644 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14645 NamedDecl *FoundDecl, 14646 CXXConstructorDecl *Constructor, 14647 bool Elidable, 14648 MultiExprArg ExprArgs, 14649 bool HadMultipleCandidates, 14650 bool IsListInitialization, 14651 bool IsStdInitListInitialization, 14652 bool RequiresZeroInit, 14653 unsigned ConstructKind, 14654 SourceRange ParenRange) { 14655 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 14656 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 14657 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 14658 return ExprError(); 14659 } 14660 14661 return BuildCXXConstructExpr( 14662 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 14663 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 14664 RequiresZeroInit, ConstructKind, ParenRange); 14665 } 14666 14667 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 14668 /// including handling of its default argument expressions. 14669 ExprResult 14670 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14671 CXXConstructorDecl *Constructor, 14672 bool Elidable, 14673 MultiExprArg ExprArgs, 14674 bool HadMultipleCandidates, 14675 bool IsListInitialization, 14676 bool IsStdInitListInitialization, 14677 bool RequiresZeroInit, 14678 unsigned ConstructKind, 14679 SourceRange ParenRange) { 14680 assert(declaresSameEntity( 14681 Constructor->getParent(), 14682 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 14683 "given constructor for wrong type"); 14684 MarkFunctionReferenced(ConstructLoc, Constructor); 14685 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 14686 return ExprError(); 14687 14688 return CXXConstructExpr::Create( 14689 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 14690 ExprArgs, HadMultipleCandidates, IsListInitialization, 14691 IsStdInitListInitialization, RequiresZeroInit, 14692 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 14693 ParenRange); 14694 } 14695 14696 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 14697 assert(Field->hasInClassInitializer()); 14698 14699 // If we already have the in-class initializer nothing needs to be done. 14700 if (Field->getInClassInitializer()) 14701 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 14702 14703 // If we might have already tried and failed to instantiate, don't try again. 14704 if (Field->isInvalidDecl()) 14705 return ExprError(); 14706 14707 // Maybe we haven't instantiated the in-class initializer. Go check the 14708 // pattern FieldDecl to see if it has one. 14709 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 14710 14711 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 14712 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 14713 DeclContext::lookup_result Lookup = 14714 ClassPattern->lookup(Field->getDeclName()); 14715 14716 // Lookup can return at most two results: the pattern for the field, or the 14717 // injected class name of the parent record. No other member can have the 14718 // same name as the field. 14719 // In modules mode, lookup can return multiple results (coming from 14720 // different modules). 14721 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 14722 "more than two lookup results for field name"); 14723 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 14724 if (!Pattern) { 14725 assert(isa<CXXRecordDecl>(Lookup[0]) && 14726 "cannot have other non-field member with same name"); 14727 for (auto L : Lookup) 14728 if (isa<FieldDecl>(L)) { 14729 Pattern = cast<FieldDecl>(L); 14730 break; 14731 } 14732 assert(Pattern && "We must have set the Pattern!"); 14733 } 14734 14735 if (!Pattern->hasInClassInitializer() || 14736 InstantiateInClassInitializer(Loc, Field, Pattern, 14737 getTemplateInstantiationArgs(Field))) { 14738 // Don't diagnose this again. 14739 Field->setInvalidDecl(); 14740 return ExprError(); 14741 } 14742 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 14743 } 14744 14745 // DR1351: 14746 // If the brace-or-equal-initializer of a non-static data member 14747 // invokes a defaulted default constructor of its class or of an 14748 // enclosing class in a potentially evaluated subexpression, the 14749 // program is ill-formed. 14750 // 14751 // This resolution is unworkable: the exception specification of the 14752 // default constructor can be needed in an unevaluated context, in 14753 // particular, in the operand of a noexcept-expression, and we can be 14754 // unable to compute an exception specification for an enclosed class. 14755 // 14756 // Any attempt to resolve the exception specification of a defaulted default 14757 // constructor before the initializer is lexically complete will ultimately 14758 // come here at which point we can diagnose it. 14759 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 14760 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 14761 << OutermostClass << Field; 14762 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 14763 // Recover by marking the field invalid, unless we're in a SFINAE context. 14764 if (!isSFINAEContext()) 14765 Field->setInvalidDecl(); 14766 return ExprError(); 14767 } 14768 14769 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 14770 if (VD->isInvalidDecl()) return; 14771 14772 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 14773 if (ClassDecl->isInvalidDecl()) return; 14774 if (ClassDecl->hasIrrelevantDestructor()) return; 14775 if (ClassDecl->isDependentContext()) return; 14776 14777 if (VD->isNoDestroy(getASTContext())) 14778 return; 14779 14780 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14781 14782 // If this is an array, we'll require the destructor during initialization, so 14783 // we can skip over this. We still want to emit exit-time destructor warnings 14784 // though. 14785 if (!VD->getType()->isArrayType()) { 14786 MarkFunctionReferenced(VD->getLocation(), Destructor); 14787 CheckDestructorAccess(VD->getLocation(), Destructor, 14788 PDiag(diag::err_access_dtor_var) 14789 << VD->getDeclName() << VD->getType()); 14790 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 14791 } 14792 14793 if (Destructor->isTrivial()) return; 14794 14795 // If the destructor is constexpr, check whether the variable has constant 14796 // destruction now. 14797 if (Destructor->isConstexpr()) { 14798 bool HasConstantInit = false; 14799 if (VD->getInit() && !VD->getInit()->isValueDependent()) 14800 HasConstantInit = VD->evaluateValue(); 14801 SmallVector<PartialDiagnosticAt, 8> Notes; 14802 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 14803 HasConstantInit) { 14804 Diag(VD->getLocation(), 14805 diag::err_constexpr_var_requires_const_destruction) << VD; 14806 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 14807 Diag(Notes[I].first, Notes[I].second); 14808 } 14809 } 14810 14811 if (!VD->hasGlobalStorage()) return; 14812 14813 // Emit warning for non-trivial dtor in global scope (a real global, 14814 // class-static, function-static). 14815 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 14816 14817 // TODO: this should be re-enabled for static locals by !CXAAtExit 14818 if (!VD->isStaticLocal()) 14819 Diag(VD->getLocation(), diag::warn_global_destructor); 14820 } 14821 14822 /// Given a constructor and the set of arguments provided for the 14823 /// constructor, convert the arguments and add any required default arguments 14824 /// to form a proper call to this constructor. 14825 /// 14826 /// \returns true if an error occurred, false otherwise. 14827 bool 14828 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 14829 MultiExprArg ArgsPtr, 14830 SourceLocation Loc, 14831 SmallVectorImpl<Expr*> &ConvertedArgs, 14832 bool AllowExplicit, 14833 bool IsListInitialization) { 14834 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 14835 unsigned NumArgs = ArgsPtr.size(); 14836 Expr **Args = ArgsPtr.data(); 14837 14838 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 14839 unsigned NumParams = Proto->getNumParams(); 14840 14841 // If too few arguments are available, we'll fill in the rest with defaults. 14842 if (NumArgs < NumParams) 14843 ConvertedArgs.reserve(NumParams); 14844 else 14845 ConvertedArgs.reserve(NumArgs); 14846 14847 VariadicCallType CallType = 14848 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 14849 SmallVector<Expr *, 8> AllArgs; 14850 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 14851 Proto, 0, 14852 llvm::makeArrayRef(Args, NumArgs), 14853 AllArgs, 14854 CallType, AllowExplicit, 14855 IsListInitialization); 14856 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 14857 14858 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 14859 14860 CheckConstructorCall(Constructor, 14861 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 14862 Proto, Loc); 14863 14864 return Invalid; 14865 } 14866 14867 static inline bool 14868 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 14869 const FunctionDecl *FnDecl) { 14870 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 14871 if (isa<NamespaceDecl>(DC)) { 14872 return SemaRef.Diag(FnDecl->getLocation(), 14873 diag::err_operator_new_delete_declared_in_namespace) 14874 << FnDecl->getDeclName(); 14875 } 14876 14877 if (isa<TranslationUnitDecl>(DC) && 14878 FnDecl->getStorageClass() == SC_Static) { 14879 return SemaRef.Diag(FnDecl->getLocation(), 14880 diag::err_operator_new_delete_declared_static) 14881 << FnDecl->getDeclName(); 14882 } 14883 14884 return false; 14885 } 14886 14887 static QualType 14888 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 14889 QualType QTy = PtrTy->getPointeeType(); 14890 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 14891 return SemaRef.Context.getPointerType(QTy); 14892 } 14893 14894 static inline bool 14895 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 14896 CanQualType ExpectedResultType, 14897 CanQualType ExpectedFirstParamType, 14898 unsigned DependentParamTypeDiag, 14899 unsigned InvalidParamTypeDiag) { 14900 QualType ResultType = 14901 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 14902 14903 // Check that the result type is not dependent. 14904 if (ResultType->isDependentType()) 14905 return SemaRef.Diag(FnDecl->getLocation(), 14906 diag::err_operator_new_delete_dependent_result_type) 14907 << FnDecl->getDeclName() << ExpectedResultType; 14908 14909 // The operator is valid on any address space for OpenCL. 14910 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 14911 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 14912 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 14913 } 14914 } 14915 14916 // Check that the result type is what we expect. 14917 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 14918 return SemaRef.Diag(FnDecl->getLocation(), 14919 diag::err_operator_new_delete_invalid_result_type) 14920 << FnDecl->getDeclName() << ExpectedResultType; 14921 14922 // A function template must have at least 2 parameters. 14923 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 14924 return SemaRef.Diag(FnDecl->getLocation(), 14925 diag::err_operator_new_delete_template_too_few_parameters) 14926 << FnDecl->getDeclName(); 14927 14928 // The function decl must have at least 1 parameter. 14929 if (FnDecl->getNumParams() == 0) 14930 return SemaRef.Diag(FnDecl->getLocation(), 14931 diag::err_operator_new_delete_too_few_parameters) 14932 << FnDecl->getDeclName(); 14933 14934 // Check the first parameter type is not dependent. 14935 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 14936 if (FirstParamType->isDependentType()) 14937 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 14938 << FnDecl->getDeclName() << ExpectedFirstParamType; 14939 14940 // Check that the first parameter type is what we expect. 14941 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 14942 // The operator is valid on any address space for OpenCL. 14943 if (auto *PtrTy = 14944 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 14945 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 14946 } 14947 } 14948 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 14949 ExpectedFirstParamType) 14950 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 14951 << FnDecl->getDeclName() << ExpectedFirstParamType; 14952 14953 return false; 14954 } 14955 14956 static bool 14957 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 14958 // C++ [basic.stc.dynamic.allocation]p1: 14959 // A program is ill-formed if an allocation function is declared in a 14960 // namespace scope other than global scope or declared static in global 14961 // scope. 14962 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 14963 return true; 14964 14965 CanQualType SizeTy = 14966 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 14967 14968 // C++ [basic.stc.dynamic.allocation]p1: 14969 // The return type shall be void*. The first parameter shall have type 14970 // std::size_t. 14971 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 14972 SizeTy, 14973 diag::err_operator_new_dependent_param_type, 14974 diag::err_operator_new_param_type)) 14975 return true; 14976 14977 // C++ [basic.stc.dynamic.allocation]p1: 14978 // The first parameter shall not have an associated default argument. 14979 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 14980 return SemaRef.Diag(FnDecl->getLocation(), 14981 diag::err_operator_new_default_arg) 14982 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 14983 14984 return false; 14985 } 14986 14987 static bool 14988 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 14989 // C++ [basic.stc.dynamic.deallocation]p1: 14990 // A program is ill-formed if deallocation functions are declared in a 14991 // namespace scope other than global scope or declared static in global 14992 // scope. 14993 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 14994 return true; 14995 14996 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 14997 14998 // C++ P0722: 14999 // Within a class C, the first parameter of a destroying operator delete 15000 // shall be of type C *. The first parameter of any other deallocation 15001 // function shall be of type void *. 15002 CanQualType ExpectedFirstParamType = 15003 MD && MD->isDestroyingOperatorDelete() 15004 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15005 SemaRef.Context.getRecordType(MD->getParent()))) 15006 : SemaRef.Context.VoidPtrTy; 15007 15008 // C++ [basic.stc.dynamic.deallocation]p2: 15009 // Each deallocation function shall return void 15010 if (CheckOperatorNewDeleteTypes( 15011 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15012 diag::err_operator_delete_dependent_param_type, 15013 diag::err_operator_delete_param_type)) 15014 return true; 15015 15016 // C++ P0722: 15017 // A destroying operator delete shall be a usual deallocation function. 15018 if (MD && !MD->getParent()->isDependentContext() && 15019 MD->isDestroyingOperatorDelete() && 15020 !SemaRef.isUsualDeallocationFunction(MD)) { 15021 SemaRef.Diag(MD->getLocation(), 15022 diag::err_destroying_operator_delete_not_usual); 15023 return true; 15024 } 15025 15026 return false; 15027 } 15028 15029 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15030 /// of this overloaded operator is well-formed. If so, returns false; 15031 /// otherwise, emits appropriate diagnostics and returns true. 15032 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15033 assert(FnDecl && FnDecl->isOverloadedOperator() && 15034 "Expected an overloaded operator declaration"); 15035 15036 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15037 15038 // C++ [over.oper]p5: 15039 // The allocation and deallocation functions, operator new, 15040 // operator new[], operator delete and operator delete[], are 15041 // described completely in 3.7.3. The attributes and restrictions 15042 // found in the rest of this subclause do not apply to them unless 15043 // explicitly stated in 3.7.3. 15044 if (Op == OO_Delete || Op == OO_Array_Delete) 15045 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15046 15047 if (Op == OO_New || Op == OO_Array_New) 15048 return CheckOperatorNewDeclaration(*this, FnDecl); 15049 15050 // C++ [over.oper]p6: 15051 // An operator function shall either be a non-static member 15052 // function or be a non-member function and have at least one 15053 // parameter whose type is a class, a reference to a class, an 15054 // enumeration, or a reference to an enumeration. 15055 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15056 if (MethodDecl->isStatic()) 15057 return Diag(FnDecl->getLocation(), 15058 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15059 } else { 15060 bool ClassOrEnumParam = false; 15061 for (auto Param : FnDecl->parameters()) { 15062 QualType ParamType = Param->getType().getNonReferenceType(); 15063 if (ParamType->isDependentType() || ParamType->isRecordType() || 15064 ParamType->isEnumeralType()) { 15065 ClassOrEnumParam = true; 15066 break; 15067 } 15068 } 15069 15070 if (!ClassOrEnumParam) 15071 return Diag(FnDecl->getLocation(), 15072 diag::err_operator_overload_needs_class_or_enum) 15073 << FnDecl->getDeclName(); 15074 } 15075 15076 // C++ [over.oper]p8: 15077 // An operator function cannot have default arguments (8.3.6), 15078 // except where explicitly stated below. 15079 // 15080 // Only the function-call operator allows default arguments 15081 // (C++ [over.call]p1). 15082 if (Op != OO_Call) { 15083 for (auto Param : FnDecl->parameters()) { 15084 if (Param->hasDefaultArg()) 15085 return Diag(Param->getLocation(), 15086 diag::err_operator_overload_default_arg) 15087 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15088 } 15089 } 15090 15091 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15092 { false, false, false } 15093 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15094 , { Unary, Binary, MemberOnly } 15095 #include "clang/Basic/OperatorKinds.def" 15096 }; 15097 15098 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15099 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15100 bool MustBeMemberOperator = OperatorUses[Op][2]; 15101 15102 // C++ [over.oper]p8: 15103 // [...] Operator functions cannot have more or fewer parameters 15104 // than the number required for the corresponding operator, as 15105 // described in the rest of this subclause. 15106 unsigned NumParams = FnDecl->getNumParams() 15107 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15108 if (Op != OO_Call && 15109 ((NumParams == 1 && !CanBeUnaryOperator) || 15110 (NumParams == 2 && !CanBeBinaryOperator) || 15111 (NumParams < 1) || (NumParams > 2))) { 15112 // We have the wrong number of parameters. 15113 unsigned ErrorKind; 15114 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15115 ErrorKind = 2; // 2 -> unary or binary. 15116 } else if (CanBeUnaryOperator) { 15117 ErrorKind = 0; // 0 -> unary 15118 } else { 15119 assert(CanBeBinaryOperator && 15120 "All non-call overloaded operators are unary or binary!"); 15121 ErrorKind = 1; // 1 -> binary 15122 } 15123 15124 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15125 << FnDecl->getDeclName() << NumParams << ErrorKind; 15126 } 15127 15128 // Overloaded operators other than operator() cannot be variadic. 15129 if (Op != OO_Call && 15130 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15131 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15132 << FnDecl->getDeclName(); 15133 } 15134 15135 // Some operators must be non-static member functions. 15136 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15137 return Diag(FnDecl->getLocation(), 15138 diag::err_operator_overload_must_be_member) 15139 << FnDecl->getDeclName(); 15140 } 15141 15142 // C++ [over.inc]p1: 15143 // The user-defined function called operator++ implements the 15144 // prefix and postfix ++ operator. If this function is a member 15145 // function with no parameters, or a non-member function with one 15146 // parameter of class or enumeration type, it defines the prefix 15147 // increment operator ++ for objects of that type. If the function 15148 // is a member function with one parameter (which shall be of type 15149 // int) or a non-member function with two parameters (the second 15150 // of which shall be of type int), it defines the postfix 15151 // increment operator ++ for objects of that type. 15152 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15153 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15154 QualType ParamType = LastParam->getType(); 15155 15156 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15157 !ParamType->isDependentType()) 15158 return Diag(LastParam->getLocation(), 15159 diag::err_operator_overload_post_incdec_must_be_int) 15160 << LastParam->getType() << (Op == OO_MinusMinus); 15161 } 15162 15163 return false; 15164 } 15165 15166 static bool 15167 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15168 FunctionTemplateDecl *TpDecl) { 15169 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15170 15171 // Must have one or two template parameters. 15172 if (TemplateParams->size() == 1) { 15173 NonTypeTemplateParmDecl *PmDecl = 15174 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15175 15176 // The template parameter must be a char parameter pack. 15177 if (PmDecl && PmDecl->isTemplateParameterPack() && 15178 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15179 return false; 15180 15181 } else if (TemplateParams->size() == 2) { 15182 TemplateTypeParmDecl *PmType = 15183 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15184 NonTypeTemplateParmDecl *PmArgs = 15185 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15186 15187 // The second template parameter must be a parameter pack with the 15188 // first template parameter as its type. 15189 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15190 PmArgs->isTemplateParameterPack()) { 15191 const TemplateTypeParmType *TArgs = 15192 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15193 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15194 TArgs->getIndex() == PmType->getIndex()) { 15195 if (!SemaRef.inTemplateInstantiation()) 15196 SemaRef.Diag(TpDecl->getLocation(), 15197 diag::ext_string_literal_operator_template); 15198 return false; 15199 } 15200 } 15201 } 15202 15203 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15204 diag::err_literal_operator_template) 15205 << TpDecl->getTemplateParameters()->getSourceRange(); 15206 return true; 15207 } 15208 15209 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15210 /// of this literal operator function is well-formed. If so, returns 15211 /// false; otherwise, emits appropriate diagnostics and returns true. 15212 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15213 if (isa<CXXMethodDecl>(FnDecl)) { 15214 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15215 << FnDecl->getDeclName(); 15216 return true; 15217 } 15218 15219 if (FnDecl->isExternC()) { 15220 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15221 if (const LinkageSpecDecl *LSD = 15222 FnDecl->getDeclContext()->getExternCContext()) 15223 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15224 return true; 15225 } 15226 15227 // This might be the definition of a literal operator template. 15228 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15229 15230 // This might be a specialization of a literal operator template. 15231 if (!TpDecl) 15232 TpDecl = FnDecl->getPrimaryTemplate(); 15233 15234 // template <char...> type operator "" name() and 15235 // template <class T, T...> type operator "" name() are the only valid 15236 // template signatures, and the only valid signatures with no parameters. 15237 if (TpDecl) { 15238 if (FnDecl->param_size() != 0) { 15239 Diag(FnDecl->getLocation(), 15240 diag::err_literal_operator_template_with_params); 15241 return true; 15242 } 15243 15244 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15245 return true; 15246 15247 } else if (FnDecl->param_size() == 1) { 15248 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15249 15250 QualType ParamType = Param->getType().getUnqualifiedType(); 15251 15252 // Only unsigned long long int, long double, any character type, and const 15253 // char * are allowed as the only parameters. 15254 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15255 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15256 Context.hasSameType(ParamType, Context.CharTy) || 15257 Context.hasSameType(ParamType, Context.WideCharTy) || 15258 Context.hasSameType(ParamType, Context.Char8Ty) || 15259 Context.hasSameType(ParamType, Context.Char16Ty) || 15260 Context.hasSameType(ParamType, Context.Char32Ty)) { 15261 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15262 QualType InnerType = Ptr->getPointeeType(); 15263 15264 // Pointer parameter must be a const char *. 15265 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15266 Context.CharTy) && 15267 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15268 Diag(Param->getSourceRange().getBegin(), 15269 diag::err_literal_operator_param) 15270 << ParamType << "'const char *'" << Param->getSourceRange(); 15271 return true; 15272 } 15273 15274 } else if (ParamType->isRealFloatingType()) { 15275 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15276 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15277 return true; 15278 15279 } else if (ParamType->isIntegerType()) { 15280 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15281 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15282 return true; 15283 15284 } else { 15285 Diag(Param->getSourceRange().getBegin(), 15286 diag::err_literal_operator_invalid_param) 15287 << ParamType << Param->getSourceRange(); 15288 return true; 15289 } 15290 15291 } else if (FnDecl->param_size() == 2) { 15292 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15293 15294 // First, verify that the first parameter is correct. 15295 15296 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15297 15298 // Two parameter function must have a pointer to const as a 15299 // first parameter; let's strip those qualifiers. 15300 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15301 15302 if (!PT) { 15303 Diag((*Param)->getSourceRange().getBegin(), 15304 diag::err_literal_operator_param) 15305 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15306 return true; 15307 } 15308 15309 QualType PointeeType = PT->getPointeeType(); 15310 // First parameter must be const 15311 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15312 Diag((*Param)->getSourceRange().getBegin(), 15313 diag::err_literal_operator_param) 15314 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15315 return true; 15316 } 15317 15318 QualType InnerType = PointeeType.getUnqualifiedType(); 15319 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15320 // const char32_t* are allowed as the first parameter to a two-parameter 15321 // function 15322 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15323 Context.hasSameType(InnerType, Context.WideCharTy) || 15324 Context.hasSameType(InnerType, Context.Char8Ty) || 15325 Context.hasSameType(InnerType, Context.Char16Ty) || 15326 Context.hasSameType(InnerType, Context.Char32Ty))) { 15327 Diag((*Param)->getSourceRange().getBegin(), 15328 diag::err_literal_operator_param) 15329 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15330 return true; 15331 } 15332 15333 // Move on to the second and final parameter. 15334 ++Param; 15335 15336 // The second parameter must be a std::size_t. 15337 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15338 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15339 Diag((*Param)->getSourceRange().getBegin(), 15340 diag::err_literal_operator_param) 15341 << SecondParamType << Context.getSizeType() 15342 << (*Param)->getSourceRange(); 15343 return true; 15344 } 15345 } else { 15346 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15347 return true; 15348 } 15349 15350 // Parameters are good. 15351 15352 // A parameter-declaration-clause containing a default argument is not 15353 // equivalent to any of the permitted forms. 15354 for (auto Param : FnDecl->parameters()) { 15355 if (Param->hasDefaultArg()) { 15356 Diag(Param->getDefaultArgRange().getBegin(), 15357 diag::err_literal_operator_default_argument) 15358 << Param->getDefaultArgRange(); 15359 break; 15360 } 15361 } 15362 15363 StringRef LiteralName 15364 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15365 if (LiteralName[0] != '_' && 15366 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15367 // C++11 [usrlit.suffix]p1: 15368 // Literal suffix identifiers that do not start with an underscore 15369 // are reserved for future standardization. 15370 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15371 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15372 } 15373 15374 return false; 15375 } 15376 15377 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15378 /// linkage specification, including the language and (if present) 15379 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15380 /// language string literal. LBraceLoc, if valid, provides the location of 15381 /// the '{' brace. Otherwise, this linkage specification does not 15382 /// have any braces. 15383 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15384 Expr *LangStr, 15385 SourceLocation LBraceLoc) { 15386 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15387 if (!Lit->isAscii()) { 15388 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15389 << LangStr->getSourceRange(); 15390 return nullptr; 15391 } 15392 15393 StringRef Lang = Lit->getString(); 15394 LinkageSpecDecl::LanguageIDs Language; 15395 if (Lang == "C") 15396 Language = LinkageSpecDecl::lang_c; 15397 else if (Lang == "C++") 15398 Language = LinkageSpecDecl::lang_cxx; 15399 else { 15400 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15401 << LangStr->getSourceRange(); 15402 return nullptr; 15403 } 15404 15405 // FIXME: Add all the various semantics of linkage specifications 15406 15407 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15408 LangStr->getExprLoc(), Language, 15409 LBraceLoc.isValid()); 15410 CurContext->addDecl(D); 15411 PushDeclContext(S, D); 15412 return D; 15413 } 15414 15415 /// ActOnFinishLinkageSpecification - Complete the definition of 15416 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15417 /// valid, it's the position of the closing '}' brace in a linkage 15418 /// specification that uses braces. 15419 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15420 Decl *LinkageSpec, 15421 SourceLocation RBraceLoc) { 15422 if (RBraceLoc.isValid()) { 15423 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15424 LSDecl->setRBraceLoc(RBraceLoc); 15425 } 15426 PopDeclContext(); 15427 return LinkageSpec; 15428 } 15429 15430 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15431 const ParsedAttributesView &AttrList, 15432 SourceLocation SemiLoc) { 15433 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15434 // Attribute declarations appertain to empty declaration so we handle 15435 // them here. 15436 ProcessDeclAttributeList(S, ED, AttrList); 15437 15438 CurContext->addDecl(ED); 15439 return ED; 15440 } 15441 15442 /// Perform semantic analysis for the variable declaration that 15443 /// occurs within a C++ catch clause, returning the newly-created 15444 /// variable. 15445 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15446 TypeSourceInfo *TInfo, 15447 SourceLocation StartLoc, 15448 SourceLocation Loc, 15449 IdentifierInfo *Name) { 15450 bool Invalid = false; 15451 QualType ExDeclType = TInfo->getType(); 15452 15453 // Arrays and functions decay. 15454 if (ExDeclType->isArrayType()) 15455 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15456 else if (ExDeclType->isFunctionType()) 15457 ExDeclType = Context.getPointerType(ExDeclType); 15458 15459 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15460 // The exception-declaration shall not denote a pointer or reference to an 15461 // incomplete type, other than [cv] void*. 15462 // N2844 forbids rvalue references. 15463 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15464 Diag(Loc, diag::err_catch_rvalue_ref); 15465 Invalid = true; 15466 } 15467 15468 if (ExDeclType->isVariablyModifiedType()) { 15469 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15470 Invalid = true; 15471 } 15472 15473 QualType BaseType = ExDeclType; 15474 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15475 unsigned DK = diag::err_catch_incomplete; 15476 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15477 BaseType = Ptr->getPointeeType(); 15478 Mode = 1; 15479 DK = diag::err_catch_incomplete_ptr; 15480 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15481 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15482 BaseType = Ref->getPointeeType(); 15483 Mode = 2; 15484 DK = diag::err_catch_incomplete_ref; 15485 } 15486 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15487 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15488 Invalid = true; 15489 15490 if (!Invalid && !ExDeclType->isDependentType() && 15491 RequireNonAbstractType(Loc, ExDeclType, 15492 diag::err_abstract_type_in_decl, 15493 AbstractVariableType)) 15494 Invalid = true; 15495 15496 // Only the non-fragile NeXT runtime currently supports C++ catches 15497 // of ObjC types, and no runtime supports catching ObjC types by value. 15498 if (!Invalid && getLangOpts().ObjC) { 15499 QualType T = ExDeclType; 15500 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15501 T = RT->getPointeeType(); 15502 15503 if (T->isObjCObjectType()) { 15504 Diag(Loc, diag::err_objc_object_catch); 15505 Invalid = true; 15506 } else if (T->isObjCObjectPointerType()) { 15507 // FIXME: should this be a test for macosx-fragile specifically? 15508 if (getLangOpts().ObjCRuntime.isFragile()) 15509 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15510 } 15511 } 15512 15513 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15514 ExDeclType, TInfo, SC_None); 15515 ExDecl->setExceptionVariable(true); 15516 15517 // In ARC, infer 'retaining' for variables of retainable type. 15518 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15519 Invalid = true; 15520 15521 if (!Invalid && !ExDeclType->isDependentType()) { 15522 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15523 // Insulate this from anything else we might currently be parsing. 15524 EnterExpressionEvaluationContext scope( 15525 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15526 15527 // C++ [except.handle]p16: 15528 // The object declared in an exception-declaration or, if the 15529 // exception-declaration does not specify a name, a temporary (12.2) is 15530 // copy-initialized (8.5) from the exception object. [...] 15531 // The object is destroyed when the handler exits, after the destruction 15532 // of any automatic objects initialized within the handler. 15533 // 15534 // We just pretend to initialize the object with itself, then make sure 15535 // it can be destroyed later. 15536 QualType initType = Context.getExceptionObjectType(ExDeclType); 15537 15538 InitializedEntity entity = 15539 InitializedEntity::InitializeVariable(ExDecl); 15540 InitializationKind initKind = 15541 InitializationKind::CreateCopy(Loc, SourceLocation()); 15542 15543 Expr *opaqueValue = 15544 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15545 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15546 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15547 if (result.isInvalid()) 15548 Invalid = true; 15549 else { 15550 // If the constructor used was non-trivial, set this as the 15551 // "initializer". 15552 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15553 if (!construct->getConstructor()->isTrivial()) { 15554 Expr *init = MaybeCreateExprWithCleanups(construct); 15555 ExDecl->setInit(init); 15556 } 15557 15558 // And make sure it's destructable. 15559 FinalizeVarWithDestructor(ExDecl, recordType); 15560 } 15561 } 15562 } 15563 15564 if (Invalid) 15565 ExDecl->setInvalidDecl(); 15566 15567 return ExDecl; 15568 } 15569 15570 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15571 /// handler. 15572 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15573 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15574 bool Invalid = D.isInvalidType(); 15575 15576 // Check for unexpanded parameter packs. 15577 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15578 UPPC_ExceptionType)) { 15579 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15580 D.getIdentifierLoc()); 15581 Invalid = true; 15582 } 15583 15584 IdentifierInfo *II = D.getIdentifier(); 15585 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15586 LookupOrdinaryName, 15587 ForVisibleRedeclaration)) { 15588 // The scope should be freshly made just for us. There is just no way 15589 // it contains any previous declaration, except for function parameters in 15590 // a function-try-block's catch statement. 15591 assert(!S->isDeclScope(PrevDecl)); 15592 if (isDeclInScope(PrevDecl, CurContext, S)) { 15593 Diag(D.getIdentifierLoc(), diag::err_redefinition) 15594 << D.getIdentifier(); 15595 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15596 Invalid = true; 15597 } else if (PrevDecl->isTemplateParameter()) 15598 // Maybe we will complain about the shadowed template parameter. 15599 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15600 } 15601 15602 if (D.getCXXScopeSpec().isSet() && !Invalid) { 15603 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 15604 << D.getCXXScopeSpec().getRange(); 15605 Invalid = true; 15606 } 15607 15608 VarDecl *ExDecl = BuildExceptionDeclaration( 15609 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 15610 if (Invalid) 15611 ExDecl->setInvalidDecl(); 15612 15613 // Add the exception declaration into this scope. 15614 if (II) 15615 PushOnScopeChains(ExDecl, S); 15616 else 15617 CurContext->addDecl(ExDecl); 15618 15619 ProcessDeclAttributes(S, ExDecl, D); 15620 return ExDecl; 15621 } 15622 15623 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15624 Expr *AssertExpr, 15625 Expr *AssertMessageExpr, 15626 SourceLocation RParenLoc) { 15627 StringLiteral *AssertMessage = 15628 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 15629 15630 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 15631 return nullptr; 15632 15633 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 15634 AssertMessage, RParenLoc, false); 15635 } 15636 15637 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15638 Expr *AssertExpr, 15639 StringLiteral *AssertMessage, 15640 SourceLocation RParenLoc, 15641 bool Failed) { 15642 assert(AssertExpr != nullptr && "Expected non-null condition"); 15643 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 15644 !Failed) { 15645 // In a static_assert-declaration, the constant-expression shall be a 15646 // constant expression that can be contextually converted to bool. 15647 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 15648 if (Converted.isInvalid()) 15649 Failed = true; 15650 15651 ExprResult FullAssertExpr = 15652 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 15653 /*DiscardedValue*/ false, 15654 /*IsConstexpr*/ true); 15655 if (FullAssertExpr.isInvalid()) 15656 Failed = true; 15657 else 15658 AssertExpr = FullAssertExpr.get(); 15659 15660 llvm::APSInt Cond; 15661 if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond, 15662 diag::err_static_assert_expression_is_not_constant, 15663 /*AllowFold=*/false).isInvalid()) 15664 Failed = true; 15665 15666 if (!Failed && !Cond) { 15667 SmallString<256> MsgBuffer; 15668 llvm::raw_svector_ostream Msg(MsgBuffer); 15669 if (AssertMessage) 15670 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 15671 15672 Expr *InnerCond = nullptr; 15673 std::string InnerCondDescription; 15674 std::tie(InnerCond, InnerCondDescription) = 15675 findFailedBooleanCondition(Converted.get()); 15676 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 15677 // Drill down into concept specialization expressions to see why they 15678 // weren't satisfied. 15679 Diag(StaticAssertLoc, diag::err_static_assert_failed) 15680 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 15681 ConstraintSatisfaction Satisfaction; 15682 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 15683 DiagnoseUnsatisfiedConstraint(Satisfaction); 15684 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 15685 && !isa<IntegerLiteral>(InnerCond)) { 15686 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 15687 << InnerCondDescription << !AssertMessage 15688 << Msg.str() << InnerCond->getSourceRange(); 15689 } else { 15690 Diag(StaticAssertLoc, diag::err_static_assert_failed) 15691 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 15692 } 15693 Failed = true; 15694 } 15695 } else { 15696 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 15697 /*DiscardedValue*/false, 15698 /*IsConstexpr*/true); 15699 if (FullAssertExpr.isInvalid()) 15700 Failed = true; 15701 else 15702 AssertExpr = FullAssertExpr.get(); 15703 } 15704 15705 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 15706 AssertExpr, AssertMessage, RParenLoc, 15707 Failed); 15708 15709 CurContext->addDecl(Decl); 15710 return Decl; 15711 } 15712 15713 /// Perform semantic analysis of the given friend type declaration. 15714 /// 15715 /// \returns A friend declaration that. 15716 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 15717 SourceLocation FriendLoc, 15718 TypeSourceInfo *TSInfo) { 15719 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 15720 15721 QualType T = TSInfo->getType(); 15722 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 15723 15724 // C++03 [class.friend]p2: 15725 // An elaborated-type-specifier shall be used in a friend declaration 15726 // for a class.* 15727 // 15728 // * The class-key of the elaborated-type-specifier is required. 15729 if (!CodeSynthesisContexts.empty()) { 15730 // Do not complain about the form of friend template types during any kind 15731 // of code synthesis. For template instantiation, we will have complained 15732 // when the template was defined. 15733 } else { 15734 if (!T->isElaboratedTypeSpecifier()) { 15735 // If we evaluated the type to a record type, suggest putting 15736 // a tag in front. 15737 if (const RecordType *RT = T->getAs<RecordType>()) { 15738 RecordDecl *RD = RT->getDecl(); 15739 15740 SmallString<16> InsertionText(" "); 15741 InsertionText += RD->getKindName(); 15742 15743 Diag(TypeRange.getBegin(), 15744 getLangOpts().CPlusPlus11 ? 15745 diag::warn_cxx98_compat_unelaborated_friend_type : 15746 diag::ext_unelaborated_friend_type) 15747 << (unsigned) RD->getTagKind() 15748 << T 15749 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 15750 InsertionText); 15751 } else { 15752 Diag(FriendLoc, 15753 getLangOpts().CPlusPlus11 ? 15754 diag::warn_cxx98_compat_nonclass_type_friend : 15755 diag::ext_nonclass_type_friend) 15756 << T 15757 << TypeRange; 15758 } 15759 } else if (T->getAs<EnumType>()) { 15760 Diag(FriendLoc, 15761 getLangOpts().CPlusPlus11 ? 15762 diag::warn_cxx98_compat_enum_friend : 15763 diag::ext_enum_friend) 15764 << T 15765 << TypeRange; 15766 } 15767 15768 // C++11 [class.friend]p3: 15769 // A friend declaration that does not declare a function shall have one 15770 // of the following forms: 15771 // friend elaborated-type-specifier ; 15772 // friend simple-type-specifier ; 15773 // friend typename-specifier ; 15774 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 15775 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 15776 } 15777 15778 // If the type specifier in a friend declaration designates a (possibly 15779 // cv-qualified) class type, that class is declared as a friend; otherwise, 15780 // the friend declaration is ignored. 15781 return FriendDecl::Create(Context, CurContext, 15782 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 15783 FriendLoc); 15784 } 15785 15786 /// Handle a friend tag declaration where the scope specifier was 15787 /// templated. 15788 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 15789 unsigned TagSpec, SourceLocation TagLoc, 15790 CXXScopeSpec &SS, IdentifierInfo *Name, 15791 SourceLocation NameLoc, 15792 const ParsedAttributesView &Attr, 15793 MultiTemplateParamsArg TempParamLists) { 15794 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15795 15796 bool IsMemberSpecialization = false; 15797 bool Invalid = false; 15798 15799 if (TemplateParameterList *TemplateParams = 15800 MatchTemplateParametersToScopeSpecifier( 15801 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 15802 IsMemberSpecialization, Invalid)) { 15803 if (TemplateParams->size() > 0) { 15804 // This is a declaration of a class template. 15805 if (Invalid) 15806 return nullptr; 15807 15808 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 15809 NameLoc, Attr, TemplateParams, AS_public, 15810 /*ModulePrivateLoc=*/SourceLocation(), 15811 FriendLoc, TempParamLists.size() - 1, 15812 TempParamLists.data()).get(); 15813 } else { 15814 // The "template<>" header is extraneous. 15815 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15816 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15817 IsMemberSpecialization = true; 15818 } 15819 } 15820 15821 if (Invalid) return nullptr; 15822 15823 bool isAllExplicitSpecializations = true; 15824 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 15825 if (TempParamLists[I]->size()) { 15826 isAllExplicitSpecializations = false; 15827 break; 15828 } 15829 } 15830 15831 // FIXME: don't ignore attributes. 15832 15833 // If it's explicit specializations all the way down, just forget 15834 // about the template header and build an appropriate non-templated 15835 // friend. TODO: for source fidelity, remember the headers. 15836 if (isAllExplicitSpecializations) { 15837 if (SS.isEmpty()) { 15838 bool Owned = false; 15839 bool IsDependent = false; 15840 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 15841 Attr, AS_public, 15842 /*ModulePrivateLoc=*/SourceLocation(), 15843 MultiTemplateParamsArg(), Owned, IsDependent, 15844 /*ScopedEnumKWLoc=*/SourceLocation(), 15845 /*ScopedEnumUsesClassTag=*/false, 15846 /*UnderlyingType=*/TypeResult(), 15847 /*IsTypeSpecifier=*/false, 15848 /*IsTemplateParamOrArg=*/false); 15849 } 15850 15851 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 15852 ElaboratedTypeKeyword Keyword 15853 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 15854 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 15855 *Name, NameLoc); 15856 if (T.isNull()) 15857 return nullptr; 15858 15859 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 15860 if (isa<DependentNameType>(T)) { 15861 DependentNameTypeLoc TL = 15862 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 15863 TL.setElaboratedKeywordLoc(TagLoc); 15864 TL.setQualifierLoc(QualifierLoc); 15865 TL.setNameLoc(NameLoc); 15866 } else { 15867 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 15868 TL.setElaboratedKeywordLoc(TagLoc); 15869 TL.setQualifierLoc(QualifierLoc); 15870 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 15871 } 15872 15873 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 15874 TSI, FriendLoc, TempParamLists); 15875 Friend->setAccess(AS_public); 15876 CurContext->addDecl(Friend); 15877 return Friend; 15878 } 15879 15880 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 15881 15882 15883 15884 // Handle the case of a templated-scope friend class. e.g. 15885 // template <class T> class A<T>::B; 15886 // FIXME: we don't support these right now. 15887 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 15888 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 15889 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 15890 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 15891 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 15892 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 15893 TL.setElaboratedKeywordLoc(TagLoc); 15894 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 15895 TL.setNameLoc(NameLoc); 15896 15897 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 15898 TSI, FriendLoc, TempParamLists); 15899 Friend->setAccess(AS_public); 15900 Friend->setUnsupportedFriend(true); 15901 CurContext->addDecl(Friend); 15902 return Friend; 15903 } 15904 15905 /// Handle a friend type declaration. This works in tandem with 15906 /// ActOnTag. 15907 /// 15908 /// Notes on friend class templates: 15909 /// 15910 /// We generally treat friend class declarations as if they were 15911 /// declaring a class. So, for example, the elaborated type specifier 15912 /// in a friend declaration is required to obey the restrictions of a 15913 /// class-head (i.e. no typedefs in the scope chain), template 15914 /// parameters are required to match up with simple template-ids, &c. 15915 /// However, unlike when declaring a template specialization, it's 15916 /// okay to refer to a template specialization without an empty 15917 /// template parameter declaration, e.g. 15918 /// friend class A<T>::B<unsigned>; 15919 /// We permit this as a special case; if there are any template 15920 /// parameters present at all, require proper matching, i.e. 15921 /// template <> template \<class T> friend class A<int>::B; 15922 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 15923 MultiTemplateParamsArg TempParams) { 15924 SourceLocation Loc = DS.getBeginLoc(); 15925 15926 assert(DS.isFriendSpecified()); 15927 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 15928 15929 // C++ [class.friend]p3: 15930 // A friend declaration that does not declare a function shall have one of 15931 // the following forms: 15932 // friend elaborated-type-specifier ; 15933 // friend simple-type-specifier ; 15934 // friend typename-specifier ; 15935 // 15936 // Any declaration with a type qualifier does not have that form. (It's 15937 // legal to specify a qualified type as a friend, you just can't write the 15938 // keywords.) 15939 if (DS.getTypeQualifiers()) { 15940 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 15941 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 15942 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 15943 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 15944 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 15945 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 15946 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 15947 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 15948 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 15949 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 15950 } 15951 15952 // Try to convert the decl specifier to a type. This works for 15953 // friend templates because ActOnTag never produces a ClassTemplateDecl 15954 // for a TUK_Friend. 15955 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 15956 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 15957 QualType T = TSI->getType(); 15958 if (TheDeclarator.isInvalidType()) 15959 return nullptr; 15960 15961 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 15962 return nullptr; 15963 15964 // This is definitely an error in C++98. It's probably meant to 15965 // be forbidden in C++0x, too, but the specification is just 15966 // poorly written. 15967 // 15968 // The problem is with declarations like the following: 15969 // template <T> friend A<T>::foo; 15970 // where deciding whether a class C is a friend or not now hinges 15971 // on whether there exists an instantiation of A that causes 15972 // 'foo' to equal C. There are restrictions on class-heads 15973 // (which we declare (by fiat) elaborated friend declarations to 15974 // be) that makes this tractable. 15975 // 15976 // FIXME: handle "template <> friend class A<T>;", which 15977 // is possibly well-formed? Who even knows? 15978 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 15979 Diag(Loc, diag::err_tagless_friend_type_template) 15980 << DS.getSourceRange(); 15981 return nullptr; 15982 } 15983 15984 // C++98 [class.friend]p1: A friend of a class is a function 15985 // or class that is not a member of the class . . . 15986 // This is fixed in DR77, which just barely didn't make the C++03 15987 // deadline. It's also a very silly restriction that seriously 15988 // affects inner classes and which nobody else seems to implement; 15989 // thus we never diagnose it, not even in -pedantic. 15990 // 15991 // But note that we could warn about it: it's always useless to 15992 // friend one of your own members (it's not, however, worthless to 15993 // friend a member of an arbitrary specialization of your template). 15994 15995 Decl *D; 15996 if (!TempParams.empty()) 15997 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 15998 TempParams, 15999 TSI, 16000 DS.getFriendSpecLoc()); 16001 else 16002 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16003 16004 if (!D) 16005 return nullptr; 16006 16007 D->setAccess(AS_public); 16008 CurContext->addDecl(D); 16009 16010 return D; 16011 } 16012 16013 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16014 MultiTemplateParamsArg TemplateParams) { 16015 const DeclSpec &DS = D.getDeclSpec(); 16016 16017 assert(DS.isFriendSpecified()); 16018 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16019 16020 SourceLocation Loc = D.getIdentifierLoc(); 16021 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16022 16023 // C++ [class.friend]p1 16024 // A friend of a class is a function or class.... 16025 // Note that this sees through typedefs, which is intended. 16026 // It *doesn't* see through dependent types, which is correct 16027 // according to [temp.arg.type]p3: 16028 // If a declaration acquires a function type through a 16029 // type dependent on a template-parameter and this causes 16030 // a declaration that does not use the syntactic form of a 16031 // function declarator to have a function type, the program 16032 // is ill-formed. 16033 if (!TInfo->getType()->isFunctionType()) { 16034 Diag(Loc, diag::err_unexpected_friend); 16035 16036 // It might be worthwhile to try to recover by creating an 16037 // appropriate declaration. 16038 return nullptr; 16039 } 16040 16041 // C++ [namespace.memdef]p3 16042 // - If a friend declaration in a non-local class first declares a 16043 // class or function, the friend class or function is a member 16044 // of the innermost enclosing namespace. 16045 // - The name of the friend is not found by simple name lookup 16046 // until a matching declaration is provided in that namespace 16047 // scope (either before or after the class declaration granting 16048 // friendship). 16049 // - If a friend function is called, its name may be found by the 16050 // name lookup that considers functions from namespaces and 16051 // classes associated with the types of the function arguments. 16052 // - When looking for a prior declaration of a class or a function 16053 // declared as a friend, scopes outside the innermost enclosing 16054 // namespace scope are not considered. 16055 16056 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16057 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16058 assert(NameInfo.getName()); 16059 16060 // Check for unexpanded parameter packs. 16061 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16062 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16063 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16064 return nullptr; 16065 16066 // The context we found the declaration in, or in which we should 16067 // create the declaration. 16068 DeclContext *DC; 16069 Scope *DCScope = S; 16070 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16071 ForExternalRedeclaration); 16072 16073 // There are five cases here. 16074 // - There's no scope specifier and we're in a local class. Only look 16075 // for functions declared in the immediately-enclosing block scope. 16076 // We recover from invalid scope qualifiers as if they just weren't there. 16077 FunctionDecl *FunctionContainingLocalClass = nullptr; 16078 if ((SS.isInvalid() || !SS.isSet()) && 16079 (FunctionContainingLocalClass = 16080 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16081 // C++11 [class.friend]p11: 16082 // If a friend declaration appears in a local class and the name 16083 // specified is an unqualified name, a prior declaration is 16084 // looked up without considering scopes that are outside the 16085 // innermost enclosing non-class scope. For a friend function 16086 // declaration, if there is no prior declaration, the program is 16087 // ill-formed. 16088 16089 // Find the innermost enclosing non-class scope. This is the block 16090 // scope containing the local class definition (or for a nested class, 16091 // the outer local class). 16092 DCScope = S->getFnParent(); 16093 16094 // Look up the function name in the scope. 16095 Previous.clear(LookupLocalFriendName); 16096 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16097 16098 if (!Previous.empty()) { 16099 // All possible previous declarations must have the same context: 16100 // either they were declared at block scope or they are members of 16101 // one of the enclosing local classes. 16102 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16103 } else { 16104 // This is ill-formed, but provide the context that we would have 16105 // declared the function in, if we were permitted to, for error recovery. 16106 DC = FunctionContainingLocalClass; 16107 } 16108 adjustContextForLocalExternDecl(DC); 16109 16110 // C++ [class.friend]p6: 16111 // A function can be defined in a friend declaration of a class if and 16112 // only if the class is a non-local class (9.8), the function name is 16113 // unqualified, and the function has namespace scope. 16114 if (D.isFunctionDefinition()) { 16115 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16116 } 16117 16118 // - There's no scope specifier, in which case we just go to the 16119 // appropriate scope and look for a function or function template 16120 // there as appropriate. 16121 } else if (SS.isInvalid() || !SS.isSet()) { 16122 // C++11 [namespace.memdef]p3: 16123 // If the name in a friend declaration is neither qualified nor 16124 // a template-id and the declaration is a function or an 16125 // elaborated-type-specifier, the lookup to determine whether 16126 // the entity has been previously declared shall not consider 16127 // any scopes outside the innermost enclosing namespace. 16128 bool isTemplateId = 16129 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16130 16131 // Find the appropriate context according to the above. 16132 DC = CurContext; 16133 16134 // Skip class contexts. If someone can cite chapter and verse 16135 // for this behavior, that would be nice --- it's what GCC and 16136 // EDG do, and it seems like a reasonable intent, but the spec 16137 // really only says that checks for unqualified existing 16138 // declarations should stop at the nearest enclosing namespace, 16139 // not that they should only consider the nearest enclosing 16140 // namespace. 16141 while (DC->isRecord()) 16142 DC = DC->getParent(); 16143 16144 DeclContext *LookupDC = DC; 16145 while (LookupDC->isTransparentContext()) 16146 LookupDC = LookupDC->getParent(); 16147 16148 while (true) { 16149 LookupQualifiedName(Previous, LookupDC); 16150 16151 if (!Previous.empty()) { 16152 DC = LookupDC; 16153 break; 16154 } 16155 16156 if (isTemplateId) { 16157 if (isa<TranslationUnitDecl>(LookupDC)) break; 16158 } else { 16159 if (LookupDC->isFileContext()) break; 16160 } 16161 LookupDC = LookupDC->getParent(); 16162 } 16163 16164 DCScope = getScopeForDeclContext(S, DC); 16165 16166 // - There's a non-dependent scope specifier, in which case we 16167 // compute it and do a previous lookup there for a function 16168 // or function template. 16169 } else if (!SS.getScopeRep()->isDependent()) { 16170 DC = computeDeclContext(SS); 16171 if (!DC) return nullptr; 16172 16173 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16174 16175 LookupQualifiedName(Previous, DC); 16176 16177 // C++ [class.friend]p1: A friend of a class is a function or 16178 // class that is not a member of the class . . . 16179 if (DC->Equals(CurContext)) 16180 Diag(DS.getFriendSpecLoc(), 16181 getLangOpts().CPlusPlus11 ? 16182 diag::warn_cxx98_compat_friend_is_member : 16183 diag::err_friend_is_member); 16184 16185 if (D.isFunctionDefinition()) { 16186 // C++ [class.friend]p6: 16187 // A function can be defined in a friend declaration of a class if and 16188 // only if the class is a non-local class (9.8), the function name is 16189 // unqualified, and the function has namespace scope. 16190 // 16191 // FIXME: We should only do this if the scope specifier names the 16192 // innermost enclosing namespace; otherwise the fixit changes the 16193 // meaning of the code. 16194 SemaDiagnosticBuilder DB 16195 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16196 16197 DB << SS.getScopeRep(); 16198 if (DC->isFileContext()) 16199 DB << FixItHint::CreateRemoval(SS.getRange()); 16200 SS.clear(); 16201 } 16202 16203 // - There's a scope specifier that does not match any template 16204 // parameter lists, in which case we use some arbitrary context, 16205 // create a method or method template, and wait for instantiation. 16206 // - There's a scope specifier that does match some template 16207 // parameter lists, which we don't handle right now. 16208 } else { 16209 if (D.isFunctionDefinition()) { 16210 // C++ [class.friend]p6: 16211 // A function can be defined in a friend declaration of a class if and 16212 // only if the class is a non-local class (9.8), the function name is 16213 // unqualified, and the function has namespace scope. 16214 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16215 << SS.getScopeRep(); 16216 } 16217 16218 DC = CurContext; 16219 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16220 } 16221 16222 if (!DC->isRecord()) { 16223 int DiagArg = -1; 16224 switch (D.getName().getKind()) { 16225 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16226 case UnqualifiedIdKind::IK_ConstructorName: 16227 DiagArg = 0; 16228 break; 16229 case UnqualifiedIdKind::IK_DestructorName: 16230 DiagArg = 1; 16231 break; 16232 case UnqualifiedIdKind::IK_ConversionFunctionId: 16233 DiagArg = 2; 16234 break; 16235 case UnqualifiedIdKind::IK_DeductionGuideName: 16236 DiagArg = 3; 16237 break; 16238 case UnqualifiedIdKind::IK_Identifier: 16239 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16240 case UnqualifiedIdKind::IK_LiteralOperatorId: 16241 case UnqualifiedIdKind::IK_OperatorFunctionId: 16242 case UnqualifiedIdKind::IK_TemplateId: 16243 break; 16244 } 16245 // This implies that it has to be an operator or function. 16246 if (DiagArg >= 0) { 16247 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16248 return nullptr; 16249 } 16250 } 16251 16252 // FIXME: This is an egregious hack to cope with cases where the scope stack 16253 // does not contain the declaration context, i.e., in an out-of-line 16254 // definition of a class. 16255 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16256 if (!DCScope) { 16257 FakeDCScope.setEntity(DC); 16258 DCScope = &FakeDCScope; 16259 } 16260 16261 bool AddToScope = true; 16262 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16263 TemplateParams, AddToScope); 16264 if (!ND) return nullptr; 16265 16266 assert(ND->getLexicalDeclContext() == CurContext); 16267 16268 // If we performed typo correction, we might have added a scope specifier 16269 // and changed the decl context. 16270 DC = ND->getDeclContext(); 16271 16272 // Add the function declaration to the appropriate lookup tables, 16273 // adjusting the redeclarations list as necessary. We don't 16274 // want to do this yet if the friending class is dependent. 16275 // 16276 // Also update the scope-based lookup if the target context's 16277 // lookup context is in lexical scope. 16278 if (!CurContext->isDependentContext()) { 16279 DC = DC->getRedeclContext(); 16280 DC->makeDeclVisibleInContext(ND); 16281 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16282 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16283 } 16284 16285 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16286 D.getIdentifierLoc(), ND, 16287 DS.getFriendSpecLoc()); 16288 FrD->setAccess(AS_public); 16289 CurContext->addDecl(FrD); 16290 16291 if (ND->isInvalidDecl()) { 16292 FrD->setInvalidDecl(); 16293 } else { 16294 if (DC->isRecord()) CheckFriendAccess(ND); 16295 16296 FunctionDecl *FD; 16297 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16298 FD = FTD->getTemplatedDecl(); 16299 else 16300 FD = cast<FunctionDecl>(ND); 16301 16302 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16303 // default argument expression, that declaration shall be a definition 16304 // and shall be the only declaration of the function or function 16305 // template in the translation unit. 16306 if (functionDeclHasDefaultArgument(FD)) { 16307 // We can't look at FD->getPreviousDecl() because it may not have been set 16308 // if we're in a dependent context. If the function is known to be a 16309 // redeclaration, we will have narrowed Previous down to the right decl. 16310 if (D.isRedeclaration()) { 16311 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16312 Diag(Previous.getRepresentativeDecl()->getLocation(), 16313 diag::note_previous_declaration); 16314 } else if (!D.isFunctionDefinition()) 16315 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16316 } 16317 16318 // Mark templated-scope function declarations as unsupported. 16319 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16320 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16321 << SS.getScopeRep() << SS.getRange() 16322 << cast<CXXRecordDecl>(CurContext); 16323 FrD->setUnsupportedFriend(true); 16324 } 16325 } 16326 16327 return ND; 16328 } 16329 16330 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16331 AdjustDeclIfTemplate(Dcl); 16332 16333 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16334 if (!Fn) { 16335 Diag(DelLoc, diag::err_deleted_non_function); 16336 return; 16337 } 16338 16339 // Deleted function does not have a body. 16340 Fn->setWillHaveBody(false); 16341 16342 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16343 // Don't consider the implicit declaration we generate for explicit 16344 // specializations. FIXME: Do not generate these implicit declarations. 16345 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16346 Prev->getPreviousDecl()) && 16347 !Prev->isDefined()) { 16348 Diag(DelLoc, diag::err_deleted_decl_not_first); 16349 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16350 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16351 : diag::note_previous_declaration); 16352 } 16353 // If the declaration wasn't the first, we delete the function anyway for 16354 // recovery. 16355 Fn = Fn->getCanonicalDecl(); 16356 } 16357 16358 // dllimport/dllexport cannot be deleted. 16359 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16360 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16361 Fn->setInvalidDecl(); 16362 } 16363 16364 if (Fn->isDeleted()) 16365 return; 16366 16367 // C++11 [basic.start.main]p3: 16368 // A program that defines main as deleted [...] is ill-formed. 16369 if (Fn->isMain()) 16370 Diag(DelLoc, diag::err_deleted_main); 16371 16372 // C++11 [dcl.fct.def.delete]p4: 16373 // A deleted function is implicitly inline. 16374 Fn->setImplicitlyInline(); 16375 Fn->setDeletedAsWritten(); 16376 16377 // See if we're deleting a function which is already known to override a 16378 // non-deleted virtual function. 16379 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 16380 bool IssuedDiagnostic = false; 16381 for (const CXXMethodDecl *O : MD->overridden_methods()) { 16382 if (!(*MD->begin_overridden_methods())->isDeleted()) { 16383 if (!IssuedDiagnostic) { 16384 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 16385 IssuedDiagnostic = true; 16386 } 16387 Diag(O->getLocation(), diag::note_overridden_virtual_function); 16388 } 16389 } 16390 // If this function was implicitly deleted because it was defaulted, 16391 // explain why it was deleted. 16392 if (IssuedDiagnostic && MD->isDefaulted()) 16393 DiagnoseDeletedDefaultedFunction(MD); 16394 } 16395 } 16396 16397 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16398 if (!Dcl || Dcl->isInvalidDecl()) 16399 return; 16400 16401 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16402 if (!FD) { 16403 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16404 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16405 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16406 return; 16407 } 16408 } 16409 16410 Diag(DefaultLoc, diag::err_default_special_members) 16411 << getLangOpts().CPlusPlus2a; 16412 return; 16413 } 16414 16415 // Reject if this can't possibly be a defaultable function. 16416 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16417 if (!DefKind && 16418 // A dependent function that doesn't locally look defaultable can 16419 // still instantiate to a defaultable function if it's a constructor 16420 // or assignment operator. 16421 (!FD->isDependentContext() || 16422 (!isa<CXXConstructorDecl>(FD) && 16423 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16424 Diag(DefaultLoc, diag::err_default_special_members) 16425 << getLangOpts().CPlusPlus2a; 16426 return; 16427 } 16428 16429 if (DefKind.isComparison() && 16430 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16431 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16432 << (int)DefKind.asComparison(); 16433 return; 16434 } 16435 16436 // Issue compatibility warning. We already warned if the operator is 16437 // 'operator<=>' when parsing the '<=>' token. 16438 if (DefKind.isComparison() && 16439 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16440 Diag(DefaultLoc, getLangOpts().CPlusPlus2a 16441 ? diag::warn_cxx17_compat_defaulted_comparison 16442 : diag::ext_defaulted_comparison); 16443 } 16444 16445 FD->setDefaulted(); 16446 FD->setExplicitlyDefaulted(); 16447 16448 // Defer checking functions that are defaulted in a dependent context. 16449 if (FD->isDependentContext()) 16450 return; 16451 16452 // Unset that we will have a body for this function. We might not, 16453 // if it turns out to be trivial, and we don't need this marking now 16454 // that we've marked it as defaulted. 16455 FD->setWillHaveBody(false); 16456 16457 // If this definition appears within the record, do the checking when 16458 // the record is complete. This is always the case for a defaulted 16459 // comparison. 16460 if (DefKind.isComparison()) 16461 return; 16462 auto *MD = cast<CXXMethodDecl>(FD); 16463 16464 const FunctionDecl *Primary = FD; 16465 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16466 // Ask the template instantiation pattern that actually had the 16467 // '= default' on it. 16468 Primary = Pattern; 16469 16470 // If the method was defaulted on its first declaration, we will have 16471 // already performed the checking in CheckCompletedCXXClass. Such a 16472 // declaration doesn't trigger an implicit definition. 16473 if (Primary->getCanonicalDecl()->isDefaulted()) 16474 return; 16475 16476 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16477 MD->setInvalidDecl(); 16478 else 16479 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 16480 } 16481 16482 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16483 for (Stmt *SubStmt : S->children()) { 16484 if (!SubStmt) 16485 continue; 16486 if (isa<ReturnStmt>(SubStmt)) 16487 Self.Diag(SubStmt->getBeginLoc(), 16488 diag::err_return_in_constructor_handler); 16489 if (!isa<Expr>(SubStmt)) 16490 SearchForReturnInStmt(Self, SubStmt); 16491 } 16492 } 16493 16494 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16495 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16496 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16497 SearchForReturnInStmt(*this, Handler); 16498 } 16499 } 16500 16501 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16502 const CXXMethodDecl *Old) { 16503 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16504 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16505 16506 if (OldFT->hasExtParameterInfos()) { 16507 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16508 // A parameter of the overriding method should be annotated with noescape 16509 // if the corresponding parameter of the overridden method is annotated. 16510 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16511 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16512 Diag(New->getParamDecl(I)->getLocation(), 16513 diag::warn_overriding_method_missing_noescape); 16514 Diag(Old->getParamDecl(I)->getLocation(), 16515 diag::note_overridden_marked_noescape); 16516 } 16517 } 16518 16519 // Virtual overrides must have the same code_seg. 16520 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16521 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16522 if ((NewCSA || OldCSA) && 16523 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16524 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16525 Diag(Old->getLocation(), diag::note_previous_declaration); 16526 return true; 16527 } 16528 16529 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16530 16531 // If the calling conventions match, everything is fine 16532 if (NewCC == OldCC) 16533 return false; 16534 16535 // If the calling conventions mismatch because the new function is static, 16536 // suppress the calling convention mismatch error; the error about static 16537 // function override (err_static_overrides_virtual from 16538 // Sema::CheckFunctionDeclaration) is more clear. 16539 if (New->getStorageClass() == SC_Static) 16540 return false; 16541 16542 Diag(New->getLocation(), 16543 diag::err_conflicting_overriding_cc_attributes) 16544 << New->getDeclName() << New->getType() << Old->getType(); 16545 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16546 return true; 16547 } 16548 16549 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16550 const CXXMethodDecl *Old) { 16551 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 16552 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 16553 16554 if (Context.hasSameType(NewTy, OldTy) || 16555 NewTy->isDependentType() || OldTy->isDependentType()) 16556 return false; 16557 16558 // Check if the return types are covariant 16559 QualType NewClassTy, OldClassTy; 16560 16561 /// Both types must be pointers or references to classes. 16562 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16563 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16564 NewClassTy = NewPT->getPointeeType(); 16565 OldClassTy = OldPT->getPointeeType(); 16566 } 16567 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16568 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16569 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16570 NewClassTy = NewRT->getPointeeType(); 16571 OldClassTy = OldRT->getPointeeType(); 16572 } 16573 } 16574 } 16575 16576 // The return types aren't either both pointers or references to a class type. 16577 if (NewClassTy.isNull()) { 16578 Diag(New->getLocation(), 16579 diag::err_different_return_type_for_overriding_virtual_function) 16580 << New->getDeclName() << NewTy << OldTy 16581 << New->getReturnTypeSourceRange(); 16582 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16583 << Old->getReturnTypeSourceRange(); 16584 16585 return true; 16586 } 16587 16588 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16589 // C++14 [class.virtual]p8: 16590 // If the class type in the covariant return type of D::f differs from 16591 // that of B::f, the class type in the return type of D::f shall be 16592 // complete at the point of declaration of D::f or shall be the class 16593 // type D. 16594 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16595 if (!RT->isBeingDefined() && 16596 RequireCompleteType(New->getLocation(), NewClassTy, 16597 diag::err_covariant_return_incomplete, 16598 New->getDeclName())) 16599 return true; 16600 } 16601 16602 // Check if the new class derives from the old class. 16603 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 16604 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 16605 << New->getDeclName() << NewTy << OldTy 16606 << New->getReturnTypeSourceRange(); 16607 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16608 << Old->getReturnTypeSourceRange(); 16609 return true; 16610 } 16611 16612 // Check if we the conversion from derived to base is valid. 16613 if (CheckDerivedToBaseConversion( 16614 NewClassTy, OldClassTy, 16615 diag::err_covariant_return_inaccessible_base, 16616 diag::err_covariant_return_ambiguous_derived_to_base_conv, 16617 New->getLocation(), New->getReturnTypeSourceRange(), 16618 New->getDeclName(), nullptr)) { 16619 // FIXME: this note won't trigger for delayed access control 16620 // diagnostics, and it's impossible to get an undelayed error 16621 // here from access control during the original parse because 16622 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 16623 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16624 << Old->getReturnTypeSourceRange(); 16625 return true; 16626 } 16627 } 16628 16629 // The qualifiers of the return types must be the same. 16630 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 16631 Diag(New->getLocation(), 16632 diag::err_covariant_return_type_different_qualifications) 16633 << New->getDeclName() << NewTy << OldTy 16634 << New->getReturnTypeSourceRange(); 16635 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16636 << Old->getReturnTypeSourceRange(); 16637 return true; 16638 } 16639 16640 16641 // The new class type must have the same or less qualifiers as the old type. 16642 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 16643 Diag(New->getLocation(), 16644 diag::err_covariant_return_type_class_type_more_qualified) 16645 << New->getDeclName() << NewTy << OldTy 16646 << New->getReturnTypeSourceRange(); 16647 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16648 << Old->getReturnTypeSourceRange(); 16649 return true; 16650 } 16651 16652 return false; 16653 } 16654 16655 /// Mark the given method pure. 16656 /// 16657 /// \param Method the method to be marked pure. 16658 /// 16659 /// \param InitRange the source range that covers the "0" initializer. 16660 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 16661 SourceLocation EndLoc = InitRange.getEnd(); 16662 if (EndLoc.isValid()) 16663 Method->setRangeEnd(EndLoc); 16664 16665 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 16666 Method->setPure(); 16667 return false; 16668 } 16669 16670 if (!Method->isInvalidDecl()) 16671 Diag(Method->getLocation(), diag::err_non_virtual_pure) 16672 << Method->getDeclName() << InitRange; 16673 return true; 16674 } 16675 16676 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 16677 if (D->getFriendObjectKind()) 16678 Diag(D->getLocation(), diag::err_pure_friend); 16679 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 16680 CheckPureMethod(M, ZeroLoc); 16681 else 16682 Diag(D->getLocation(), diag::err_illegal_initializer); 16683 } 16684 16685 /// Determine whether the given declaration is a global variable or 16686 /// static data member. 16687 static bool isNonlocalVariable(const Decl *D) { 16688 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 16689 return Var->hasGlobalStorage(); 16690 16691 return false; 16692 } 16693 16694 /// Invoked when we are about to parse an initializer for the declaration 16695 /// 'Dcl'. 16696 /// 16697 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 16698 /// static data member of class X, names should be looked up in the scope of 16699 /// class X. If the declaration had a scope specifier, a scope will have 16700 /// been created and passed in for this purpose. Otherwise, S will be null. 16701 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 16702 // If there is no declaration, there was an error parsing it. 16703 if (!D || D->isInvalidDecl()) 16704 return; 16705 16706 // We will always have a nested name specifier here, but this declaration 16707 // might not be out of line if the specifier names the current namespace: 16708 // extern int n; 16709 // int ::n = 0; 16710 if (S && D->isOutOfLine()) 16711 EnterDeclaratorContext(S, D->getDeclContext()); 16712 16713 // If we are parsing the initializer for a static data member, push a 16714 // new expression evaluation context that is associated with this static 16715 // data member. 16716 if (isNonlocalVariable(D)) 16717 PushExpressionEvaluationContext( 16718 ExpressionEvaluationContext::PotentiallyEvaluated, D); 16719 } 16720 16721 /// Invoked after we are finished parsing an initializer for the declaration D. 16722 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 16723 // If there is no declaration, there was an error parsing it. 16724 if (!D || D->isInvalidDecl()) 16725 return; 16726 16727 if (isNonlocalVariable(D)) 16728 PopExpressionEvaluationContext(); 16729 16730 if (S && D->isOutOfLine()) 16731 ExitDeclaratorContext(S); 16732 } 16733 16734 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 16735 /// C++ if/switch/while/for statement. 16736 /// e.g: "if (int x = f()) {...}" 16737 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 16738 // C++ 6.4p2: 16739 // The declarator shall not specify a function or an array. 16740 // The type-specifier-seq shall not contain typedef and shall not declare a 16741 // new class or enumeration. 16742 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 16743 "Parser allowed 'typedef' as storage class of condition decl."); 16744 16745 Decl *Dcl = ActOnDeclarator(S, D); 16746 if (!Dcl) 16747 return true; 16748 16749 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 16750 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 16751 << D.getSourceRange(); 16752 return true; 16753 } 16754 16755 return Dcl; 16756 } 16757 16758 void Sema::LoadExternalVTableUses() { 16759 if (!ExternalSource) 16760 return; 16761 16762 SmallVector<ExternalVTableUse, 4> VTables; 16763 ExternalSource->ReadUsedVTables(VTables); 16764 SmallVector<VTableUse, 4> NewUses; 16765 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 16766 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 16767 = VTablesUsed.find(VTables[I].Record); 16768 // Even if a definition wasn't required before, it may be required now. 16769 if (Pos != VTablesUsed.end()) { 16770 if (!Pos->second && VTables[I].DefinitionRequired) 16771 Pos->second = true; 16772 continue; 16773 } 16774 16775 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 16776 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 16777 } 16778 16779 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 16780 } 16781 16782 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 16783 bool DefinitionRequired) { 16784 // Ignore any vtable uses in unevaluated operands or for classes that do 16785 // not have a vtable. 16786 if (!Class->isDynamicClass() || Class->isDependentContext() || 16787 CurContext->isDependentContext() || isUnevaluatedContext()) 16788 return; 16789 // Do not mark as used if compiling for the device outside of the target 16790 // region. 16791 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 16792 !isInOpenMPDeclareTargetContext() && 16793 !isInOpenMPTargetExecutionDirective()) { 16794 if (!DefinitionRequired) 16795 MarkVirtualMembersReferenced(Loc, Class); 16796 return; 16797 } 16798 16799 // Try to insert this class into the map. 16800 LoadExternalVTableUses(); 16801 Class = Class->getCanonicalDecl(); 16802 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 16803 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 16804 if (!Pos.second) { 16805 // If we already had an entry, check to see if we are promoting this vtable 16806 // to require a definition. If so, we need to reappend to the VTableUses 16807 // list, since we may have already processed the first entry. 16808 if (DefinitionRequired && !Pos.first->second) { 16809 Pos.first->second = true; 16810 } else { 16811 // Otherwise, we can early exit. 16812 return; 16813 } 16814 } else { 16815 // The Microsoft ABI requires that we perform the destructor body 16816 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 16817 // the deleting destructor is emitted with the vtable, not with the 16818 // destructor definition as in the Itanium ABI. 16819 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16820 CXXDestructorDecl *DD = Class->getDestructor(); 16821 if (DD && DD->isVirtual() && !DD->isDeleted()) { 16822 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 16823 // If this is an out-of-line declaration, marking it referenced will 16824 // not do anything. Manually call CheckDestructor to look up operator 16825 // delete(). 16826 ContextRAII SavedContext(*this, DD); 16827 CheckDestructor(DD); 16828 } else { 16829 MarkFunctionReferenced(Loc, Class->getDestructor()); 16830 } 16831 } 16832 } 16833 } 16834 16835 // Local classes need to have their virtual members marked 16836 // immediately. For all other classes, we mark their virtual members 16837 // at the end of the translation unit. 16838 if (Class->isLocalClass()) 16839 MarkVirtualMembersReferenced(Loc, Class); 16840 else 16841 VTableUses.push_back(std::make_pair(Class, Loc)); 16842 } 16843 16844 bool Sema::DefineUsedVTables() { 16845 LoadExternalVTableUses(); 16846 if (VTableUses.empty()) 16847 return false; 16848 16849 // Note: The VTableUses vector could grow as a result of marking 16850 // the members of a class as "used", so we check the size each 16851 // time through the loop and prefer indices (which are stable) to 16852 // iterators (which are not). 16853 bool DefinedAnything = false; 16854 for (unsigned I = 0; I != VTableUses.size(); ++I) { 16855 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 16856 if (!Class) 16857 continue; 16858 TemplateSpecializationKind ClassTSK = 16859 Class->getTemplateSpecializationKind(); 16860 16861 SourceLocation Loc = VTableUses[I].second; 16862 16863 bool DefineVTable = true; 16864 16865 // If this class has a key function, but that key function is 16866 // defined in another translation unit, we don't need to emit the 16867 // vtable even though we're using it. 16868 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 16869 if (KeyFunction && !KeyFunction->hasBody()) { 16870 // The key function is in another translation unit. 16871 DefineVTable = false; 16872 TemplateSpecializationKind TSK = 16873 KeyFunction->getTemplateSpecializationKind(); 16874 assert(TSK != TSK_ExplicitInstantiationDefinition && 16875 TSK != TSK_ImplicitInstantiation && 16876 "Instantiations don't have key functions"); 16877 (void)TSK; 16878 } else if (!KeyFunction) { 16879 // If we have a class with no key function that is the subject 16880 // of an explicit instantiation declaration, suppress the 16881 // vtable; it will live with the explicit instantiation 16882 // definition. 16883 bool IsExplicitInstantiationDeclaration = 16884 ClassTSK == TSK_ExplicitInstantiationDeclaration; 16885 for (auto R : Class->redecls()) { 16886 TemplateSpecializationKind TSK 16887 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 16888 if (TSK == TSK_ExplicitInstantiationDeclaration) 16889 IsExplicitInstantiationDeclaration = true; 16890 else if (TSK == TSK_ExplicitInstantiationDefinition) { 16891 IsExplicitInstantiationDeclaration = false; 16892 break; 16893 } 16894 } 16895 16896 if (IsExplicitInstantiationDeclaration) 16897 DefineVTable = false; 16898 } 16899 16900 // The exception specifications for all virtual members may be needed even 16901 // if we are not providing an authoritative form of the vtable in this TU. 16902 // We may choose to emit it available_externally anyway. 16903 if (!DefineVTable) { 16904 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 16905 continue; 16906 } 16907 16908 // Mark all of the virtual members of this class as referenced, so 16909 // that we can build a vtable. Then, tell the AST consumer that a 16910 // vtable for this class is required. 16911 DefinedAnything = true; 16912 MarkVirtualMembersReferenced(Loc, Class); 16913 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 16914 if (VTablesUsed[Canonical]) 16915 Consumer.HandleVTable(Class); 16916 16917 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 16918 // no key function or the key function is inlined. Don't warn in C++ ABIs 16919 // that lack key functions, since the user won't be able to make one. 16920 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 16921 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 16922 const FunctionDecl *KeyFunctionDef = nullptr; 16923 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 16924 KeyFunctionDef->isInlined())) { 16925 Diag(Class->getLocation(), 16926 ClassTSK == TSK_ExplicitInstantiationDefinition 16927 ? diag::warn_weak_template_vtable 16928 : diag::warn_weak_vtable) 16929 << Class; 16930 } 16931 } 16932 } 16933 VTableUses.clear(); 16934 16935 return DefinedAnything; 16936 } 16937 16938 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 16939 const CXXRecordDecl *RD) { 16940 for (const auto *I : RD->methods()) 16941 if (I->isVirtual() && !I->isPure()) 16942 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 16943 } 16944 16945 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 16946 const CXXRecordDecl *RD, 16947 bool ConstexprOnly) { 16948 // Mark all functions which will appear in RD's vtable as used. 16949 CXXFinalOverriderMap FinalOverriders; 16950 RD->getFinalOverriders(FinalOverriders); 16951 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 16952 E = FinalOverriders.end(); 16953 I != E; ++I) { 16954 for (OverridingMethods::const_iterator OI = I->second.begin(), 16955 OE = I->second.end(); 16956 OI != OE; ++OI) { 16957 assert(OI->second.size() > 0 && "no final overrider"); 16958 CXXMethodDecl *Overrider = OI->second.front().Method; 16959 16960 // C++ [basic.def.odr]p2: 16961 // [...] A virtual member function is used if it is not pure. [...] 16962 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 16963 MarkFunctionReferenced(Loc, Overrider); 16964 } 16965 } 16966 16967 // Only classes that have virtual bases need a VTT. 16968 if (RD->getNumVBases() == 0) 16969 return; 16970 16971 for (const auto &I : RD->bases()) { 16972 const auto *Base = 16973 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 16974 if (Base->getNumVBases() == 0) 16975 continue; 16976 MarkVirtualMembersReferenced(Loc, Base); 16977 } 16978 } 16979 16980 /// SetIvarInitializers - This routine builds initialization ASTs for the 16981 /// Objective-C implementation whose ivars need be initialized. 16982 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 16983 if (!getLangOpts().CPlusPlus) 16984 return; 16985 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 16986 SmallVector<ObjCIvarDecl*, 8> ivars; 16987 CollectIvarsToConstructOrDestruct(OID, ivars); 16988 if (ivars.empty()) 16989 return; 16990 SmallVector<CXXCtorInitializer*, 32> AllToInit; 16991 for (unsigned i = 0; i < ivars.size(); i++) { 16992 FieldDecl *Field = ivars[i]; 16993 if (Field->isInvalidDecl()) 16994 continue; 16995 16996 CXXCtorInitializer *Member; 16997 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 16998 InitializationKind InitKind = 16999 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17000 17001 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17002 ExprResult MemberInit = 17003 InitSeq.Perform(*this, InitEntity, InitKind, None); 17004 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17005 // Note, MemberInit could actually come back empty if no initialization 17006 // is required (e.g., because it would call a trivial default constructor) 17007 if (!MemberInit.get() || MemberInit.isInvalid()) 17008 continue; 17009 17010 Member = 17011 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17012 SourceLocation(), 17013 MemberInit.getAs<Expr>(), 17014 SourceLocation()); 17015 AllToInit.push_back(Member); 17016 17017 // Be sure that the destructor is accessible and is marked as referenced. 17018 if (const RecordType *RecordTy = 17019 Context.getBaseElementType(Field->getType()) 17020 ->getAs<RecordType>()) { 17021 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17022 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17023 MarkFunctionReferenced(Field->getLocation(), Destructor); 17024 CheckDestructorAccess(Field->getLocation(), Destructor, 17025 PDiag(diag::err_access_dtor_ivar) 17026 << Context.getBaseElementType(Field->getType())); 17027 } 17028 } 17029 } 17030 ObjCImplementation->setIvarInitializers(Context, 17031 AllToInit.data(), AllToInit.size()); 17032 } 17033 } 17034 17035 static 17036 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17037 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17038 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17039 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17040 Sema &S) { 17041 if (Ctor->isInvalidDecl()) 17042 return; 17043 17044 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17045 17046 // Target may not be determinable yet, for instance if this is a dependent 17047 // call in an uninstantiated template. 17048 if (Target) { 17049 const FunctionDecl *FNTarget = nullptr; 17050 (void)Target->hasBody(FNTarget); 17051 Target = const_cast<CXXConstructorDecl*>( 17052 cast_or_null<CXXConstructorDecl>(FNTarget)); 17053 } 17054 17055 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17056 // Avoid dereferencing a null pointer here. 17057 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17058 17059 if (!Current.insert(Canonical).second) 17060 return; 17061 17062 // We know that beyond here, we aren't chaining into a cycle. 17063 if (!Target || !Target->isDelegatingConstructor() || 17064 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17065 Valid.insert(Current.begin(), Current.end()); 17066 Current.clear(); 17067 // We've hit a cycle. 17068 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17069 Current.count(TCanonical)) { 17070 // If we haven't diagnosed this cycle yet, do so now. 17071 if (!Invalid.count(TCanonical)) { 17072 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17073 diag::warn_delegating_ctor_cycle) 17074 << Ctor; 17075 17076 // Don't add a note for a function delegating directly to itself. 17077 if (TCanonical != Canonical) 17078 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17079 17080 CXXConstructorDecl *C = Target; 17081 while (C->getCanonicalDecl() != Canonical) { 17082 const FunctionDecl *FNTarget = nullptr; 17083 (void)C->getTargetConstructor()->hasBody(FNTarget); 17084 assert(FNTarget && "Ctor cycle through bodiless function"); 17085 17086 C = const_cast<CXXConstructorDecl*>( 17087 cast<CXXConstructorDecl>(FNTarget)); 17088 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17089 } 17090 } 17091 17092 Invalid.insert(Current.begin(), Current.end()); 17093 Current.clear(); 17094 } else { 17095 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17096 } 17097 } 17098 17099 17100 void Sema::CheckDelegatingCtorCycles() { 17101 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17102 17103 for (DelegatingCtorDeclsType::iterator 17104 I = DelegatingCtorDecls.begin(ExternalSource), 17105 E = DelegatingCtorDecls.end(); 17106 I != E; ++I) 17107 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17108 17109 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17110 (*CI)->setInvalidDecl(); 17111 } 17112 17113 namespace { 17114 /// AST visitor that finds references to the 'this' expression. 17115 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17116 Sema &S; 17117 17118 public: 17119 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17120 17121 bool VisitCXXThisExpr(CXXThisExpr *E) { 17122 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17123 << E->isImplicit(); 17124 return false; 17125 } 17126 }; 17127 } 17128 17129 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17130 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17131 if (!TSInfo) 17132 return false; 17133 17134 TypeLoc TL = TSInfo->getTypeLoc(); 17135 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17136 if (!ProtoTL) 17137 return false; 17138 17139 // C++11 [expr.prim.general]p3: 17140 // [The expression this] shall not appear before the optional 17141 // cv-qualifier-seq and it shall not appear within the declaration of a 17142 // static member function (although its type and value category are defined 17143 // within a static member function as they are within a non-static member 17144 // function). [ Note: this is because declaration matching does not occur 17145 // until the complete declarator is known. - end note ] 17146 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17147 FindCXXThisExpr Finder(*this); 17148 17149 // If the return type came after the cv-qualifier-seq, check it now. 17150 if (Proto->hasTrailingReturn() && 17151 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17152 return true; 17153 17154 // Check the exception specification. 17155 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17156 return true; 17157 17158 // Check the trailing requires clause 17159 if (Expr *E = Method->getTrailingRequiresClause()) 17160 if (!Finder.TraverseStmt(E)) 17161 return true; 17162 17163 return checkThisInStaticMemberFunctionAttributes(Method); 17164 } 17165 17166 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17167 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17168 if (!TSInfo) 17169 return false; 17170 17171 TypeLoc TL = TSInfo->getTypeLoc(); 17172 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17173 if (!ProtoTL) 17174 return false; 17175 17176 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17177 FindCXXThisExpr Finder(*this); 17178 17179 switch (Proto->getExceptionSpecType()) { 17180 case EST_Unparsed: 17181 case EST_Uninstantiated: 17182 case EST_Unevaluated: 17183 case EST_BasicNoexcept: 17184 case EST_NoThrow: 17185 case EST_DynamicNone: 17186 case EST_MSAny: 17187 case EST_None: 17188 break; 17189 17190 case EST_DependentNoexcept: 17191 case EST_NoexceptFalse: 17192 case EST_NoexceptTrue: 17193 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17194 return true; 17195 LLVM_FALLTHROUGH; 17196 17197 case EST_Dynamic: 17198 for (const auto &E : Proto->exceptions()) { 17199 if (!Finder.TraverseType(E)) 17200 return true; 17201 } 17202 break; 17203 } 17204 17205 return false; 17206 } 17207 17208 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17209 FindCXXThisExpr Finder(*this); 17210 17211 // Check attributes. 17212 for (const auto *A : Method->attrs()) { 17213 // FIXME: This should be emitted by tblgen. 17214 Expr *Arg = nullptr; 17215 ArrayRef<Expr *> Args; 17216 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17217 Arg = G->getArg(); 17218 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17219 Arg = G->getArg(); 17220 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17221 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17222 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17223 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17224 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17225 Arg = ETLF->getSuccessValue(); 17226 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17227 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17228 Arg = STLF->getSuccessValue(); 17229 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17230 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17231 Arg = LR->getArg(); 17232 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17233 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17234 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17235 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17236 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17237 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17238 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17239 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17240 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17241 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17242 17243 if (Arg && !Finder.TraverseStmt(Arg)) 17244 return true; 17245 17246 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17247 if (!Finder.TraverseStmt(Args[I])) 17248 return true; 17249 } 17250 } 17251 17252 return false; 17253 } 17254 17255 void Sema::checkExceptionSpecification( 17256 bool IsTopLevel, ExceptionSpecificationType EST, 17257 ArrayRef<ParsedType> DynamicExceptions, 17258 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17259 SmallVectorImpl<QualType> &Exceptions, 17260 FunctionProtoType::ExceptionSpecInfo &ESI) { 17261 Exceptions.clear(); 17262 ESI.Type = EST; 17263 if (EST == EST_Dynamic) { 17264 Exceptions.reserve(DynamicExceptions.size()); 17265 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17266 // FIXME: Preserve type source info. 17267 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17268 17269 if (IsTopLevel) { 17270 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17271 collectUnexpandedParameterPacks(ET, Unexpanded); 17272 if (!Unexpanded.empty()) { 17273 DiagnoseUnexpandedParameterPacks( 17274 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17275 Unexpanded); 17276 continue; 17277 } 17278 } 17279 17280 // Check that the type is valid for an exception spec, and 17281 // drop it if not. 17282 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17283 Exceptions.push_back(ET); 17284 } 17285 ESI.Exceptions = Exceptions; 17286 return; 17287 } 17288 17289 if (isComputedNoexcept(EST)) { 17290 assert((NoexceptExpr->isTypeDependent() || 17291 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17292 Context.BoolTy) && 17293 "Parser should have made sure that the expression is boolean"); 17294 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17295 ESI.Type = EST_BasicNoexcept; 17296 return; 17297 } 17298 17299 ESI.NoexceptExpr = NoexceptExpr; 17300 return; 17301 } 17302 } 17303 17304 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17305 ExceptionSpecificationType EST, 17306 SourceRange SpecificationRange, 17307 ArrayRef<ParsedType> DynamicExceptions, 17308 ArrayRef<SourceRange> DynamicExceptionRanges, 17309 Expr *NoexceptExpr) { 17310 if (!MethodD) 17311 return; 17312 17313 // Dig out the method we're referring to. 17314 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17315 MethodD = FunTmpl->getTemplatedDecl(); 17316 17317 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17318 if (!Method) 17319 return; 17320 17321 // Check the exception specification. 17322 llvm::SmallVector<QualType, 4> Exceptions; 17323 FunctionProtoType::ExceptionSpecInfo ESI; 17324 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17325 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17326 ESI); 17327 17328 // Update the exception specification on the function type. 17329 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17330 17331 if (Method->isStatic()) 17332 checkThisInStaticMemberFunctionExceptionSpec(Method); 17333 17334 if (Method->isVirtual()) { 17335 // Check overrides, which we previously had to delay. 17336 for (const CXXMethodDecl *O : Method->overridden_methods()) 17337 CheckOverridingFunctionExceptionSpec(Method, O); 17338 } 17339 } 17340 17341 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17342 /// 17343 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17344 SourceLocation DeclStart, Declarator &D, 17345 Expr *BitWidth, 17346 InClassInitStyle InitStyle, 17347 AccessSpecifier AS, 17348 const ParsedAttr &MSPropertyAttr) { 17349 IdentifierInfo *II = D.getIdentifier(); 17350 if (!II) { 17351 Diag(DeclStart, diag::err_anonymous_property); 17352 return nullptr; 17353 } 17354 SourceLocation Loc = D.getIdentifierLoc(); 17355 17356 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17357 QualType T = TInfo->getType(); 17358 if (getLangOpts().CPlusPlus) { 17359 CheckExtraCXXDefaultArguments(D); 17360 17361 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17362 UPPC_DataMemberType)) { 17363 D.setInvalidType(); 17364 T = Context.IntTy; 17365 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17366 } 17367 } 17368 17369 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17370 17371 if (D.getDeclSpec().isInlineSpecified()) 17372 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17373 << getLangOpts().CPlusPlus17; 17374 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17375 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17376 diag::err_invalid_thread) 17377 << DeclSpec::getSpecifierName(TSCS); 17378 17379 // Check to see if this name was declared as a member previously 17380 NamedDecl *PrevDecl = nullptr; 17381 LookupResult Previous(*this, II, Loc, LookupMemberName, 17382 ForVisibleRedeclaration); 17383 LookupName(Previous, S); 17384 switch (Previous.getResultKind()) { 17385 case LookupResult::Found: 17386 case LookupResult::FoundUnresolvedValue: 17387 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17388 break; 17389 17390 case LookupResult::FoundOverloaded: 17391 PrevDecl = Previous.getRepresentativeDecl(); 17392 break; 17393 17394 case LookupResult::NotFound: 17395 case LookupResult::NotFoundInCurrentInstantiation: 17396 case LookupResult::Ambiguous: 17397 break; 17398 } 17399 17400 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17401 // Maybe we will complain about the shadowed template parameter. 17402 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17403 // Just pretend that we didn't see the previous declaration. 17404 PrevDecl = nullptr; 17405 } 17406 17407 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17408 PrevDecl = nullptr; 17409 17410 SourceLocation TSSL = D.getBeginLoc(); 17411 MSPropertyDecl *NewPD = 17412 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17413 MSPropertyAttr.getPropertyDataGetter(), 17414 MSPropertyAttr.getPropertyDataSetter()); 17415 ProcessDeclAttributes(TUScope, NewPD, D); 17416 NewPD->setAccess(AS); 17417 17418 if (NewPD->isInvalidDecl()) 17419 Record->setInvalidDecl(); 17420 17421 if (D.getDeclSpec().isModulePrivateSpecified()) 17422 NewPD->setModulePrivate(); 17423 17424 if (NewPD->isInvalidDecl() && PrevDecl) { 17425 // Don't introduce NewFD into scope; there's already something 17426 // with the same name in the same scope. 17427 } else if (II) { 17428 PushOnScopeChains(NewPD, S); 17429 } else 17430 Record->addDecl(NewPD); 17431 17432 return NewPD; 17433 } 17434 17435 void Sema::ActOnStartFunctionDeclarationDeclarator( 17436 Declarator &Declarator, unsigned TemplateParameterDepth) { 17437 auto &Info = InventedParameterInfos.emplace_back(); 17438 TemplateParameterList *ExplicitParams = nullptr; 17439 ArrayRef<TemplateParameterList *> ExplicitLists = 17440 Declarator.getTemplateParameterLists(); 17441 if (!ExplicitLists.empty()) { 17442 bool IsMemberSpecialization, IsInvalid; 17443 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17444 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17445 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17446 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17447 /*SuppressDiagnostic=*/true); 17448 } 17449 if (ExplicitParams) { 17450 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17451 for (NamedDecl *Param : *ExplicitParams) 17452 Info.TemplateParams.push_back(Param); 17453 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17454 } else { 17455 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17456 Info.NumExplicitTemplateParams = 0; 17457 } 17458 } 17459 17460 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17461 auto &FSI = InventedParameterInfos.back(); 17462 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17463 if (FSI.NumExplicitTemplateParams != 0) { 17464 TemplateParameterList *ExplicitParams = 17465 Declarator.getTemplateParameterLists().back(); 17466 Declarator.setInventedTemplateParameterList( 17467 TemplateParameterList::Create( 17468 Context, ExplicitParams->getTemplateLoc(), 17469 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17470 ExplicitParams->getRAngleLoc(), 17471 ExplicitParams->getRequiresClause())); 17472 } else { 17473 Declarator.setInventedTemplateParameterList( 17474 TemplateParameterList::Create( 17475 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17476 SourceLocation(), /*RequiresClause=*/nullptr)); 17477 } 17478 } 17479 InventedParameterInfos.pop_back(); 17480 } 17481