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 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->getAs<ReferenceType>()->getPointeeType(); 1505 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1506 NewType = P->getPointeeType(); 1507 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1508 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1509 NewType = M->getPointeeType(); 1510 OldType = OldType->getAs<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 FunctionProtoType *FT = FD->getType()->getAs<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); 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 /// This is invoked after parsing an in-class initializer for a 3872 /// non-static C++ class member, and after instantiating an in-class initializer 3873 /// in a class template. Such actions are deferred until the class is complete. 3874 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3875 SourceLocation InitLoc, 3876 Expr *InitExpr) { 3877 // Pop the notional constructor scope we created earlier. 3878 PopFunctionScopeInfo(nullptr, D); 3879 3880 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3881 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3882 "must set init style when field is created"); 3883 3884 if (!InitExpr) { 3885 D->setInvalidDecl(); 3886 if (FD) 3887 FD->removeInClassInitializer(); 3888 return; 3889 } 3890 3891 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3892 FD->setInvalidDecl(); 3893 FD->removeInClassInitializer(); 3894 return; 3895 } 3896 3897 ExprResult Init = InitExpr; 3898 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3899 InitializedEntity Entity = 3900 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3901 InitializationKind Kind = 3902 FD->getInClassInitStyle() == ICIS_ListInit 3903 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3904 InitExpr->getBeginLoc(), 3905 InitExpr->getEndLoc()) 3906 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3907 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3908 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3909 if (Init.isInvalid()) { 3910 FD->setInvalidDecl(); 3911 return; 3912 } 3913 } 3914 3915 // C++11 [class.base.init]p7: 3916 // The initialization of each base and member constitutes a 3917 // full-expression. 3918 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3919 if (Init.isInvalid()) { 3920 FD->setInvalidDecl(); 3921 return; 3922 } 3923 3924 InitExpr = Init.get(); 3925 3926 FD->setInClassInitializer(InitExpr); 3927 } 3928 3929 /// Find the direct and/or virtual base specifiers that 3930 /// correspond to the given base type, for use in base initialization 3931 /// within a constructor. 3932 static bool FindBaseInitializer(Sema &SemaRef, 3933 CXXRecordDecl *ClassDecl, 3934 QualType BaseType, 3935 const CXXBaseSpecifier *&DirectBaseSpec, 3936 const CXXBaseSpecifier *&VirtualBaseSpec) { 3937 // First, check for a direct base class. 3938 DirectBaseSpec = nullptr; 3939 for (const auto &Base : ClassDecl->bases()) { 3940 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3941 // We found a direct base of this type. That's what we're 3942 // initializing. 3943 DirectBaseSpec = &Base; 3944 break; 3945 } 3946 } 3947 3948 // Check for a virtual base class. 3949 // FIXME: We might be able to short-circuit this if we know in advance that 3950 // there are no virtual bases. 3951 VirtualBaseSpec = nullptr; 3952 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3953 // We haven't found a base yet; search the class hierarchy for a 3954 // virtual base class. 3955 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3956 /*DetectVirtual=*/false); 3957 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3958 SemaRef.Context.getTypeDeclType(ClassDecl), 3959 BaseType, Paths)) { 3960 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3961 Path != Paths.end(); ++Path) { 3962 if (Path->back().Base->isVirtual()) { 3963 VirtualBaseSpec = Path->back().Base; 3964 break; 3965 } 3966 } 3967 } 3968 } 3969 3970 return DirectBaseSpec || VirtualBaseSpec; 3971 } 3972 3973 /// Handle a C++ member initializer using braced-init-list syntax. 3974 MemInitResult 3975 Sema::ActOnMemInitializer(Decl *ConstructorD, 3976 Scope *S, 3977 CXXScopeSpec &SS, 3978 IdentifierInfo *MemberOrBase, 3979 ParsedType TemplateTypeTy, 3980 const DeclSpec &DS, 3981 SourceLocation IdLoc, 3982 Expr *InitList, 3983 SourceLocation EllipsisLoc) { 3984 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3985 DS, IdLoc, InitList, 3986 EllipsisLoc); 3987 } 3988 3989 /// Handle a C++ member initializer using parentheses syntax. 3990 MemInitResult 3991 Sema::ActOnMemInitializer(Decl *ConstructorD, 3992 Scope *S, 3993 CXXScopeSpec &SS, 3994 IdentifierInfo *MemberOrBase, 3995 ParsedType TemplateTypeTy, 3996 const DeclSpec &DS, 3997 SourceLocation IdLoc, 3998 SourceLocation LParenLoc, 3999 ArrayRef<Expr *> Args, 4000 SourceLocation RParenLoc, 4001 SourceLocation EllipsisLoc) { 4002 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4003 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4004 DS, IdLoc, List, EllipsisLoc); 4005 } 4006 4007 namespace { 4008 4009 // Callback to only accept typo corrections that can be a valid C++ member 4010 // intializer: either a non-static field member or a base class. 4011 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4012 public: 4013 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4014 : ClassDecl(ClassDecl) {} 4015 4016 bool ValidateCandidate(const TypoCorrection &candidate) override { 4017 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4018 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4019 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4020 return isa<TypeDecl>(ND); 4021 } 4022 return false; 4023 } 4024 4025 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4026 return std::make_unique<MemInitializerValidatorCCC>(*this); 4027 } 4028 4029 private: 4030 CXXRecordDecl *ClassDecl; 4031 }; 4032 4033 } 4034 4035 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4036 CXXScopeSpec &SS, 4037 ParsedType TemplateTypeTy, 4038 IdentifierInfo *MemberOrBase) { 4039 if (SS.getScopeRep() || TemplateTypeTy) 4040 return nullptr; 4041 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4042 if (Result.empty()) 4043 return nullptr; 4044 ValueDecl *Member; 4045 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4046 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4047 return Member; 4048 return nullptr; 4049 } 4050 4051 /// Handle a C++ member initializer. 4052 MemInitResult 4053 Sema::BuildMemInitializer(Decl *ConstructorD, 4054 Scope *S, 4055 CXXScopeSpec &SS, 4056 IdentifierInfo *MemberOrBase, 4057 ParsedType TemplateTypeTy, 4058 const DeclSpec &DS, 4059 SourceLocation IdLoc, 4060 Expr *Init, 4061 SourceLocation EllipsisLoc) { 4062 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4063 if (!Res.isUsable()) 4064 return true; 4065 Init = Res.get(); 4066 4067 if (!ConstructorD) 4068 return true; 4069 4070 AdjustDeclIfTemplate(ConstructorD); 4071 4072 CXXConstructorDecl *Constructor 4073 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4074 if (!Constructor) { 4075 // The user wrote a constructor initializer on a function that is 4076 // not a C++ constructor. Ignore the error for now, because we may 4077 // have more member initializers coming; we'll diagnose it just 4078 // once in ActOnMemInitializers. 4079 return true; 4080 } 4081 4082 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4083 4084 // C++ [class.base.init]p2: 4085 // Names in a mem-initializer-id are looked up in the scope of the 4086 // constructor's class and, if not found in that scope, are looked 4087 // up in the scope containing the constructor's definition. 4088 // [Note: if the constructor's class contains a member with the 4089 // same name as a direct or virtual base class of the class, a 4090 // mem-initializer-id naming the member or base class and composed 4091 // of a single identifier refers to the class member. A 4092 // mem-initializer-id for the hidden base class may be specified 4093 // using a qualified name. ] 4094 4095 // Look for a member, first. 4096 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4097 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4098 if (EllipsisLoc.isValid()) 4099 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4100 << MemberOrBase 4101 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4102 4103 return BuildMemberInitializer(Member, Init, IdLoc); 4104 } 4105 // It didn't name a member, so see if it names a class. 4106 QualType BaseType; 4107 TypeSourceInfo *TInfo = nullptr; 4108 4109 if (TemplateTypeTy) { 4110 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4111 if (BaseType.isNull()) 4112 return true; 4113 } else if (DS.getTypeSpecType() == TST_decltype) { 4114 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4115 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4116 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4117 return true; 4118 } else { 4119 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4120 LookupParsedName(R, S, &SS); 4121 4122 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4123 if (!TyD) { 4124 if (R.isAmbiguous()) return true; 4125 4126 // We don't want access-control diagnostics here. 4127 R.suppressDiagnostics(); 4128 4129 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4130 bool NotUnknownSpecialization = false; 4131 DeclContext *DC = computeDeclContext(SS, false); 4132 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4133 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4134 4135 if (!NotUnknownSpecialization) { 4136 // When the scope specifier can refer to a member of an unknown 4137 // specialization, we take it as a type name. 4138 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4139 SS.getWithLocInContext(Context), 4140 *MemberOrBase, IdLoc); 4141 if (BaseType.isNull()) 4142 return true; 4143 4144 TInfo = Context.CreateTypeSourceInfo(BaseType); 4145 DependentNameTypeLoc TL = 4146 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4147 if (!TL.isNull()) { 4148 TL.setNameLoc(IdLoc); 4149 TL.setElaboratedKeywordLoc(SourceLocation()); 4150 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4151 } 4152 4153 R.clear(); 4154 R.setLookupName(MemberOrBase); 4155 } 4156 } 4157 4158 // If no results were found, try to correct typos. 4159 TypoCorrection Corr; 4160 MemInitializerValidatorCCC CCC(ClassDecl); 4161 if (R.empty() && BaseType.isNull() && 4162 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4163 CCC, CTK_ErrorRecovery, ClassDecl))) { 4164 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4165 // We have found a non-static data member with a similar 4166 // name to what was typed; complain and initialize that 4167 // member. 4168 diagnoseTypo(Corr, 4169 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4170 << MemberOrBase << true); 4171 return BuildMemberInitializer(Member, Init, IdLoc); 4172 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4173 const CXXBaseSpecifier *DirectBaseSpec; 4174 const CXXBaseSpecifier *VirtualBaseSpec; 4175 if (FindBaseInitializer(*this, ClassDecl, 4176 Context.getTypeDeclType(Type), 4177 DirectBaseSpec, VirtualBaseSpec)) { 4178 // We have found a direct or virtual base class with a 4179 // similar name to what was typed; complain and initialize 4180 // that base class. 4181 diagnoseTypo(Corr, 4182 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4183 << MemberOrBase << false, 4184 PDiag() /*Suppress note, we provide our own.*/); 4185 4186 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4187 : VirtualBaseSpec; 4188 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4189 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4190 4191 TyD = Type; 4192 } 4193 } 4194 } 4195 4196 if (!TyD && BaseType.isNull()) { 4197 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4198 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4199 return true; 4200 } 4201 } 4202 4203 if (BaseType.isNull()) { 4204 BaseType = Context.getTypeDeclType(TyD); 4205 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4206 if (SS.isSet()) { 4207 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4208 BaseType); 4209 TInfo = Context.CreateTypeSourceInfo(BaseType); 4210 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4211 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4212 TL.setElaboratedKeywordLoc(SourceLocation()); 4213 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4214 } 4215 } 4216 } 4217 4218 if (!TInfo) 4219 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4220 4221 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4222 } 4223 4224 MemInitResult 4225 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4226 SourceLocation IdLoc) { 4227 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4228 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4229 assert((DirectMember || IndirectMember) && 4230 "Member must be a FieldDecl or IndirectFieldDecl"); 4231 4232 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4233 return true; 4234 4235 if (Member->isInvalidDecl()) 4236 return true; 4237 4238 MultiExprArg Args; 4239 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4240 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4241 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4242 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4243 } else { 4244 // Template instantiation doesn't reconstruct ParenListExprs for us. 4245 Args = Init; 4246 } 4247 4248 SourceRange InitRange = Init->getSourceRange(); 4249 4250 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4251 // Can't check initialization for a member of dependent type or when 4252 // any of the arguments are type-dependent expressions. 4253 DiscardCleanupsInEvaluationContext(); 4254 } else { 4255 bool InitList = false; 4256 if (isa<InitListExpr>(Init)) { 4257 InitList = true; 4258 Args = Init; 4259 } 4260 4261 // Initialize the member. 4262 InitializedEntity MemberEntity = 4263 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4264 : InitializedEntity::InitializeMember(IndirectMember, 4265 nullptr); 4266 InitializationKind Kind = 4267 InitList ? InitializationKind::CreateDirectList( 4268 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4269 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4270 InitRange.getEnd()); 4271 4272 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4273 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4274 nullptr); 4275 if (MemberInit.isInvalid()) 4276 return true; 4277 4278 // C++11 [class.base.init]p7: 4279 // The initialization of each base and member constitutes a 4280 // full-expression. 4281 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4282 /*DiscardedValue*/ false); 4283 if (MemberInit.isInvalid()) 4284 return true; 4285 4286 Init = MemberInit.get(); 4287 } 4288 4289 if (DirectMember) { 4290 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4291 InitRange.getBegin(), Init, 4292 InitRange.getEnd()); 4293 } else { 4294 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4295 InitRange.getBegin(), Init, 4296 InitRange.getEnd()); 4297 } 4298 } 4299 4300 MemInitResult 4301 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4302 CXXRecordDecl *ClassDecl) { 4303 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4304 if (!LangOpts.CPlusPlus11) 4305 return Diag(NameLoc, diag::err_delegating_ctor) 4306 << TInfo->getTypeLoc().getLocalSourceRange(); 4307 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4308 4309 bool InitList = true; 4310 MultiExprArg Args = Init; 4311 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4312 InitList = false; 4313 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4314 } 4315 4316 SourceRange InitRange = Init->getSourceRange(); 4317 // Initialize the object. 4318 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4319 QualType(ClassDecl->getTypeForDecl(), 0)); 4320 InitializationKind Kind = 4321 InitList ? InitializationKind::CreateDirectList( 4322 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4323 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4324 InitRange.getEnd()); 4325 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4326 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4327 Args, nullptr); 4328 if (DelegationInit.isInvalid()) 4329 return true; 4330 4331 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4332 "Delegating constructor with no target?"); 4333 4334 // C++11 [class.base.init]p7: 4335 // The initialization of each base and member constitutes a 4336 // full-expression. 4337 DelegationInit = ActOnFinishFullExpr( 4338 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4339 if (DelegationInit.isInvalid()) 4340 return true; 4341 4342 // If we are in a dependent context, template instantiation will 4343 // perform this type-checking again. Just save the arguments that we 4344 // received in a ParenListExpr. 4345 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4346 // of the information that we have about the base 4347 // initializer. However, deconstructing the ASTs is a dicey process, 4348 // and this approach is far more likely to get the corner cases right. 4349 if (CurContext->isDependentContext()) 4350 DelegationInit = Init; 4351 4352 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4353 DelegationInit.getAs<Expr>(), 4354 InitRange.getEnd()); 4355 } 4356 4357 MemInitResult 4358 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4359 Expr *Init, CXXRecordDecl *ClassDecl, 4360 SourceLocation EllipsisLoc) { 4361 SourceLocation BaseLoc 4362 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4363 4364 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4365 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4366 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4367 4368 // C++ [class.base.init]p2: 4369 // [...] Unless the mem-initializer-id names a nonstatic data 4370 // member of the constructor's class or a direct or virtual base 4371 // of that class, the mem-initializer is ill-formed. A 4372 // mem-initializer-list can initialize a base class using any 4373 // name that denotes that base class type. 4374 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4375 4376 SourceRange InitRange = Init->getSourceRange(); 4377 if (EllipsisLoc.isValid()) { 4378 // This is a pack expansion. 4379 if (!BaseType->containsUnexpandedParameterPack()) { 4380 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4381 << SourceRange(BaseLoc, InitRange.getEnd()); 4382 4383 EllipsisLoc = SourceLocation(); 4384 } 4385 } else { 4386 // Check for any unexpanded parameter packs. 4387 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4388 return true; 4389 4390 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4391 return true; 4392 } 4393 4394 // Check for direct and virtual base classes. 4395 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4396 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4397 if (!Dependent) { 4398 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4399 BaseType)) 4400 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4401 4402 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4403 VirtualBaseSpec); 4404 4405 // C++ [base.class.init]p2: 4406 // Unless the mem-initializer-id names a nonstatic data member of the 4407 // constructor's class or a direct or virtual base of that class, the 4408 // mem-initializer is ill-formed. 4409 if (!DirectBaseSpec && !VirtualBaseSpec) { 4410 // If the class has any dependent bases, then it's possible that 4411 // one of those types will resolve to the same type as 4412 // BaseType. Therefore, just treat this as a dependent base 4413 // class initialization. FIXME: Should we try to check the 4414 // initialization anyway? It seems odd. 4415 if (ClassDecl->hasAnyDependentBases()) 4416 Dependent = true; 4417 else 4418 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4419 << BaseType << Context.getTypeDeclType(ClassDecl) 4420 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4421 } 4422 } 4423 4424 if (Dependent) { 4425 DiscardCleanupsInEvaluationContext(); 4426 4427 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4428 /*IsVirtual=*/false, 4429 InitRange.getBegin(), Init, 4430 InitRange.getEnd(), EllipsisLoc); 4431 } 4432 4433 // C++ [base.class.init]p2: 4434 // If a mem-initializer-id is ambiguous because it designates both 4435 // a direct non-virtual base class and an inherited virtual base 4436 // class, the mem-initializer is ill-formed. 4437 if (DirectBaseSpec && VirtualBaseSpec) 4438 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4439 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4440 4441 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4442 if (!BaseSpec) 4443 BaseSpec = VirtualBaseSpec; 4444 4445 // Initialize the base. 4446 bool InitList = true; 4447 MultiExprArg Args = Init; 4448 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4449 InitList = false; 4450 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4451 } 4452 4453 InitializedEntity BaseEntity = 4454 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4455 InitializationKind Kind = 4456 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4457 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4458 InitRange.getEnd()); 4459 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4460 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4461 if (BaseInit.isInvalid()) 4462 return true; 4463 4464 // C++11 [class.base.init]p7: 4465 // The initialization of each base and member constitutes a 4466 // full-expression. 4467 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4468 /*DiscardedValue*/ false); 4469 if (BaseInit.isInvalid()) 4470 return true; 4471 4472 // If we are in a dependent context, template instantiation will 4473 // perform this type-checking again. Just save the arguments that we 4474 // received in a ParenListExpr. 4475 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4476 // of the information that we have about the base 4477 // initializer. However, deconstructing the ASTs is a dicey process, 4478 // and this approach is far more likely to get the corner cases right. 4479 if (CurContext->isDependentContext()) 4480 BaseInit = Init; 4481 4482 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4483 BaseSpec->isVirtual(), 4484 InitRange.getBegin(), 4485 BaseInit.getAs<Expr>(), 4486 InitRange.getEnd(), EllipsisLoc); 4487 } 4488 4489 // Create a static_cast\<T&&>(expr). 4490 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4491 if (T.isNull()) T = E->getType(); 4492 QualType TargetType = SemaRef.BuildReferenceType( 4493 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4494 SourceLocation ExprLoc = E->getBeginLoc(); 4495 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4496 TargetType, ExprLoc); 4497 4498 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4499 SourceRange(ExprLoc, ExprLoc), 4500 E->getSourceRange()).get(); 4501 } 4502 4503 /// ImplicitInitializerKind - How an implicit base or member initializer should 4504 /// initialize its base or member. 4505 enum ImplicitInitializerKind { 4506 IIK_Default, 4507 IIK_Copy, 4508 IIK_Move, 4509 IIK_Inherit 4510 }; 4511 4512 static bool 4513 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4514 ImplicitInitializerKind ImplicitInitKind, 4515 CXXBaseSpecifier *BaseSpec, 4516 bool IsInheritedVirtualBase, 4517 CXXCtorInitializer *&CXXBaseInit) { 4518 InitializedEntity InitEntity 4519 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4520 IsInheritedVirtualBase); 4521 4522 ExprResult BaseInit; 4523 4524 switch (ImplicitInitKind) { 4525 case IIK_Inherit: 4526 case IIK_Default: { 4527 InitializationKind InitKind 4528 = InitializationKind::CreateDefault(Constructor->getLocation()); 4529 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4530 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4531 break; 4532 } 4533 4534 case IIK_Move: 4535 case IIK_Copy: { 4536 bool Moving = ImplicitInitKind == IIK_Move; 4537 ParmVarDecl *Param = Constructor->getParamDecl(0); 4538 QualType ParamType = Param->getType().getNonReferenceType(); 4539 4540 Expr *CopyCtorArg = 4541 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4542 SourceLocation(), Param, false, 4543 Constructor->getLocation(), ParamType, 4544 VK_LValue, nullptr); 4545 4546 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4547 4548 // Cast to the base class to avoid ambiguities. 4549 QualType ArgTy = 4550 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4551 ParamType.getQualifiers()); 4552 4553 if (Moving) { 4554 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4555 } 4556 4557 CXXCastPath BasePath; 4558 BasePath.push_back(BaseSpec); 4559 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4560 CK_UncheckedDerivedToBase, 4561 Moving ? VK_XValue : VK_LValue, 4562 &BasePath).get(); 4563 4564 InitializationKind InitKind 4565 = InitializationKind::CreateDirect(Constructor->getLocation(), 4566 SourceLocation(), SourceLocation()); 4567 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4568 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4569 break; 4570 } 4571 } 4572 4573 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4574 if (BaseInit.isInvalid()) 4575 return true; 4576 4577 CXXBaseInit = 4578 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4579 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4580 SourceLocation()), 4581 BaseSpec->isVirtual(), 4582 SourceLocation(), 4583 BaseInit.getAs<Expr>(), 4584 SourceLocation(), 4585 SourceLocation()); 4586 4587 return false; 4588 } 4589 4590 static bool RefersToRValueRef(Expr *MemRef) { 4591 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4592 return Referenced->getType()->isRValueReferenceType(); 4593 } 4594 4595 static bool 4596 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4597 ImplicitInitializerKind ImplicitInitKind, 4598 FieldDecl *Field, IndirectFieldDecl *Indirect, 4599 CXXCtorInitializer *&CXXMemberInit) { 4600 if (Field->isInvalidDecl()) 4601 return true; 4602 4603 SourceLocation Loc = Constructor->getLocation(); 4604 4605 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4606 bool Moving = ImplicitInitKind == IIK_Move; 4607 ParmVarDecl *Param = Constructor->getParamDecl(0); 4608 QualType ParamType = Param->getType().getNonReferenceType(); 4609 4610 // Suppress copying zero-width bitfields. 4611 if (Field->isZeroLengthBitField(SemaRef.Context)) 4612 return false; 4613 4614 Expr *MemberExprBase = 4615 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4616 SourceLocation(), Param, false, 4617 Loc, ParamType, VK_LValue, nullptr); 4618 4619 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4620 4621 if (Moving) { 4622 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4623 } 4624 4625 // Build a reference to this field within the parameter. 4626 CXXScopeSpec SS; 4627 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4628 Sema::LookupMemberName); 4629 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4630 : cast<ValueDecl>(Field), AS_public); 4631 MemberLookup.resolveKind(); 4632 ExprResult CtorArg 4633 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4634 ParamType, Loc, 4635 /*IsArrow=*/false, 4636 SS, 4637 /*TemplateKWLoc=*/SourceLocation(), 4638 /*FirstQualifierInScope=*/nullptr, 4639 MemberLookup, 4640 /*TemplateArgs=*/nullptr, 4641 /*S*/nullptr); 4642 if (CtorArg.isInvalid()) 4643 return true; 4644 4645 // C++11 [class.copy]p15: 4646 // - if a member m has rvalue reference type T&&, it is direct-initialized 4647 // with static_cast<T&&>(x.m); 4648 if (RefersToRValueRef(CtorArg.get())) { 4649 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4650 } 4651 4652 InitializedEntity Entity = 4653 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4654 /*Implicit*/ true) 4655 : InitializedEntity::InitializeMember(Field, nullptr, 4656 /*Implicit*/ true); 4657 4658 // Direct-initialize to use the copy constructor. 4659 InitializationKind InitKind = 4660 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4661 4662 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4663 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4664 ExprResult MemberInit = 4665 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4666 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4667 if (MemberInit.isInvalid()) 4668 return true; 4669 4670 if (Indirect) 4671 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4672 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4673 else 4674 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4675 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4676 return false; 4677 } 4678 4679 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4680 "Unhandled implicit init kind!"); 4681 4682 QualType FieldBaseElementType = 4683 SemaRef.Context.getBaseElementType(Field->getType()); 4684 4685 if (FieldBaseElementType->isRecordType()) { 4686 InitializedEntity InitEntity = 4687 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4688 /*Implicit*/ true) 4689 : InitializedEntity::InitializeMember(Field, nullptr, 4690 /*Implicit*/ true); 4691 InitializationKind InitKind = 4692 InitializationKind::CreateDefault(Loc); 4693 4694 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4695 ExprResult MemberInit = 4696 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4697 4698 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4699 if (MemberInit.isInvalid()) 4700 return true; 4701 4702 if (Indirect) 4703 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4704 Indirect, Loc, 4705 Loc, 4706 MemberInit.get(), 4707 Loc); 4708 else 4709 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4710 Field, Loc, Loc, 4711 MemberInit.get(), 4712 Loc); 4713 return false; 4714 } 4715 4716 if (!Field->getParent()->isUnion()) { 4717 if (FieldBaseElementType->isReferenceType()) { 4718 SemaRef.Diag(Constructor->getLocation(), 4719 diag::err_uninitialized_member_in_ctor) 4720 << (int)Constructor->isImplicit() 4721 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4722 << 0 << Field->getDeclName(); 4723 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4724 return true; 4725 } 4726 4727 if (FieldBaseElementType.isConstQualified()) { 4728 SemaRef.Diag(Constructor->getLocation(), 4729 diag::err_uninitialized_member_in_ctor) 4730 << (int)Constructor->isImplicit() 4731 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4732 << 1 << Field->getDeclName(); 4733 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4734 return true; 4735 } 4736 } 4737 4738 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4739 // ARC and Weak: 4740 // Default-initialize Objective-C pointers to NULL. 4741 CXXMemberInit 4742 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4743 Loc, Loc, 4744 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4745 Loc); 4746 return false; 4747 } 4748 4749 // Nothing to initialize. 4750 CXXMemberInit = nullptr; 4751 return false; 4752 } 4753 4754 namespace { 4755 struct BaseAndFieldInfo { 4756 Sema &S; 4757 CXXConstructorDecl *Ctor; 4758 bool AnyErrorsInInits; 4759 ImplicitInitializerKind IIK; 4760 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4761 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4762 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4763 4764 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4765 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4766 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4767 if (Ctor->getInheritedConstructor()) 4768 IIK = IIK_Inherit; 4769 else if (Generated && Ctor->isCopyConstructor()) 4770 IIK = IIK_Copy; 4771 else if (Generated && Ctor->isMoveConstructor()) 4772 IIK = IIK_Move; 4773 else 4774 IIK = IIK_Default; 4775 } 4776 4777 bool isImplicitCopyOrMove() const { 4778 switch (IIK) { 4779 case IIK_Copy: 4780 case IIK_Move: 4781 return true; 4782 4783 case IIK_Default: 4784 case IIK_Inherit: 4785 return false; 4786 } 4787 4788 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4789 } 4790 4791 bool addFieldInitializer(CXXCtorInitializer *Init) { 4792 AllToInit.push_back(Init); 4793 4794 // Check whether this initializer makes the field "used". 4795 if (Init->getInit()->HasSideEffects(S.Context)) 4796 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4797 4798 return false; 4799 } 4800 4801 bool isInactiveUnionMember(FieldDecl *Field) { 4802 RecordDecl *Record = Field->getParent(); 4803 if (!Record->isUnion()) 4804 return false; 4805 4806 if (FieldDecl *Active = 4807 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4808 return Active != Field->getCanonicalDecl(); 4809 4810 // In an implicit copy or move constructor, ignore any in-class initializer. 4811 if (isImplicitCopyOrMove()) 4812 return true; 4813 4814 // If there's no explicit initialization, the field is active only if it 4815 // has an in-class initializer... 4816 if (Field->hasInClassInitializer()) 4817 return false; 4818 // ... or it's an anonymous struct or union whose class has an in-class 4819 // initializer. 4820 if (!Field->isAnonymousStructOrUnion()) 4821 return true; 4822 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4823 return !FieldRD->hasInClassInitializer(); 4824 } 4825 4826 /// Determine whether the given field is, or is within, a union member 4827 /// that is inactive (because there was an initializer given for a different 4828 /// member of the union, or because the union was not initialized at all). 4829 bool isWithinInactiveUnionMember(FieldDecl *Field, 4830 IndirectFieldDecl *Indirect) { 4831 if (!Indirect) 4832 return isInactiveUnionMember(Field); 4833 4834 for (auto *C : Indirect->chain()) { 4835 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4836 if (Field && isInactiveUnionMember(Field)) 4837 return true; 4838 } 4839 return false; 4840 } 4841 }; 4842 } 4843 4844 /// Determine whether the given type is an incomplete or zero-lenfgth 4845 /// array type. 4846 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4847 if (T->isIncompleteArrayType()) 4848 return true; 4849 4850 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4851 if (!ArrayT->getSize()) 4852 return true; 4853 4854 T = ArrayT->getElementType(); 4855 } 4856 4857 return false; 4858 } 4859 4860 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4861 FieldDecl *Field, 4862 IndirectFieldDecl *Indirect = nullptr) { 4863 if (Field->isInvalidDecl()) 4864 return false; 4865 4866 // Overwhelmingly common case: we have a direct initializer for this field. 4867 if (CXXCtorInitializer *Init = 4868 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4869 return Info.addFieldInitializer(Init); 4870 4871 // C++11 [class.base.init]p8: 4872 // if the entity is a non-static data member that has a 4873 // brace-or-equal-initializer and either 4874 // -- the constructor's class is a union and no other variant member of that 4875 // union is designated by a mem-initializer-id or 4876 // -- the constructor's class is not a union, and, if the entity is a member 4877 // of an anonymous union, no other member of that union is designated by 4878 // a mem-initializer-id, 4879 // the entity is initialized as specified in [dcl.init]. 4880 // 4881 // We also apply the same rules to handle anonymous structs within anonymous 4882 // unions. 4883 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4884 return false; 4885 4886 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4887 ExprResult DIE = 4888 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4889 if (DIE.isInvalid()) 4890 return true; 4891 4892 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4893 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4894 4895 CXXCtorInitializer *Init; 4896 if (Indirect) 4897 Init = new (SemaRef.Context) 4898 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4899 SourceLocation(), DIE.get(), SourceLocation()); 4900 else 4901 Init = new (SemaRef.Context) 4902 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4903 SourceLocation(), DIE.get(), SourceLocation()); 4904 return Info.addFieldInitializer(Init); 4905 } 4906 4907 // Don't initialize incomplete or zero-length arrays. 4908 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4909 return false; 4910 4911 // Don't try to build an implicit initializer if there were semantic 4912 // errors in any of the initializers (and therefore we might be 4913 // missing some that the user actually wrote). 4914 if (Info.AnyErrorsInInits) 4915 return false; 4916 4917 CXXCtorInitializer *Init = nullptr; 4918 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4919 Indirect, Init)) 4920 return true; 4921 4922 if (!Init) 4923 return false; 4924 4925 return Info.addFieldInitializer(Init); 4926 } 4927 4928 bool 4929 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4930 CXXCtorInitializer *Initializer) { 4931 assert(Initializer->isDelegatingInitializer()); 4932 Constructor->setNumCtorInitializers(1); 4933 CXXCtorInitializer **initializer = 4934 new (Context) CXXCtorInitializer*[1]; 4935 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4936 Constructor->setCtorInitializers(initializer); 4937 4938 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4939 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4940 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4941 } 4942 4943 DelegatingCtorDecls.push_back(Constructor); 4944 4945 DiagnoseUninitializedFields(*this, Constructor); 4946 4947 return false; 4948 } 4949 4950 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4951 ArrayRef<CXXCtorInitializer *> Initializers) { 4952 if (Constructor->isDependentContext()) { 4953 // Just store the initializers as written, they will be checked during 4954 // instantiation. 4955 if (!Initializers.empty()) { 4956 Constructor->setNumCtorInitializers(Initializers.size()); 4957 CXXCtorInitializer **baseOrMemberInitializers = 4958 new (Context) CXXCtorInitializer*[Initializers.size()]; 4959 memcpy(baseOrMemberInitializers, Initializers.data(), 4960 Initializers.size() * sizeof(CXXCtorInitializer*)); 4961 Constructor->setCtorInitializers(baseOrMemberInitializers); 4962 } 4963 4964 // Let template instantiation know whether we had errors. 4965 if (AnyErrors) 4966 Constructor->setInvalidDecl(); 4967 4968 return false; 4969 } 4970 4971 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4972 4973 // We need to build the initializer AST according to order of construction 4974 // and not what user specified in the Initializers list. 4975 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4976 if (!ClassDecl) 4977 return true; 4978 4979 bool HadError = false; 4980 4981 for (unsigned i = 0; i < Initializers.size(); i++) { 4982 CXXCtorInitializer *Member = Initializers[i]; 4983 4984 if (Member->isBaseInitializer()) 4985 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4986 else { 4987 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4988 4989 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4990 for (auto *C : F->chain()) { 4991 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4992 if (FD && FD->getParent()->isUnion()) 4993 Info.ActiveUnionMember.insert(std::make_pair( 4994 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4995 } 4996 } else if (FieldDecl *FD = Member->getMember()) { 4997 if (FD->getParent()->isUnion()) 4998 Info.ActiveUnionMember.insert(std::make_pair( 4999 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5000 } 5001 } 5002 } 5003 5004 // Keep track of the direct virtual bases. 5005 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5006 for (auto &I : ClassDecl->bases()) { 5007 if (I.isVirtual()) 5008 DirectVBases.insert(&I); 5009 } 5010 5011 // Push virtual bases before others. 5012 for (auto &VBase : ClassDecl->vbases()) { 5013 if (CXXCtorInitializer *Value 5014 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5015 // [class.base.init]p7, per DR257: 5016 // A mem-initializer where the mem-initializer-id names a virtual base 5017 // class is ignored during execution of a constructor of any class that 5018 // is not the most derived class. 5019 if (ClassDecl->isAbstract()) { 5020 // FIXME: Provide a fixit to remove the base specifier. This requires 5021 // tracking the location of the associated comma for a base specifier. 5022 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5023 << VBase.getType() << ClassDecl; 5024 DiagnoseAbstractType(ClassDecl); 5025 } 5026 5027 Info.AllToInit.push_back(Value); 5028 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5029 // [class.base.init]p8, per DR257: 5030 // If a given [...] base class is not named by a mem-initializer-id 5031 // [...] and the entity is not a virtual base class of an abstract 5032 // class, then [...] the entity is default-initialized. 5033 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5034 CXXCtorInitializer *CXXBaseInit; 5035 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5036 &VBase, IsInheritedVirtualBase, 5037 CXXBaseInit)) { 5038 HadError = true; 5039 continue; 5040 } 5041 5042 Info.AllToInit.push_back(CXXBaseInit); 5043 } 5044 } 5045 5046 // Non-virtual bases. 5047 for (auto &Base : ClassDecl->bases()) { 5048 // Virtuals are in the virtual base list and already constructed. 5049 if (Base.isVirtual()) 5050 continue; 5051 5052 if (CXXCtorInitializer *Value 5053 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5054 Info.AllToInit.push_back(Value); 5055 } else if (!AnyErrors) { 5056 CXXCtorInitializer *CXXBaseInit; 5057 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5058 &Base, /*IsInheritedVirtualBase=*/false, 5059 CXXBaseInit)) { 5060 HadError = true; 5061 continue; 5062 } 5063 5064 Info.AllToInit.push_back(CXXBaseInit); 5065 } 5066 } 5067 5068 // Fields. 5069 for (auto *Mem : ClassDecl->decls()) { 5070 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5071 // C++ [class.bit]p2: 5072 // A declaration for a bit-field that omits the identifier declares an 5073 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5074 // initialized. 5075 if (F->isUnnamedBitfield()) 5076 continue; 5077 5078 // If we're not generating the implicit copy/move constructor, then we'll 5079 // handle anonymous struct/union fields based on their individual 5080 // indirect fields. 5081 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5082 continue; 5083 5084 if (CollectFieldInitializer(*this, Info, F)) 5085 HadError = true; 5086 continue; 5087 } 5088 5089 // Beyond this point, we only consider default initialization. 5090 if (Info.isImplicitCopyOrMove()) 5091 continue; 5092 5093 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5094 if (F->getType()->isIncompleteArrayType()) { 5095 assert(ClassDecl->hasFlexibleArrayMember() && 5096 "Incomplete array type is not valid"); 5097 continue; 5098 } 5099 5100 // Initialize each field of an anonymous struct individually. 5101 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5102 HadError = true; 5103 5104 continue; 5105 } 5106 } 5107 5108 unsigned NumInitializers = Info.AllToInit.size(); 5109 if (NumInitializers > 0) { 5110 Constructor->setNumCtorInitializers(NumInitializers); 5111 CXXCtorInitializer **baseOrMemberInitializers = 5112 new (Context) CXXCtorInitializer*[NumInitializers]; 5113 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5114 NumInitializers * sizeof(CXXCtorInitializer*)); 5115 Constructor->setCtorInitializers(baseOrMemberInitializers); 5116 5117 // Constructors implicitly reference the base and member 5118 // destructors. 5119 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5120 Constructor->getParent()); 5121 } 5122 5123 return HadError; 5124 } 5125 5126 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5127 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5128 const RecordDecl *RD = RT->getDecl(); 5129 if (RD->isAnonymousStructOrUnion()) { 5130 for (auto *Field : RD->fields()) 5131 PopulateKeysForFields(Field, IdealInits); 5132 return; 5133 } 5134 } 5135 IdealInits.push_back(Field->getCanonicalDecl()); 5136 } 5137 5138 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5139 return Context.getCanonicalType(BaseType).getTypePtr(); 5140 } 5141 5142 static const void *GetKeyForMember(ASTContext &Context, 5143 CXXCtorInitializer *Member) { 5144 if (!Member->isAnyMemberInitializer()) 5145 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5146 5147 return Member->getAnyMember()->getCanonicalDecl(); 5148 } 5149 5150 static void DiagnoseBaseOrMemInitializerOrder( 5151 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5152 ArrayRef<CXXCtorInitializer *> Inits) { 5153 if (Constructor->getDeclContext()->isDependentContext()) 5154 return; 5155 5156 // Don't check initializers order unless the warning is enabled at the 5157 // location of at least one initializer. 5158 bool ShouldCheckOrder = false; 5159 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5160 CXXCtorInitializer *Init = Inits[InitIndex]; 5161 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5162 Init->getSourceLocation())) { 5163 ShouldCheckOrder = true; 5164 break; 5165 } 5166 } 5167 if (!ShouldCheckOrder) 5168 return; 5169 5170 // Build the list of bases and members in the order that they'll 5171 // actually be initialized. The explicit initializers should be in 5172 // this same order but may be missing things. 5173 SmallVector<const void*, 32> IdealInitKeys; 5174 5175 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5176 5177 // 1. Virtual bases. 5178 for (const auto &VBase : ClassDecl->vbases()) 5179 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5180 5181 // 2. Non-virtual bases. 5182 for (const auto &Base : ClassDecl->bases()) { 5183 if (Base.isVirtual()) 5184 continue; 5185 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5186 } 5187 5188 // 3. Direct fields. 5189 for (auto *Field : ClassDecl->fields()) { 5190 if (Field->isUnnamedBitfield()) 5191 continue; 5192 5193 PopulateKeysForFields(Field, IdealInitKeys); 5194 } 5195 5196 unsigned NumIdealInits = IdealInitKeys.size(); 5197 unsigned IdealIndex = 0; 5198 5199 CXXCtorInitializer *PrevInit = nullptr; 5200 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5201 CXXCtorInitializer *Init = Inits[InitIndex]; 5202 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5203 5204 // Scan forward to try to find this initializer in the idealized 5205 // initializers list. 5206 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5207 if (InitKey == IdealInitKeys[IdealIndex]) 5208 break; 5209 5210 // If we didn't find this initializer, it must be because we 5211 // scanned past it on a previous iteration. That can only 5212 // happen if we're out of order; emit a warning. 5213 if (IdealIndex == NumIdealInits && PrevInit) { 5214 Sema::SemaDiagnosticBuilder D = 5215 SemaRef.Diag(PrevInit->getSourceLocation(), 5216 diag::warn_initializer_out_of_order); 5217 5218 if (PrevInit->isAnyMemberInitializer()) 5219 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5220 else 5221 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5222 5223 if (Init->isAnyMemberInitializer()) 5224 D << 0 << Init->getAnyMember()->getDeclName(); 5225 else 5226 D << 1 << Init->getTypeSourceInfo()->getType(); 5227 5228 // Move back to the initializer's location in the ideal list. 5229 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5230 if (InitKey == IdealInitKeys[IdealIndex]) 5231 break; 5232 5233 assert(IdealIndex < NumIdealInits && 5234 "initializer not found in initializer list"); 5235 } 5236 5237 PrevInit = Init; 5238 } 5239 } 5240 5241 namespace { 5242 bool CheckRedundantInit(Sema &S, 5243 CXXCtorInitializer *Init, 5244 CXXCtorInitializer *&PrevInit) { 5245 if (!PrevInit) { 5246 PrevInit = Init; 5247 return false; 5248 } 5249 5250 if (FieldDecl *Field = Init->getAnyMember()) 5251 S.Diag(Init->getSourceLocation(), 5252 diag::err_multiple_mem_initialization) 5253 << Field->getDeclName() 5254 << Init->getSourceRange(); 5255 else { 5256 const Type *BaseClass = Init->getBaseClass(); 5257 assert(BaseClass && "neither field nor base"); 5258 S.Diag(Init->getSourceLocation(), 5259 diag::err_multiple_base_initialization) 5260 << QualType(BaseClass, 0) 5261 << Init->getSourceRange(); 5262 } 5263 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5264 << 0 << PrevInit->getSourceRange(); 5265 5266 return true; 5267 } 5268 5269 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5270 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5271 5272 bool CheckRedundantUnionInit(Sema &S, 5273 CXXCtorInitializer *Init, 5274 RedundantUnionMap &Unions) { 5275 FieldDecl *Field = Init->getAnyMember(); 5276 RecordDecl *Parent = Field->getParent(); 5277 NamedDecl *Child = Field; 5278 5279 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5280 if (Parent->isUnion()) { 5281 UnionEntry &En = Unions[Parent]; 5282 if (En.first && En.first != Child) { 5283 S.Diag(Init->getSourceLocation(), 5284 diag::err_multiple_mem_union_initialization) 5285 << Field->getDeclName() 5286 << Init->getSourceRange(); 5287 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5288 << 0 << En.second->getSourceRange(); 5289 return true; 5290 } 5291 if (!En.first) { 5292 En.first = Child; 5293 En.second = Init; 5294 } 5295 if (!Parent->isAnonymousStructOrUnion()) 5296 return false; 5297 } 5298 5299 Child = Parent; 5300 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5301 } 5302 5303 return false; 5304 } 5305 } 5306 5307 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5308 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5309 SourceLocation ColonLoc, 5310 ArrayRef<CXXCtorInitializer*> MemInits, 5311 bool AnyErrors) { 5312 if (!ConstructorDecl) 5313 return; 5314 5315 AdjustDeclIfTemplate(ConstructorDecl); 5316 5317 CXXConstructorDecl *Constructor 5318 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5319 5320 if (!Constructor) { 5321 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5322 return; 5323 } 5324 5325 // Mapping for the duplicate initializers check. 5326 // For member initializers, this is keyed with a FieldDecl*. 5327 // For base initializers, this is keyed with a Type*. 5328 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5329 5330 // Mapping for the inconsistent anonymous-union initializers check. 5331 RedundantUnionMap MemberUnions; 5332 5333 bool HadError = false; 5334 for (unsigned i = 0; i < MemInits.size(); i++) { 5335 CXXCtorInitializer *Init = MemInits[i]; 5336 5337 // Set the source order index. 5338 Init->setSourceOrder(i); 5339 5340 if (Init->isAnyMemberInitializer()) { 5341 const void *Key = GetKeyForMember(Context, Init); 5342 if (CheckRedundantInit(*this, Init, Members[Key]) || 5343 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5344 HadError = true; 5345 } else if (Init->isBaseInitializer()) { 5346 const void *Key = GetKeyForMember(Context, Init); 5347 if (CheckRedundantInit(*this, Init, Members[Key])) 5348 HadError = true; 5349 } else { 5350 assert(Init->isDelegatingInitializer()); 5351 // This must be the only initializer 5352 if (MemInits.size() != 1) { 5353 Diag(Init->getSourceLocation(), 5354 diag::err_delegating_initializer_alone) 5355 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5356 // We will treat this as being the only initializer. 5357 } 5358 SetDelegatingInitializer(Constructor, MemInits[i]); 5359 // Return immediately as the initializer is set. 5360 return; 5361 } 5362 } 5363 5364 if (HadError) 5365 return; 5366 5367 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5368 5369 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5370 5371 DiagnoseUninitializedFields(*this, Constructor); 5372 } 5373 5374 void 5375 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5376 CXXRecordDecl *ClassDecl) { 5377 // Ignore dependent contexts. Also ignore unions, since their members never 5378 // have destructors implicitly called. 5379 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5380 return; 5381 5382 // FIXME: all the access-control diagnostics are positioned on the 5383 // field/base declaration. That's probably good; that said, the 5384 // user might reasonably want to know why the destructor is being 5385 // emitted, and we currently don't say. 5386 5387 // Non-static data members. 5388 for (auto *Field : ClassDecl->fields()) { 5389 if (Field->isInvalidDecl()) 5390 continue; 5391 5392 // Don't destroy incomplete or zero-length arrays. 5393 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5394 continue; 5395 5396 QualType FieldType = Context.getBaseElementType(Field->getType()); 5397 5398 const RecordType* RT = FieldType->getAs<RecordType>(); 5399 if (!RT) 5400 continue; 5401 5402 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5403 if (FieldClassDecl->isInvalidDecl()) 5404 continue; 5405 if (FieldClassDecl->hasIrrelevantDestructor()) 5406 continue; 5407 // The destructor for an implicit anonymous union member is never invoked. 5408 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5409 continue; 5410 5411 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5412 assert(Dtor && "No dtor found for FieldClassDecl!"); 5413 CheckDestructorAccess(Field->getLocation(), Dtor, 5414 PDiag(diag::err_access_dtor_field) 5415 << Field->getDeclName() 5416 << FieldType); 5417 5418 MarkFunctionReferenced(Location, Dtor); 5419 DiagnoseUseOfDecl(Dtor, Location); 5420 } 5421 5422 // We only potentially invoke the destructors of potentially constructed 5423 // subobjects. 5424 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5425 5426 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5427 5428 // Bases. 5429 for (const auto &Base : ClassDecl->bases()) { 5430 // Bases are always records in a well-formed non-dependent class. 5431 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5432 5433 // Remember direct virtual bases. 5434 if (Base.isVirtual()) { 5435 if (!VisitVirtualBases) 5436 continue; 5437 DirectVirtualBases.insert(RT); 5438 } 5439 5440 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5441 // If our base class is invalid, we probably can't get its dtor anyway. 5442 if (BaseClassDecl->isInvalidDecl()) 5443 continue; 5444 if (BaseClassDecl->hasIrrelevantDestructor()) 5445 continue; 5446 5447 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5448 assert(Dtor && "No dtor found for BaseClassDecl!"); 5449 5450 // FIXME: caret should be on the start of the class name 5451 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5452 PDiag(diag::err_access_dtor_base) 5453 << Base.getType() << Base.getSourceRange(), 5454 Context.getTypeDeclType(ClassDecl)); 5455 5456 MarkFunctionReferenced(Location, Dtor); 5457 DiagnoseUseOfDecl(Dtor, Location); 5458 } 5459 5460 if (!VisitVirtualBases) 5461 return; 5462 5463 // Virtual bases. 5464 for (const auto &VBase : ClassDecl->vbases()) { 5465 // Bases are always records in a well-formed non-dependent class. 5466 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5467 5468 // Ignore direct virtual bases. 5469 if (DirectVirtualBases.count(RT)) 5470 continue; 5471 5472 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5473 // If our base class is invalid, we probably can't get its dtor anyway. 5474 if (BaseClassDecl->isInvalidDecl()) 5475 continue; 5476 if (BaseClassDecl->hasIrrelevantDestructor()) 5477 continue; 5478 5479 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5480 assert(Dtor && "No dtor found for BaseClassDecl!"); 5481 if (CheckDestructorAccess( 5482 ClassDecl->getLocation(), Dtor, 5483 PDiag(diag::err_access_dtor_vbase) 5484 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5485 Context.getTypeDeclType(ClassDecl)) == 5486 AR_accessible) { 5487 CheckDerivedToBaseConversion( 5488 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5489 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5490 SourceRange(), DeclarationName(), nullptr); 5491 } 5492 5493 MarkFunctionReferenced(Location, Dtor); 5494 DiagnoseUseOfDecl(Dtor, Location); 5495 } 5496 } 5497 5498 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5499 if (!CDtorDecl) 5500 return; 5501 5502 if (CXXConstructorDecl *Constructor 5503 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5504 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5505 DiagnoseUninitializedFields(*this, Constructor); 5506 } 5507 } 5508 5509 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5510 if (!getLangOpts().CPlusPlus) 5511 return false; 5512 5513 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5514 if (!RD) 5515 return false; 5516 5517 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5518 // class template specialization here, but doing so breaks a lot of code. 5519 5520 // We can't answer whether something is abstract until it has a 5521 // definition. If it's currently being defined, we'll walk back 5522 // over all the declarations when we have a full definition. 5523 const CXXRecordDecl *Def = RD->getDefinition(); 5524 if (!Def || Def->isBeingDefined()) 5525 return false; 5526 5527 return RD->isAbstract(); 5528 } 5529 5530 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5531 TypeDiagnoser &Diagnoser) { 5532 if (!isAbstractType(Loc, T)) 5533 return false; 5534 5535 T = Context.getBaseElementType(T); 5536 Diagnoser.diagnose(*this, Loc, T); 5537 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5538 return true; 5539 } 5540 5541 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5542 // Check if we've already emitted the list of pure virtual functions 5543 // for this class. 5544 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5545 return; 5546 5547 // If the diagnostic is suppressed, don't emit the notes. We're only 5548 // going to emit them once, so try to attach them to a diagnostic we're 5549 // actually going to show. 5550 if (Diags.isLastDiagnosticIgnored()) 5551 return; 5552 5553 CXXFinalOverriderMap FinalOverriders; 5554 RD->getFinalOverriders(FinalOverriders); 5555 5556 // Keep a set of seen pure methods so we won't diagnose the same method 5557 // more than once. 5558 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5559 5560 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5561 MEnd = FinalOverriders.end(); 5562 M != MEnd; 5563 ++M) { 5564 for (OverridingMethods::iterator SO = M->second.begin(), 5565 SOEnd = M->second.end(); 5566 SO != SOEnd; ++SO) { 5567 // C++ [class.abstract]p4: 5568 // A class is abstract if it contains or inherits at least one 5569 // pure virtual function for which the final overrider is pure 5570 // virtual. 5571 5572 // 5573 if (SO->second.size() != 1) 5574 continue; 5575 5576 if (!SO->second.front().Method->isPure()) 5577 continue; 5578 5579 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5580 continue; 5581 5582 Diag(SO->second.front().Method->getLocation(), 5583 diag::note_pure_virtual_function) 5584 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5585 } 5586 } 5587 5588 if (!PureVirtualClassDiagSet) 5589 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5590 PureVirtualClassDiagSet->insert(RD); 5591 } 5592 5593 namespace { 5594 struct AbstractUsageInfo { 5595 Sema &S; 5596 CXXRecordDecl *Record; 5597 CanQualType AbstractType; 5598 bool Invalid; 5599 5600 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5601 : S(S), Record(Record), 5602 AbstractType(S.Context.getCanonicalType( 5603 S.Context.getTypeDeclType(Record))), 5604 Invalid(false) {} 5605 5606 void DiagnoseAbstractType() { 5607 if (Invalid) return; 5608 S.DiagnoseAbstractType(Record); 5609 Invalid = true; 5610 } 5611 5612 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5613 }; 5614 5615 struct CheckAbstractUsage { 5616 AbstractUsageInfo &Info; 5617 const NamedDecl *Ctx; 5618 5619 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5620 : Info(Info), Ctx(Ctx) {} 5621 5622 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5623 switch (TL.getTypeLocClass()) { 5624 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5625 #define TYPELOC(CLASS, PARENT) \ 5626 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5627 #include "clang/AST/TypeLocNodes.def" 5628 } 5629 } 5630 5631 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5632 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5633 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5634 if (!TL.getParam(I)) 5635 continue; 5636 5637 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5638 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5639 } 5640 } 5641 5642 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5643 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5644 } 5645 5646 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5647 // Visit the type parameters from a permissive context. 5648 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5649 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5650 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5651 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5652 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5653 // TODO: other template argument types? 5654 } 5655 } 5656 5657 // Visit pointee types from a permissive context. 5658 #define CheckPolymorphic(Type) \ 5659 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5660 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5661 } 5662 CheckPolymorphic(PointerTypeLoc) 5663 CheckPolymorphic(ReferenceTypeLoc) 5664 CheckPolymorphic(MemberPointerTypeLoc) 5665 CheckPolymorphic(BlockPointerTypeLoc) 5666 CheckPolymorphic(AtomicTypeLoc) 5667 5668 /// Handle all the types we haven't given a more specific 5669 /// implementation for above. 5670 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5671 // Every other kind of type that we haven't called out already 5672 // that has an inner type is either (1) sugar or (2) contains that 5673 // inner type in some way as a subobject. 5674 if (TypeLoc Next = TL.getNextTypeLoc()) 5675 return Visit(Next, Sel); 5676 5677 // If there's no inner type and we're in a permissive context, 5678 // don't diagnose. 5679 if (Sel == Sema::AbstractNone) return; 5680 5681 // Check whether the type matches the abstract type. 5682 QualType T = TL.getType(); 5683 if (T->isArrayType()) { 5684 Sel = Sema::AbstractArrayType; 5685 T = Info.S.Context.getBaseElementType(T); 5686 } 5687 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5688 if (CT != Info.AbstractType) return; 5689 5690 // It matched; do some magic. 5691 if (Sel == Sema::AbstractArrayType) { 5692 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5693 << T << TL.getSourceRange(); 5694 } else { 5695 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5696 << Sel << T << TL.getSourceRange(); 5697 } 5698 Info.DiagnoseAbstractType(); 5699 } 5700 }; 5701 5702 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5703 Sema::AbstractDiagSelID Sel) { 5704 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5705 } 5706 5707 } 5708 5709 /// Check for invalid uses of an abstract type in a method declaration. 5710 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5711 CXXMethodDecl *MD) { 5712 // No need to do the check on definitions, which require that 5713 // the return/param types be complete. 5714 if (MD->doesThisDeclarationHaveABody()) 5715 return; 5716 5717 // For safety's sake, just ignore it if we don't have type source 5718 // information. This should never happen for non-implicit methods, 5719 // but... 5720 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5721 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5722 } 5723 5724 /// Check for invalid uses of an abstract type within a class definition. 5725 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5726 CXXRecordDecl *RD) { 5727 for (auto *D : RD->decls()) { 5728 if (D->isImplicit()) continue; 5729 5730 // Methods and method templates. 5731 if (isa<CXXMethodDecl>(D)) { 5732 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5733 } else if (isa<FunctionTemplateDecl>(D)) { 5734 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5735 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5736 5737 // Fields and static variables. 5738 } else if (isa<FieldDecl>(D)) { 5739 FieldDecl *FD = cast<FieldDecl>(D); 5740 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5741 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5742 } else if (isa<VarDecl>(D)) { 5743 VarDecl *VD = cast<VarDecl>(D); 5744 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5745 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5746 5747 // Nested classes and class templates. 5748 } else if (isa<CXXRecordDecl>(D)) { 5749 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5750 } else if (isa<ClassTemplateDecl>(D)) { 5751 CheckAbstractClassUsage(Info, 5752 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5753 } 5754 } 5755 } 5756 5757 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5758 Attr *ClassAttr = getDLLAttr(Class); 5759 if (!ClassAttr) 5760 return; 5761 5762 assert(ClassAttr->getKind() == attr::DLLExport); 5763 5764 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5765 5766 if (TSK == TSK_ExplicitInstantiationDeclaration) 5767 // Don't go any further if this is just an explicit instantiation 5768 // declaration. 5769 return; 5770 5771 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5772 S.MarkVTableUsed(Class->getLocation(), Class, true); 5773 5774 for (Decl *Member : Class->decls()) { 5775 // Defined static variables that are members of an exported base 5776 // class must be marked export too. 5777 auto *VD = dyn_cast<VarDecl>(Member); 5778 if (VD && Member->getAttr<DLLExportAttr>() && 5779 VD->getStorageClass() == SC_Static && 5780 TSK == TSK_ImplicitInstantiation) 5781 S.MarkVariableReferenced(VD->getLocation(), VD); 5782 5783 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5784 if (!MD) 5785 continue; 5786 5787 if (Member->getAttr<DLLExportAttr>()) { 5788 if (MD->isUserProvided()) { 5789 // Instantiate non-default class member functions ... 5790 5791 // .. except for certain kinds of template specializations. 5792 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5793 continue; 5794 5795 S.MarkFunctionReferenced(Class->getLocation(), MD); 5796 5797 // The function will be passed to the consumer when its definition is 5798 // encountered. 5799 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5800 MD->isCopyAssignmentOperator() || 5801 MD->isMoveAssignmentOperator()) { 5802 // Synthesize and instantiate non-trivial implicit methods, explicitly 5803 // defaulted methods, and the copy and move assignment operators. The 5804 // latter are exported even if they are trivial, because the address of 5805 // an operator can be taken and should compare equal across libraries. 5806 DiagnosticErrorTrap Trap(S.Diags); 5807 S.MarkFunctionReferenced(Class->getLocation(), MD); 5808 if (Trap.hasErrorOccurred()) { 5809 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5810 << Class << !S.getLangOpts().CPlusPlus11; 5811 break; 5812 } 5813 5814 // There is no later point when we will see the definition of this 5815 // function, so pass it to the consumer now. 5816 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5817 } 5818 } 5819 } 5820 } 5821 5822 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5823 CXXRecordDecl *Class) { 5824 // Only the MS ABI has default constructor closures, so we don't need to do 5825 // this semantic checking anywhere else. 5826 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5827 return; 5828 5829 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5830 for (Decl *Member : Class->decls()) { 5831 // Look for exported default constructors. 5832 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5833 if (!CD || !CD->isDefaultConstructor()) 5834 continue; 5835 auto *Attr = CD->getAttr<DLLExportAttr>(); 5836 if (!Attr) 5837 continue; 5838 5839 // If the class is non-dependent, mark the default arguments as ODR-used so 5840 // that we can properly codegen the constructor closure. 5841 if (!Class->isDependentContext()) { 5842 for (ParmVarDecl *PD : CD->parameters()) { 5843 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5844 S.DiscardCleanupsInEvaluationContext(); 5845 } 5846 } 5847 5848 if (LastExportedDefaultCtor) { 5849 S.Diag(LastExportedDefaultCtor->getLocation(), 5850 diag::err_attribute_dll_ambiguous_default_ctor) 5851 << Class; 5852 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5853 << CD->getDeclName(); 5854 return; 5855 } 5856 LastExportedDefaultCtor = CD; 5857 } 5858 } 5859 5860 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5861 // Mark any compiler-generated routines with the implicit code_seg attribute. 5862 for (auto *Method : Class->methods()) { 5863 if (Method->isUserProvided()) 5864 continue; 5865 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5866 Method->addAttr(A); 5867 } 5868 } 5869 5870 /// Check class-level dllimport/dllexport attribute. 5871 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5872 Attr *ClassAttr = getDLLAttr(Class); 5873 5874 // MSVC inherits DLL attributes to partial class template specializations. 5875 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5876 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5877 if (Attr *TemplateAttr = 5878 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5879 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5880 A->setInherited(true); 5881 ClassAttr = A; 5882 } 5883 } 5884 } 5885 5886 if (!ClassAttr) 5887 return; 5888 5889 if (!Class->isExternallyVisible()) { 5890 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5891 << Class << ClassAttr; 5892 return; 5893 } 5894 5895 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5896 !ClassAttr->isInherited()) { 5897 // Diagnose dll attributes on members of class with dll attribute. 5898 for (Decl *Member : Class->decls()) { 5899 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5900 continue; 5901 InheritableAttr *MemberAttr = getDLLAttr(Member); 5902 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5903 continue; 5904 5905 Diag(MemberAttr->getLocation(), 5906 diag::err_attribute_dll_member_of_dll_class) 5907 << MemberAttr << ClassAttr; 5908 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5909 Member->setInvalidDecl(); 5910 } 5911 } 5912 5913 if (Class->getDescribedClassTemplate()) 5914 // Don't inherit dll attribute until the template is instantiated. 5915 return; 5916 5917 // The class is either imported or exported. 5918 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5919 5920 // Check if this was a dllimport attribute propagated from a derived class to 5921 // a base class template specialization. We don't apply these attributes to 5922 // static data members. 5923 const bool PropagatedImport = 5924 !ClassExported && 5925 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5926 5927 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5928 5929 // Ignore explicit dllexport on explicit class template instantiation 5930 // declarations, except in MinGW mode. 5931 if (ClassExported && !ClassAttr->isInherited() && 5932 TSK == TSK_ExplicitInstantiationDeclaration && 5933 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 5934 Class->dropAttr<DLLExportAttr>(); 5935 return; 5936 } 5937 5938 // Force declaration of implicit members so they can inherit the attribute. 5939 ForceDeclarationOfImplicitMembers(Class); 5940 5941 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5942 // seem to be true in practice? 5943 5944 for (Decl *Member : Class->decls()) { 5945 VarDecl *VD = dyn_cast<VarDecl>(Member); 5946 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5947 5948 // Only methods and static fields inherit the attributes. 5949 if (!VD && !MD) 5950 continue; 5951 5952 if (MD) { 5953 // Don't process deleted methods. 5954 if (MD->isDeleted()) 5955 continue; 5956 5957 if (MD->isInlined()) { 5958 // MinGW does not import or export inline methods. But do it for 5959 // template instantiations. 5960 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5961 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 5962 TSK != TSK_ExplicitInstantiationDeclaration && 5963 TSK != TSK_ExplicitInstantiationDefinition) 5964 continue; 5965 5966 // MSVC versions before 2015 don't export the move assignment operators 5967 // and move constructor, so don't attempt to import/export them if 5968 // we have a definition. 5969 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5970 if ((MD->isMoveAssignmentOperator() || 5971 (Ctor && Ctor->isMoveConstructor())) && 5972 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5973 continue; 5974 5975 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5976 // operator is exported anyway. 5977 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5978 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5979 continue; 5980 } 5981 } 5982 5983 // Don't apply dllimport attributes to static data members of class template 5984 // instantiations when the attribute is propagated from a derived class. 5985 if (VD && PropagatedImport) 5986 continue; 5987 5988 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5989 continue; 5990 5991 if (!getDLLAttr(Member)) { 5992 InheritableAttr *NewAttr = nullptr; 5993 5994 // Do not export/import inline function when -fno-dllexport-inlines is 5995 // passed. But add attribute for later local static var check. 5996 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 5997 TSK != TSK_ExplicitInstantiationDeclaration && 5998 TSK != TSK_ExplicitInstantiationDefinition) { 5999 if (ClassExported) { 6000 NewAttr = ::new (getASTContext()) 6001 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6002 } else { 6003 NewAttr = ::new (getASTContext()) 6004 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6005 } 6006 } else { 6007 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6008 } 6009 6010 NewAttr->setInherited(true); 6011 Member->addAttr(NewAttr); 6012 6013 if (MD) { 6014 // Propagate DLLAttr to friend re-declarations of MD that have already 6015 // been constructed. 6016 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6017 FD = FD->getPreviousDecl()) { 6018 if (FD->getFriendObjectKind() == Decl::FOK_None) 6019 continue; 6020 assert(!getDLLAttr(FD) && 6021 "friend re-decl should not already have a DLLAttr"); 6022 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6023 NewAttr->setInherited(true); 6024 FD->addAttr(NewAttr); 6025 } 6026 } 6027 } 6028 } 6029 6030 if (ClassExported) 6031 DelayedDllExportClasses.push_back(Class); 6032 } 6033 6034 /// Perform propagation of DLL attributes from a derived class to a 6035 /// templated base class for MS compatibility. 6036 void Sema::propagateDLLAttrToBaseClassTemplate( 6037 CXXRecordDecl *Class, Attr *ClassAttr, 6038 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6039 if (getDLLAttr( 6040 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6041 // If the base class template has a DLL attribute, don't try to change it. 6042 return; 6043 } 6044 6045 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6046 if (!getDLLAttr(BaseTemplateSpec) && 6047 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6048 TSK == TSK_ImplicitInstantiation)) { 6049 // The template hasn't been instantiated yet (or it has, but only as an 6050 // explicit instantiation declaration or implicit instantiation, which means 6051 // we haven't codegenned any members yet), so propagate the attribute. 6052 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6053 NewAttr->setInherited(true); 6054 BaseTemplateSpec->addAttr(NewAttr); 6055 6056 // If this was an import, mark that we propagated it from a derived class to 6057 // a base class template specialization. 6058 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6059 ImportAttr->setPropagatedToBaseTemplate(); 6060 6061 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6062 // needs to be run again to work see the new attribute. Otherwise this will 6063 // get run whenever the template is instantiated. 6064 if (TSK != TSK_Undeclared) 6065 checkClassLevelDLLAttribute(BaseTemplateSpec); 6066 6067 return; 6068 } 6069 6070 if (getDLLAttr(BaseTemplateSpec)) { 6071 // The template has already been specialized or instantiated with an 6072 // attribute, explicitly or through propagation. We should not try to change 6073 // it. 6074 return; 6075 } 6076 6077 // The template was previously instantiated or explicitly specialized without 6078 // a dll attribute, It's too late for us to add an attribute, so warn that 6079 // this is unsupported. 6080 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6081 << BaseTemplateSpec->isExplicitSpecialization(); 6082 Diag(ClassAttr->getLocation(), diag::note_attribute); 6083 if (BaseTemplateSpec->isExplicitSpecialization()) { 6084 Diag(BaseTemplateSpec->getLocation(), 6085 diag::note_template_class_explicit_specialization_was_here) 6086 << BaseTemplateSpec; 6087 } else { 6088 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6089 diag::note_template_class_instantiation_was_here) 6090 << BaseTemplateSpec; 6091 } 6092 } 6093 6094 /// Determine the kind of defaulting that would be done for a given function. 6095 /// 6096 /// If the function is both a default constructor and a copy / move constructor 6097 /// (due to having a default argument for the first parameter), this picks 6098 /// CXXDefaultConstructor. 6099 /// 6100 /// FIXME: Check that case is properly handled by all callers. 6101 Sema::DefaultedFunctionKind 6102 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6103 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6104 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6105 if (Ctor->isDefaultConstructor()) 6106 return Sema::CXXDefaultConstructor; 6107 6108 if (Ctor->isCopyConstructor()) 6109 return Sema::CXXCopyConstructor; 6110 6111 if (Ctor->isMoveConstructor()) 6112 return Sema::CXXMoveConstructor; 6113 } 6114 6115 if (MD->isCopyAssignmentOperator()) 6116 return Sema::CXXCopyAssignment; 6117 6118 if (MD->isMoveAssignmentOperator()) 6119 return Sema::CXXMoveAssignment; 6120 6121 if (isa<CXXDestructorDecl>(FD)) 6122 return Sema::CXXDestructor; 6123 } 6124 6125 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6126 case OO_EqualEqual: 6127 return DefaultedComparisonKind::Equal; 6128 6129 case OO_ExclaimEqual: 6130 return DefaultedComparisonKind::NotEqual; 6131 6132 case OO_Spaceship: 6133 // No point allowing this if <=> doesn't exist in the current language mode. 6134 if (!getLangOpts().CPlusPlus2a) 6135 break; 6136 return DefaultedComparisonKind::ThreeWay; 6137 6138 case OO_Less: 6139 case OO_LessEqual: 6140 case OO_Greater: 6141 case OO_GreaterEqual: 6142 // No point allowing this if <=> doesn't exist in the current language mode. 6143 if (!getLangOpts().CPlusPlus2a) 6144 break; 6145 return DefaultedComparisonKind::Relational; 6146 6147 default: 6148 break; 6149 } 6150 6151 // Not defaultable. 6152 return DefaultedFunctionKind(); 6153 } 6154 6155 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 6156 SourceLocation DefaultLoc) { 6157 switch (S.getSpecialMember(MD)) { 6158 case Sema::CXXDefaultConstructor: 6159 S.DefineImplicitDefaultConstructor(DefaultLoc, 6160 cast<CXXConstructorDecl>(MD)); 6161 break; 6162 case Sema::CXXCopyConstructor: 6163 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6164 break; 6165 case Sema::CXXCopyAssignment: 6166 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 6167 break; 6168 case Sema::CXXDestructor: 6169 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 6170 break; 6171 case Sema::CXXMoveConstructor: 6172 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6173 break; 6174 case Sema::CXXMoveAssignment: 6175 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 6176 break; 6177 case Sema::CXXInvalid: 6178 llvm_unreachable("Invalid special member."); 6179 } 6180 } 6181 6182 /// Determine whether a type is permitted to be passed or returned in 6183 /// registers, per C++ [class.temporary]p3. 6184 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6185 TargetInfo::CallingConvKind CCK) { 6186 if (D->isDependentType() || D->isInvalidDecl()) 6187 return false; 6188 6189 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6190 // The PS4 platform ABI follows the behavior of Clang 3.2. 6191 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6192 return !D->hasNonTrivialDestructorForCall() && 6193 !D->hasNonTrivialCopyConstructorForCall(); 6194 6195 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6196 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6197 bool DtorIsTrivialForCall = false; 6198 6199 // If a class has at least one non-deleted, trivial copy constructor, it 6200 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6201 // 6202 // Note: This permits classes with non-trivial copy or move ctors to be 6203 // passed in registers, so long as they *also* have a trivial copy ctor, 6204 // which is non-conforming. 6205 if (D->needsImplicitCopyConstructor()) { 6206 if (!D->defaultedCopyConstructorIsDeleted()) { 6207 if (D->hasTrivialCopyConstructor()) 6208 CopyCtorIsTrivial = true; 6209 if (D->hasTrivialCopyConstructorForCall()) 6210 CopyCtorIsTrivialForCall = true; 6211 } 6212 } else { 6213 for (const CXXConstructorDecl *CD : D->ctors()) { 6214 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6215 if (CD->isTrivial()) 6216 CopyCtorIsTrivial = true; 6217 if (CD->isTrivialForCall()) 6218 CopyCtorIsTrivialForCall = true; 6219 } 6220 } 6221 } 6222 6223 if (D->needsImplicitDestructor()) { 6224 if (!D->defaultedDestructorIsDeleted() && 6225 D->hasTrivialDestructorForCall()) 6226 DtorIsTrivialForCall = true; 6227 } else if (const auto *DD = D->getDestructor()) { 6228 if (!DD->isDeleted() && DD->isTrivialForCall()) 6229 DtorIsTrivialForCall = true; 6230 } 6231 6232 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6233 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6234 return true; 6235 6236 // If a class has a destructor, we'd really like to pass it indirectly 6237 // because it allows us to elide copies. Unfortunately, MSVC makes that 6238 // impossible for small types, which it will pass in a single register or 6239 // stack slot. Most objects with dtors are large-ish, so handle that early. 6240 // We can't call out all large objects as being indirect because there are 6241 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6242 // how we pass large POD types. 6243 6244 // Note: This permits small classes with nontrivial destructors to be 6245 // passed in registers, which is non-conforming. 6246 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6247 uint64_t TypeSize = isAArch64 ? 128 : 64; 6248 6249 if (CopyCtorIsTrivial && 6250 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6251 return true; 6252 return false; 6253 } 6254 6255 // Per C++ [class.temporary]p3, the relevant condition is: 6256 // each copy constructor, move constructor, and destructor of X is 6257 // either trivial or deleted, and X has at least one non-deleted copy 6258 // or move constructor 6259 bool HasNonDeletedCopyOrMove = false; 6260 6261 if (D->needsImplicitCopyConstructor() && 6262 !D->defaultedCopyConstructorIsDeleted()) { 6263 if (!D->hasTrivialCopyConstructorForCall()) 6264 return false; 6265 HasNonDeletedCopyOrMove = true; 6266 } 6267 6268 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6269 !D->defaultedMoveConstructorIsDeleted()) { 6270 if (!D->hasTrivialMoveConstructorForCall()) 6271 return false; 6272 HasNonDeletedCopyOrMove = true; 6273 } 6274 6275 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6276 !D->hasTrivialDestructorForCall()) 6277 return false; 6278 6279 for (const CXXMethodDecl *MD : D->methods()) { 6280 if (MD->isDeleted()) 6281 continue; 6282 6283 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6284 if (CD && CD->isCopyOrMoveConstructor()) 6285 HasNonDeletedCopyOrMove = true; 6286 else if (!isa<CXXDestructorDecl>(MD)) 6287 continue; 6288 6289 if (!MD->isTrivialForCall()) 6290 return false; 6291 } 6292 6293 return HasNonDeletedCopyOrMove; 6294 } 6295 6296 /// Perform semantic checks on a class definition that has been 6297 /// completing, introducing implicitly-declared members, checking for 6298 /// abstract types, etc. 6299 /// 6300 /// \param S The scope in which the class was parsed. Null if we didn't just 6301 /// parse a class definition. 6302 /// \param Record The completed class. 6303 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6304 if (!Record) 6305 return; 6306 6307 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6308 AbstractUsageInfo Info(*this, Record); 6309 CheckAbstractClassUsage(Info, Record); 6310 } 6311 6312 // If this is not an aggregate type and has no user-declared constructor, 6313 // complain about any non-static data members of reference or const scalar 6314 // type, since they will never get initializers. 6315 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6316 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6317 !Record->isLambda()) { 6318 bool Complained = false; 6319 for (const auto *F : Record->fields()) { 6320 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6321 continue; 6322 6323 if (F->getType()->isReferenceType() || 6324 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6325 if (!Complained) { 6326 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6327 << Record->getTagKind() << Record; 6328 Complained = true; 6329 } 6330 6331 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6332 << F->getType()->isReferenceType() 6333 << F->getDeclName(); 6334 } 6335 } 6336 } 6337 6338 if (Record->getIdentifier()) { 6339 // C++ [class.mem]p13: 6340 // If T is the name of a class, then each of the following shall have a 6341 // name different from T: 6342 // - every member of every anonymous union that is a member of class T. 6343 // 6344 // C++ [class.mem]p14: 6345 // In addition, if class T has a user-declared constructor (12.1), every 6346 // non-static data member of class T shall have a name different from T. 6347 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6348 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6349 ++I) { 6350 NamedDecl *D = (*I)->getUnderlyingDecl(); 6351 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6352 Record->hasUserDeclaredConstructor()) || 6353 isa<IndirectFieldDecl>(D)) { 6354 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6355 << D->getDeclName(); 6356 break; 6357 } 6358 } 6359 } 6360 6361 // Warn if the class has virtual methods but non-virtual public destructor. 6362 if (Record->isPolymorphic() && !Record->isDependentType()) { 6363 CXXDestructorDecl *dtor = Record->getDestructor(); 6364 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6365 !Record->hasAttr<FinalAttr>()) 6366 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6367 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6368 } 6369 6370 if (Record->isAbstract()) { 6371 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6372 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6373 << FA->isSpelledAsSealed(); 6374 DiagnoseAbstractType(Record); 6375 } 6376 } 6377 6378 // Warn if the class has a final destructor but is not itself marked final. 6379 if (!Record->hasAttr<FinalAttr>()) { 6380 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6381 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6382 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6383 << FA->isSpelledAsSealed() 6384 << FixItHint::CreateInsertion( 6385 getLocForEndOfToken(Record->getLocation()), 6386 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6387 Diag(Record->getLocation(), 6388 diag::note_final_dtor_non_final_class_silence) 6389 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6390 } 6391 } 6392 } 6393 6394 // See if trivial_abi has to be dropped. 6395 if (Record->hasAttr<TrivialABIAttr>()) 6396 checkIllFormedTrivialABIStruct(*Record); 6397 6398 // Set HasTrivialSpecialMemberForCall if the record has attribute 6399 // "trivial_abi". 6400 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6401 6402 if (HasTrivialABI) 6403 Record->setHasTrivialSpecialMemberForCall(); 6404 6405 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6406 // We check these last because they can depend on the properties of the 6407 // primary comparison functions (==, <=>). 6408 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6409 6410 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) { 6411 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6412 return; 6413 6414 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6415 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6416 DFK.asComparison() == DefaultedComparisonKind::Relational) 6417 DefaultedSecondaryComparisons.push_back(FD); 6418 else 6419 CheckExplicitlyDefaultedFunction(S, FD); 6420 }; 6421 6422 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6423 // Check whether the explicitly-defaulted members are valid. 6424 CheckForDefaultedFunction(M); 6425 6426 // Skip the rest of the checks for a member of a dependent class. 6427 if (Record->isDependentType()) 6428 return; 6429 6430 // For an explicitly defaulted or deleted special member, we defer 6431 // determining triviality until the class is complete. That time is now! 6432 CXXSpecialMember CSM = getSpecialMember(M); 6433 if (!M->isImplicit() && !M->isUserProvided()) { 6434 if (CSM != CXXInvalid) { 6435 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6436 // Inform the class that we've finished declaring this member. 6437 Record->finishedDefaultedOrDeletedMember(M); 6438 M->setTrivialForCall( 6439 HasTrivialABI || 6440 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6441 Record->setTrivialForCallFlags(M); 6442 } 6443 } 6444 6445 // Set triviality for the purpose of calls if this is a user-provided 6446 // copy/move constructor or destructor. 6447 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6448 CSM == CXXDestructor) && M->isUserProvided()) { 6449 M->setTrivialForCall(HasTrivialABI); 6450 Record->setTrivialForCallFlags(M); 6451 } 6452 6453 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6454 M->hasAttr<DLLExportAttr>()) { 6455 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6456 M->isTrivial() && 6457 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6458 CSM == CXXDestructor)) 6459 M->dropAttr<DLLExportAttr>(); 6460 6461 if (M->hasAttr<DLLExportAttr>()) { 6462 // Define after any fields with in-class initializers have been parsed. 6463 DelayedDllExportMemberFunctions.push_back(M); 6464 } 6465 } 6466 6467 // Define defaulted constexpr virtual functions that override a base class 6468 // function right away. 6469 // FIXME: We can defer doing this until the vtable is marked as used. 6470 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6471 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6472 }; 6473 6474 // Check the destructor before any other member function. We need to 6475 // determine whether it's trivial in order to determine whether the claas 6476 // type is a literal type, which is a prerequisite for determining whether 6477 // other special member functions are valid and whether they're implicitly 6478 // 'constexpr'. 6479 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6480 CompleteMemberFunction(Dtor); 6481 6482 bool HasMethodWithOverrideControl = false, 6483 HasOverridingMethodWithoutOverrideControl = false; 6484 for (auto *D : Record->decls()) { 6485 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6486 // FIXME: We could do this check for dependent types with non-dependent 6487 // bases. 6488 if (!Record->isDependentType()) { 6489 // See if a method overloads virtual methods in a base 6490 // class without overriding any. 6491 if (!M->isStatic()) 6492 DiagnoseHiddenVirtualMethods(M); 6493 if (M->hasAttr<OverrideAttr>()) 6494 HasMethodWithOverrideControl = true; 6495 else if (M->size_overridden_methods() > 0) 6496 HasOverridingMethodWithoutOverrideControl = true; 6497 } 6498 6499 if (!isa<CXXDestructorDecl>(M)) 6500 CompleteMemberFunction(M); 6501 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6502 CheckForDefaultedFunction( 6503 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6504 } 6505 } 6506 6507 if (HasMethodWithOverrideControl && 6508 HasOverridingMethodWithoutOverrideControl) { 6509 // At least one method has the 'override' control declared. 6510 // Diagnose all other overridden methods which do not have 'override' 6511 // specified on them. 6512 for (auto *M : Record->methods()) 6513 DiagnoseAbsenceOfOverrideControl(M); 6514 } 6515 6516 // Check the defaulted secondary comparisons after any other member functions. 6517 for (FunctionDecl *FD : DefaultedSecondaryComparisons) 6518 CheckExplicitlyDefaultedFunction(S, FD); 6519 6520 // ms_struct is a request to use the same ABI rules as MSVC. Check 6521 // whether this class uses any C++ features that are implemented 6522 // completely differently in MSVC, and if so, emit a diagnostic. 6523 // That diagnostic defaults to an error, but we allow projects to 6524 // map it down to a warning (or ignore it). It's a fairly common 6525 // practice among users of the ms_struct pragma to mass-annotate 6526 // headers, sweeping up a bunch of types that the project doesn't 6527 // really rely on MSVC-compatible layout for. We must therefore 6528 // support "ms_struct except for C++ stuff" as a secondary ABI. 6529 if (Record->isMsStruct(Context) && 6530 (Record->isPolymorphic() || Record->getNumBases())) { 6531 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6532 } 6533 6534 checkClassLevelDLLAttribute(Record); 6535 checkClassLevelCodeSegAttribute(Record); 6536 6537 bool ClangABICompat4 = 6538 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6539 TargetInfo::CallingConvKind CCK = 6540 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6541 bool CanPass = canPassInRegisters(*this, Record, CCK); 6542 6543 // Do not change ArgPassingRestrictions if it has already been set to 6544 // APK_CanNeverPassInRegs. 6545 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6546 Record->setArgPassingRestrictions(CanPass 6547 ? RecordDecl::APK_CanPassInRegs 6548 : RecordDecl::APK_CannotPassInRegs); 6549 6550 // If canPassInRegisters returns true despite the record having a non-trivial 6551 // destructor, the record is destructed in the callee. This happens only when 6552 // the record or one of its subobjects has a field annotated with trivial_abi 6553 // or a field qualified with ObjC __strong/__weak. 6554 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6555 Record->setParamDestroyedInCallee(true); 6556 else if (Record->hasNonTrivialDestructor()) 6557 Record->setParamDestroyedInCallee(CanPass); 6558 6559 if (getLangOpts().ForceEmitVTables) { 6560 // If we want to emit all the vtables, we need to mark it as used. This 6561 // is especially required for cases like vtable assumption loads. 6562 MarkVTableUsed(Record->getInnerLocStart(), Record); 6563 } 6564 } 6565 6566 /// Look up the special member function that would be called by a special 6567 /// member function for a subobject of class type. 6568 /// 6569 /// \param Class The class type of the subobject. 6570 /// \param CSM The kind of special member function. 6571 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6572 /// \param ConstRHS True if this is a copy operation with a const object 6573 /// on its RHS, that is, if the argument to the outer special member 6574 /// function is 'const' and this is not a field marked 'mutable'. 6575 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6576 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6577 unsigned FieldQuals, bool ConstRHS) { 6578 unsigned LHSQuals = 0; 6579 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6580 LHSQuals = FieldQuals; 6581 6582 unsigned RHSQuals = FieldQuals; 6583 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6584 RHSQuals = 0; 6585 else if (ConstRHS) 6586 RHSQuals |= Qualifiers::Const; 6587 6588 return S.LookupSpecialMember(Class, CSM, 6589 RHSQuals & Qualifiers::Const, 6590 RHSQuals & Qualifiers::Volatile, 6591 false, 6592 LHSQuals & Qualifiers::Const, 6593 LHSQuals & Qualifiers::Volatile); 6594 } 6595 6596 class Sema::InheritedConstructorInfo { 6597 Sema &S; 6598 SourceLocation UseLoc; 6599 6600 /// A mapping from the base classes through which the constructor was 6601 /// inherited to the using shadow declaration in that base class (or a null 6602 /// pointer if the constructor was declared in that base class). 6603 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6604 InheritedFromBases; 6605 6606 public: 6607 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6608 ConstructorUsingShadowDecl *Shadow) 6609 : S(S), UseLoc(UseLoc) { 6610 bool DiagnosedMultipleConstructedBases = false; 6611 CXXRecordDecl *ConstructedBase = nullptr; 6612 UsingDecl *ConstructedBaseUsing = nullptr; 6613 6614 // Find the set of such base class subobjects and check that there's a 6615 // unique constructed subobject. 6616 for (auto *D : Shadow->redecls()) { 6617 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6618 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6619 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6620 6621 InheritedFromBases.insert( 6622 std::make_pair(DNominatedBase->getCanonicalDecl(), 6623 DShadow->getNominatedBaseClassShadowDecl())); 6624 if (DShadow->constructsVirtualBase()) 6625 InheritedFromBases.insert( 6626 std::make_pair(DConstructedBase->getCanonicalDecl(), 6627 DShadow->getConstructedBaseClassShadowDecl())); 6628 else 6629 assert(DNominatedBase == DConstructedBase); 6630 6631 // [class.inhctor.init]p2: 6632 // If the constructor was inherited from multiple base class subobjects 6633 // of type B, the program is ill-formed. 6634 if (!ConstructedBase) { 6635 ConstructedBase = DConstructedBase; 6636 ConstructedBaseUsing = D->getUsingDecl(); 6637 } else if (ConstructedBase != DConstructedBase && 6638 !Shadow->isInvalidDecl()) { 6639 if (!DiagnosedMultipleConstructedBases) { 6640 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6641 << Shadow->getTargetDecl(); 6642 S.Diag(ConstructedBaseUsing->getLocation(), 6643 diag::note_ambiguous_inherited_constructor_using) 6644 << ConstructedBase; 6645 DiagnosedMultipleConstructedBases = true; 6646 } 6647 S.Diag(D->getUsingDecl()->getLocation(), 6648 diag::note_ambiguous_inherited_constructor_using) 6649 << DConstructedBase; 6650 } 6651 } 6652 6653 if (DiagnosedMultipleConstructedBases) 6654 Shadow->setInvalidDecl(); 6655 } 6656 6657 /// Find the constructor to use for inherited construction of a base class, 6658 /// and whether that base class constructor inherits the constructor from a 6659 /// virtual base class (in which case it won't actually invoke it). 6660 std::pair<CXXConstructorDecl *, bool> 6661 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6662 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6663 if (It == InheritedFromBases.end()) 6664 return std::make_pair(nullptr, false); 6665 6666 // This is an intermediary class. 6667 if (It->second) 6668 return std::make_pair( 6669 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6670 It->second->constructsVirtualBase()); 6671 6672 // This is the base class from which the constructor was inherited. 6673 return std::make_pair(Ctor, false); 6674 } 6675 }; 6676 6677 /// Is the special member function which would be selected to perform the 6678 /// specified operation on the specified class type a constexpr constructor? 6679 static bool 6680 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6681 Sema::CXXSpecialMember CSM, unsigned Quals, 6682 bool ConstRHS, 6683 CXXConstructorDecl *InheritedCtor = nullptr, 6684 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6685 // If we're inheriting a constructor, see if we need to call it for this base 6686 // class. 6687 if (InheritedCtor) { 6688 assert(CSM == Sema::CXXDefaultConstructor); 6689 auto BaseCtor = 6690 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6691 if (BaseCtor) 6692 return BaseCtor->isConstexpr(); 6693 } 6694 6695 if (CSM == Sema::CXXDefaultConstructor) 6696 return ClassDecl->hasConstexprDefaultConstructor(); 6697 if (CSM == Sema::CXXDestructor) 6698 return ClassDecl->hasConstexprDestructor(); 6699 6700 Sema::SpecialMemberOverloadResult SMOR = 6701 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6702 if (!SMOR.getMethod()) 6703 // A constructor we wouldn't select can't be "involved in initializing" 6704 // anything. 6705 return true; 6706 return SMOR.getMethod()->isConstexpr(); 6707 } 6708 6709 /// Determine whether the specified special member function would be constexpr 6710 /// if it were implicitly defined. 6711 static bool defaultedSpecialMemberIsConstexpr( 6712 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6713 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6714 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6715 if (!S.getLangOpts().CPlusPlus11) 6716 return false; 6717 6718 // C++11 [dcl.constexpr]p4: 6719 // In the definition of a constexpr constructor [...] 6720 bool Ctor = true; 6721 switch (CSM) { 6722 case Sema::CXXDefaultConstructor: 6723 if (Inherited) 6724 break; 6725 // Since default constructor lookup is essentially trivial (and cannot 6726 // involve, for instance, template instantiation), we compute whether a 6727 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6728 // 6729 // This is important for performance; we need to know whether the default 6730 // constructor is constexpr to determine whether the type is a literal type. 6731 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6732 6733 case Sema::CXXCopyConstructor: 6734 case Sema::CXXMoveConstructor: 6735 // For copy or move constructors, we need to perform overload resolution. 6736 break; 6737 6738 case Sema::CXXCopyAssignment: 6739 case Sema::CXXMoveAssignment: 6740 if (!S.getLangOpts().CPlusPlus14) 6741 return false; 6742 // In C++1y, we need to perform overload resolution. 6743 Ctor = false; 6744 break; 6745 6746 case Sema::CXXDestructor: 6747 return ClassDecl->defaultedDestructorIsConstexpr(); 6748 6749 case Sema::CXXInvalid: 6750 return false; 6751 } 6752 6753 // -- if the class is a non-empty union, or for each non-empty anonymous 6754 // union member of a non-union class, exactly one non-static data member 6755 // shall be initialized; [DR1359] 6756 // 6757 // If we squint, this is guaranteed, since exactly one non-static data member 6758 // will be initialized (if the constructor isn't deleted), we just don't know 6759 // which one. 6760 if (Ctor && ClassDecl->isUnion()) 6761 return CSM == Sema::CXXDefaultConstructor 6762 ? ClassDecl->hasInClassInitializer() || 6763 !ClassDecl->hasVariantMembers() 6764 : true; 6765 6766 // -- the class shall not have any virtual base classes; 6767 if (Ctor && ClassDecl->getNumVBases()) 6768 return false; 6769 6770 // C++1y [class.copy]p26: 6771 // -- [the class] is a literal type, and 6772 if (!Ctor && !ClassDecl->isLiteral()) 6773 return false; 6774 6775 // -- every constructor involved in initializing [...] base class 6776 // sub-objects shall be a constexpr constructor; 6777 // -- the assignment operator selected to copy/move each direct base 6778 // class is a constexpr function, and 6779 for (const auto &B : ClassDecl->bases()) { 6780 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6781 if (!BaseType) continue; 6782 6783 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6784 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6785 InheritedCtor, Inherited)) 6786 return false; 6787 } 6788 6789 // -- every constructor involved in initializing non-static data members 6790 // [...] shall be a constexpr constructor; 6791 // -- every non-static data member and base class sub-object shall be 6792 // initialized 6793 // -- for each non-static data member of X that is of class type (or array 6794 // thereof), the assignment operator selected to copy/move that member is 6795 // a constexpr function 6796 for (const auto *F : ClassDecl->fields()) { 6797 if (F->isInvalidDecl()) 6798 continue; 6799 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6800 continue; 6801 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6802 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6803 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6804 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6805 BaseType.getCVRQualifiers(), 6806 ConstArg && !F->isMutable())) 6807 return false; 6808 } else if (CSM == Sema::CXXDefaultConstructor) { 6809 return false; 6810 } 6811 } 6812 6813 // All OK, it's constexpr! 6814 return true; 6815 } 6816 6817 namespace { 6818 /// RAII object to register a defaulted function as having its exception 6819 /// specification computed. 6820 struct ComputingExceptionSpec { 6821 Sema &S; 6822 6823 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 6824 : S(S) { 6825 Sema::CodeSynthesisContext Ctx; 6826 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 6827 Ctx.PointOfInstantiation = Loc; 6828 Ctx.Entity = FD; 6829 S.pushCodeSynthesisContext(Ctx); 6830 } 6831 ~ComputingExceptionSpec() { 6832 S.popCodeSynthesisContext(); 6833 } 6834 }; 6835 } 6836 6837 static Sema::ImplicitExceptionSpecification 6838 ComputeDefaultedSpecialMemberExceptionSpec( 6839 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6840 Sema::InheritedConstructorInfo *ICI); 6841 6842 static Sema::ImplicitExceptionSpecification 6843 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 6844 FunctionDecl *FD, 6845 Sema::DefaultedComparisonKind DCK); 6846 6847 static Sema::ImplicitExceptionSpecification 6848 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 6849 auto DFK = S.getDefaultedFunctionKind(FD); 6850 if (DFK.isSpecialMember()) 6851 return ComputeDefaultedSpecialMemberExceptionSpec( 6852 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 6853 if (DFK.isComparison()) 6854 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 6855 DFK.asComparison()); 6856 6857 auto *CD = cast<CXXConstructorDecl>(FD); 6858 assert(CD->getInheritedConstructor() && 6859 "only defaulted functions and inherited constructors have implicit " 6860 "exception specs"); 6861 Sema::InheritedConstructorInfo ICI( 6862 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6863 return ComputeDefaultedSpecialMemberExceptionSpec( 6864 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6865 } 6866 6867 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6868 CXXMethodDecl *MD) { 6869 FunctionProtoType::ExtProtoInfo EPI; 6870 6871 // Build an exception specification pointing back at this member. 6872 EPI.ExceptionSpec.Type = EST_Unevaluated; 6873 EPI.ExceptionSpec.SourceDecl = MD; 6874 6875 // Set the calling convention to the default for C++ instance methods. 6876 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6877 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6878 /*IsCXXMethod=*/true)); 6879 return EPI; 6880 } 6881 6882 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 6883 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 6884 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6885 return; 6886 6887 // Evaluate the exception specification. 6888 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 6889 auto ESI = IES.getExceptionSpec(); 6890 6891 // Update the type of the special member to use it. 6892 UpdateExceptionSpec(FD, ESI); 6893 } 6894 6895 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 6896 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 6897 6898 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 6899 if (!DefKind) { 6900 assert(FD->getDeclContext()->isDependentContext()); 6901 return; 6902 } 6903 6904 if (DefKind.isSpecialMember() 6905 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 6906 DefKind.asSpecialMember()) 6907 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 6908 FD->setInvalidDecl(); 6909 } 6910 6911 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 6912 CXXSpecialMember CSM) { 6913 CXXRecordDecl *RD = MD->getParent(); 6914 6915 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6916 "not an explicitly-defaulted special member"); 6917 6918 // Defer all checking for special members of a dependent type. 6919 if (RD->isDependentType()) 6920 return false; 6921 6922 // Whether this was the first-declared instance of the constructor. 6923 // This affects whether we implicitly add an exception spec and constexpr. 6924 bool First = MD == MD->getCanonicalDecl(); 6925 6926 bool HadError = false; 6927 6928 // C++11 [dcl.fct.def.default]p1: 6929 // A function that is explicitly defaulted shall 6930 // -- be a special member function [...] (checked elsewhere), 6931 // -- have the same type (except for ref-qualifiers, and except that a 6932 // copy operation can take a non-const reference) as an implicit 6933 // declaration, and 6934 // -- not have default arguments. 6935 // C++2a changes the second bullet to instead delete the function if it's 6936 // defaulted on its first declaration, unless it's "an assignment operator, 6937 // and its return type differs or its parameter type is not a reference". 6938 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6939 bool ShouldDeleteForTypeMismatch = false; 6940 unsigned ExpectedParams = 1; 6941 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6942 ExpectedParams = 0; 6943 if (MD->getNumParams() != ExpectedParams) { 6944 // This checks for default arguments: a copy or move constructor with a 6945 // default argument is classified as a default constructor, and assignment 6946 // operations and destructors can't have default arguments. 6947 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6948 << CSM << MD->getSourceRange(); 6949 HadError = true; 6950 } else if (MD->isVariadic()) { 6951 if (DeleteOnTypeMismatch) 6952 ShouldDeleteForTypeMismatch = true; 6953 else { 6954 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6955 << CSM << MD->getSourceRange(); 6956 HadError = true; 6957 } 6958 } 6959 6960 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6961 6962 bool CanHaveConstParam = false; 6963 if (CSM == CXXCopyConstructor) 6964 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6965 else if (CSM == CXXCopyAssignment) 6966 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6967 6968 QualType ReturnType = Context.VoidTy; 6969 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6970 // Check for return type matching. 6971 ReturnType = Type->getReturnType(); 6972 6973 QualType DeclType = Context.getTypeDeclType(RD); 6974 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 6975 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6976 6977 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6978 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6979 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6980 HadError = true; 6981 } 6982 6983 // A defaulted special member cannot have cv-qualifiers. 6984 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 6985 if (DeleteOnTypeMismatch) 6986 ShouldDeleteForTypeMismatch = true; 6987 else { 6988 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6989 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6990 HadError = true; 6991 } 6992 } 6993 } 6994 6995 // Check for parameter type matching. 6996 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6997 bool HasConstParam = false; 6998 if (ExpectedParams && ArgType->isReferenceType()) { 6999 // Argument must be reference to possibly-const T. 7000 QualType ReferentType = ArgType->getPointeeType(); 7001 HasConstParam = ReferentType.isConstQualified(); 7002 7003 if (ReferentType.isVolatileQualified()) { 7004 if (DeleteOnTypeMismatch) 7005 ShouldDeleteForTypeMismatch = true; 7006 else { 7007 Diag(MD->getLocation(), 7008 diag::err_defaulted_special_member_volatile_param) << CSM; 7009 HadError = true; 7010 } 7011 } 7012 7013 if (HasConstParam && !CanHaveConstParam) { 7014 if (DeleteOnTypeMismatch) 7015 ShouldDeleteForTypeMismatch = true; 7016 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7017 Diag(MD->getLocation(), 7018 diag::err_defaulted_special_member_copy_const_param) 7019 << (CSM == CXXCopyAssignment); 7020 // FIXME: Explain why this special member can't be const. 7021 HadError = true; 7022 } else { 7023 Diag(MD->getLocation(), 7024 diag::err_defaulted_special_member_move_const_param) 7025 << (CSM == CXXMoveAssignment); 7026 HadError = true; 7027 } 7028 } 7029 } else if (ExpectedParams) { 7030 // A copy assignment operator can take its argument by value, but a 7031 // defaulted one cannot. 7032 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7033 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7034 HadError = true; 7035 } 7036 7037 // C++11 [dcl.fct.def.default]p2: 7038 // An explicitly-defaulted function may be declared constexpr only if it 7039 // would have been implicitly declared as constexpr, 7040 // Do not apply this rule to members of class templates, since core issue 1358 7041 // makes such functions always instantiate to constexpr functions. For 7042 // functions which cannot be constexpr (for non-constructors in C++11 and for 7043 // destructors in C++14 and C++17), this is checked elsewhere. 7044 // 7045 // FIXME: This should not apply if the member is deleted. 7046 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7047 HasConstParam); 7048 if ((getLangOpts().CPlusPlus2a || 7049 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7050 : isa<CXXConstructorDecl>(MD))) && 7051 MD->isConstexpr() && !Constexpr && 7052 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7053 Diag(MD->getBeginLoc(), MD->isConsteval() 7054 ? diag::err_incorrect_defaulted_consteval 7055 : diag::err_incorrect_defaulted_constexpr) 7056 << CSM; 7057 // FIXME: Explain why the special member can't be constexpr. 7058 HadError = true; 7059 } 7060 7061 if (First) { 7062 // C++2a [dcl.fct.def.default]p3: 7063 // If a function is explicitly defaulted on its first declaration, it is 7064 // implicitly considered to be constexpr if the implicit declaration 7065 // would be. 7066 MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified); 7067 7068 if (!Type->hasExceptionSpec()) { 7069 // C++2a [except.spec]p3: 7070 // If a declaration of a function does not have a noexcept-specifier 7071 // [and] is defaulted on its first declaration, [...] the exception 7072 // specification is as specified below 7073 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7074 EPI.ExceptionSpec.Type = EST_Unevaluated; 7075 EPI.ExceptionSpec.SourceDecl = MD; 7076 MD->setType(Context.getFunctionType(ReturnType, 7077 llvm::makeArrayRef(&ArgType, 7078 ExpectedParams), 7079 EPI)); 7080 } 7081 } 7082 7083 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7084 if (First) { 7085 SetDeclDeleted(MD, MD->getLocation()); 7086 if (!inTemplateInstantiation() && !HadError) { 7087 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7088 if (ShouldDeleteForTypeMismatch) { 7089 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7090 } else { 7091 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7092 } 7093 } 7094 if (ShouldDeleteForTypeMismatch && !HadError) { 7095 Diag(MD->getLocation(), 7096 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7097 } 7098 } else { 7099 // C++11 [dcl.fct.def.default]p4: 7100 // [For a] user-provided explicitly-defaulted function [...] if such a 7101 // function is implicitly defined as deleted, the program is ill-formed. 7102 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7103 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7104 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7105 HadError = true; 7106 } 7107 } 7108 7109 return HadError; 7110 } 7111 7112 namespace { 7113 /// Helper class for building and checking a defaulted comparison. 7114 /// 7115 /// Defaulted functions are built in two phases: 7116 /// 7117 /// * First, the set of operations that the function will perform are 7118 /// identified, and some of them are checked. If any of the checked 7119 /// operations is invalid in certain ways, the comparison function is 7120 /// defined as deleted and no body is built. 7121 /// * Then, if the function is not defined as deleted, the body is built. 7122 /// 7123 /// This is accomplished by performing two visitation steps over the eventual 7124 /// body of the function. 7125 template<typename Derived, typename ResultList, typename Result, 7126 typename Subobject> 7127 class DefaultedComparisonVisitor { 7128 public: 7129 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7130 7131 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7132 DefaultedComparisonKind DCK) 7133 : S(S), RD(RD), FD(FD), DCK(DCK) { 7134 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7135 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7136 // UnresolvedSet to avoid this copy. 7137 Fns.assign(Info->getUnqualifiedLookups().begin(), 7138 Info->getUnqualifiedLookups().end()); 7139 } 7140 } 7141 7142 ResultList visit() { 7143 // The type of an lvalue naming a parameter of this function. 7144 QualType ParamLvalType = 7145 FD->getParamDecl(0)->getType().getNonReferenceType(); 7146 7147 ResultList Results; 7148 7149 switch (DCK) { 7150 case DefaultedComparisonKind::None: 7151 llvm_unreachable("not a defaulted comparison"); 7152 7153 case DefaultedComparisonKind::Equal: 7154 case DefaultedComparisonKind::ThreeWay: 7155 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7156 return Results; 7157 7158 case DefaultedComparisonKind::NotEqual: 7159 case DefaultedComparisonKind::Relational: 7160 Results.add(getDerived().visitExpandedSubobject( 7161 ParamLvalType, getDerived().getCompleteObject())); 7162 return Results; 7163 } 7164 llvm_unreachable(""); 7165 } 7166 7167 protected: 7168 Derived &getDerived() { return static_cast<Derived&>(*this); } 7169 7170 /// Visit the expanded list of subobjects of the given type, as specified in 7171 /// C++2a [class.compare.default]. 7172 /// 7173 /// \return \c true if the ResultList object said we're done, \c false if not. 7174 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7175 Qualifiers Quals) { 7176 // C++2a [class.compare.default]p4: 7177 // The direct base class subobjects of C 7178 for (CXXBaseSpecifier &Base : Record->bases()) 7179 if (Results.add(getDerived().visitSubobject( 7180 S.Context.getQualifiedType(Base.getType(), Quals), 7181 getDerived().getBase(&Base)))) 7182 return true; 7183 7184 // followed by the non-static data members of C 7185 for (FieldDecl *Field : Record->fields()) { 7186 // Recursively expand anonymous structs. 7187 if (Field->isAnonymousStructOrUnion()) { 7188 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7189 Quals)) 7190 return true; 7191 continue; 7192 } 7193 7194 // Figure out the type of an lvalue denoting this field. 7195 Qualifiers FieldQuals = Quals; 7196 if (Field->isMutable()) 7197 FieldQuals.removeConst(); 7198 QualType FieldType = 7199 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7200 7201 if (Results.add(getDerived().visitSubobject( 7202 FieldType, getDerived().getField(Field)))) 7203 return true; 7204 } 7205 7206 // form a list of subobjects. 7207 return false; 7208 } 7209 7210 Result visitSubobject(QualType Type, Subobject Subobj) { 7211 // In that list, any subobject of array type is recursively expanded 7212 const ArrayType *AT = S.Context.getAsArrayType(Type); 7213 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7214 return getDerived().visitSubobjectArray(CAT->getElementType(), 7215 CAT->getSize(), Subobj); 7216 return getDerived().visitExpandedSubobject(Type, Subobj); 7217 } 7218 7219 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7220 Subobject Subobj) { 7221 return getDerived().visitSubobject(Type, Subobj); 7222 } 7223 7224 protected: 7225 Sema &S; 7226 CXXRecordDecl *RD; 7227 FunctionDecl *FD; 7228 DefaultedComparisonKind DCK; 7229 UnresolvedSet<16> Fns; 7230 }; 7231 7232 /// Information about a defaulted comparison, as determined by 7233 /// DefaultedComparisonAnalyzer. 7234 struct DefaultedComparisonInfo { 7235 bool Deleted = false; 7236 bool Constexpr = true; 7237 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7238 7239 static DefaultedComparisonInfo deleted() { 7240 DefaultedComparisonInfo Deleted; 7241 Deleted.Deleted = true; 7242 return Deleted; 7243 } 7244 7245 bool add(const DefaultedComparisonInfo &R) { 7246 Deleted |= R.Deleted; 7247 Constexpr &= R.Constexpr; 7248 Category = commonComparisonType(Category, R.Category); 7249 return Deleted; 7250 } 7251 }; 7252 7253 /// An element in the expanded list of subobjects of a defaulted comparison, as 7254 /// specified in C++2a [class.compare.default]p4. 7255 struct DefaultedComparisonSubobject { 7256 enum { CompleteObject, Member, Base } Kind; 7257 NamedDecl *Decl; 7258 SourceLocation Loc; 7259 }; 7260 7261 /// A visitor over the notional body of a defaulted comparison that determines 7262 /// whether that body would be deleted or constexpr. 7263 class DefaultedComparisonAnalyzer 7264 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7265 DefaultedComparisonInfo, 7266 DefaultedComparisonInfo, 7267 DefaultedComparisonSubobject> { 7268 public: 7269 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7270 7271 private: 7272 DiagnosticKind Diagnose; 7273 7274 public: 7275 using Base = DefaultedComparisonVisitor; 7276 using Result = DefaultedComparisonInfo; 7277 using Subobject = DefaultedComparisonSubobject; 7278 7279 friend Base; 7280 7281 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7282 DefaultedComparisonKind DCK, 7283 DiagnosticKind Diagnose = NoDiagnostics) 7284 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7285 7286 Result visit() { 7287 if ((DCK == DefaultedComparisonKind::Equal || 7288 DCK == DefaultedComparisonKind::ThreeWay) && 7289 RD->hasVariantMembers()) { 7290 // C++2a [class.compare.default]p2 [P2002R0]: 7291 // A defaulted comparison operator function for class C is defined as 7292 // deleted if [...] C has variant members. 7293 if (Diagnose == ExplainDeleted) { 7294 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7295 << FD << RD->isUnion() << RD; 7296 } 7297 return Result::deleted(); 7298 } 7299 7300 return Base::visit(); 7301 } 7302 7303 private: 7304 Subobject getCompleteObject() { 7305 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7306 } 7307 7308 Subobject getBase(CXXBaseSpecifier *Base) { 7309 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7310 Base->getBaseTypeLoc()}; 7311 } 7312 7313 Subobject getField(FieldDecl *Field) { 7314 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7315 } 7316 7317 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7318 // C++2a [class.compare.default]p2 [P2002R0]: 7319 // A defaulted <=> or == operator function for class C is defined as 7320 // deleted if any non-static data member of C is of reference type 7321 if (Type->isReferenceType()) { 7322 if (Diagnose == ExplainDeleted) { 7323 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7324 << FD << RD; 7325 } 7326 return Result::deleted(); 7327 } 7328 7329 // [...] Let xi be an lvalue denoting the ith element [...] 7330 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7331 Expr *Args[] = {&Xi, &Xi}; 7332 7333 // All operators start by trying to apply that same operator recursively. 7334 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7335 assert(OO != OO_None && "not an overloaded operator!"); 7336 return visitBinaryOperator(OO, Args, Subobj); 7337 } 7338 7339 Result 7340 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7341 Subobject Subobj, 7342 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7343 // Note that there is no need to consider rewritten candidates here if 7344 // we've already found there is no viable 'operator<=>' candidate (and are 7345 // considering synthesizing a '<=>' from '==' and '<'). 7346 OverloadCandidateSet CandidateSet( 7347 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7348 OverloadCandidateSet::OperatorRewriteInfo( 7349 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7350 7351 /// C++2a [class.compare.default]p1 [P2002R0]: 7352 /// [...] the defaulted function itself is never a candidate for overload 7353 /// resolution [...] 7354 CandidateSet.exclude(FD); 7355 7356 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7357 7358 Result R; 7359 7360 OverloadCandidateSet::iterator Best; 7361 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7362 case OR_Success: { 7363 // C++2a [class.compare.secondary]p2 [P2002R0]: 7364 // The operator function [...] is defined as deleted if [...] the 7365 // candidate selected by overload resolution is not a rewritten 7366 // candidate. 7367 if ((DCK == DefaultedComparisonKind::NotEqual || 7368 DCK == DefaultedComparisonKind::Relational) && 7369 !Best->RewriteKind) { 7370 if (Diagnose == ExplainDeleted) { 7371 S.Diag(Best->Function->getLocation(), 7372 diag::note_defaulted_comparison_not_rewritten_callee) 7373 << FD; 7374 } 7375 return Result::deleted(); 7376 } 7377 7378 // Throughout C++2a [class.compare]: if overload resolution does not 7379 // result in a usable function, the candidate function is defined as 7380 // deleted. This requires that we selected an accessible function. 7381 // 7382 // Note that this only considers the access of the function when named 7383 // within the type of the subobject, and not the access path for any 7384 // derived-to-base conversion. 7385 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7386 if (ArgClass && Best->FoundDecl.getDecl() && 7387 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7388 QualType ObjectType = Subobj.Kind == Subobject::Member 7389 ? Args[0]->getType() 7390 : S.Context.getRecordType(RD); 7391 if (!S.isMemberAccessibleForDeletion( 7392 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7393 Diagnose == ExplainDeleted 7394 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7395 << FD << Subobj.Kind << Subobj.Decl 7396 : S.PDiag())) 7397 return Result::deleted(); 7398 } 7399 7400 // C++2a [class.compare.default]p3 [P2002R0]: 7401 // A defaulted comparison function is constexpr-compatible if [...] 7402 // no overlod resolution performed [...] results in a non-constexpr 7403 // function. 7404 if (FunctionDecl *BestFD = Best->Function) { 7405 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7406 // If it's not constexpr, explain why not. 7407 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7408 if (Subobj.Kind != Subobject::CompleteObject) 7409 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7410 << Subobj.Kind << Subobj.Decl; 7411 S.Diag(BestFD->getLocation(), 7412 diag::note_defaulted_comparison_not_constexpr_here); 7413 // Bail out after explaining; we don't want any more notes. 7414 return Result::deleted(); 7415 } 7416 R.Constexpr &= BestFD->isConstexpr(); 7417 } 7418 7419 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7420 if (auto *BestFD = Best->Function) { 7421 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7422 BestFD->getCallResultType())) { 7423 R.Category = Info->Kind; 7424 } else { 7425 if (Diagnose == ExplainDeleted) { 7426 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7427 << Subobj.Kind << Subobj.Decl 7428 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7429 S.Diag(BestFD->getLocation(), 7430 diag::note_defaulted_comparison_cannot_deduce_callee) 7431 << Subobj.Kind << Subobj.Decl; 7432 } 7433 return Result::deleted(); 7434 } 7435 } else { 7436 Optional<ComparisonCategoryType> Cat = 7437 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7438 assert(Cat && "no category for builtin comparison?"); 7439 R.Category = *Cat; 7440 } 7441 } 7442 7443 // Note that we might be rewriting to a different operator. That call is 7444 // not considered until we come to actually build the comparison function. 7445 break; 7446 } 7447 7448 case OR_Ambiguous: 7449 if (Diagnose == ExplainDeleted) { 7450 unsigned Kind = 0; 7451 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7452 Kind = OO == OO_EqualEqual ? 1 : 2; 7453 CandidateSet.NoteCandidates( 7454 PartialDiagnosticAt( 7455 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7456 << FD << Kind << Subobj.Kind << Subobj.Decl), 7457 S, OCD_AmbiguousCandidates, Args); 7458 } 7459 R = Result::deleted(); 7460 break; 7461 7462 case OR_Deleted: 7463 if (Diagnose == ExplainDeleted) { 7464 if ((DCK == DefaultedComparisonKind::NotEqual || 7465 DCK == DefaultedComparisonKind::Relational) && 7466 !Best->RewriteKind) { 7467 S.Diag(Best->Function->getLocation(), 7468 diag::note_defaulted_comparison_not_rewritten_callee) 7469 << FD; 7470 } else { 7471 S.Diag(Subobj.Loc, 7472 diag::note_defaulted_comparison_calls_deleted) 7473 << FD << Subobj.Kind << Subobj.Decl; 7474 S.NoteDeletedFunction(Best->Function); 7475 } 7476 } 7477 R = Result::deleted(); 7478 break; 7479 7480 case OR_No_Viable_Function: 7481 // If there's no usable candidate, we're done unless we can rewrite a 7482 // '<=>' in terms of '==' and '<'. 7483 if (OO == OO_Spaceship && 7484 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7485 // For any kind of comparison category return type, we need a usable 7486 // '==' and a usable '<'. 7487 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7488 &CandidateSet))) 7489 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7490 break; 7491 } 7492 7493 if (Diagnose == ExplainDeleted) { 7494 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7495 << FD << Subobj.Kind << Subobj.Decl; 7496 7497 // For a three-way comparison, list both the candidates for the 7498 // original operator and the candidates for the synthesized operator. 7499 if (SpaceshipCandidates) { 7500 SpaceshipCandidates->NoteCandidates( 7501 S, Args, 7502 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7503 Args, FD->getLocation())); 7504 S.Diag(Subobj.Loc, 7505 diag::note_defaulted_comparison_no_viable_function_synthesized) 7506 << (OO == OO_EqualEqual ? 0 : 1); 7507 } 7508 7509 CandidateSet.NoteCandidates( 7510 S, Args, 7511 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7512 FD->getLocation())); 7513 } 7514 R = Result::deleted(); 7515 break; 7516 } 7517 7518 return R; 7519 } 7520 }; 7521 7522 /// A list of statements. 7523 struct StmtListResult { 7524 bool IsInvalid = false; 7525 llvm::SmallVector<Stmt*, 16> Stmts; 7526 7527 bool add(const StmtResult &S) { 7528 IsInvalid |= S.isInvalid(); 7529 if (IsInvalid) 7530 return true; 7531 Stmts.push_back(S.get()); 7532 return false; 7533 } 7534 }; 7535 7536 /// A visitor over the notional body of a defaulted comparison that synthesizes 7537 /// the actual body. 7538 class DefaultedComparisonSynthesizer 7539 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7540 StmtListResult, StmtResult, 7541 std::pair<ExprResult, ExprResult>> { 7542 SourceLocation Loc; 7543 unsigned ArrayDepth = 0; 7544 7545 public: 7546 using Base = DefaultedComparisonVisitor; 7547 using ExprPair = std::pair<ExprResult, ExprResult>; 7548 7549 friend Base; 7550 7551 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7552 DefaultedComparisonKind DCK, 7553 SourceLocation BodyLoc) 7554 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7555 7556 /// Build a suitable function body for this defaulted comparison operator. 7557 StmtResult build() { 7558 Sema::CompoundScopeRAII CompoundScope(S); 7559 7560 StmtListResult Stmts = visit(); 7561 if (Stmts.IsInvalid) 7562 return StmtError(); 7563 7564 ExprResult RetVal; 7565 switch (DCK) { 7566 case DefaultedComparisonKind::None: 7567 llvm_unreachable("not a defaulted comparison"); 7568 7569 case DefaultedComparisonKind::Equal: { 7570 // C++2a [class.eq]p3: 7571 // [...] compar[e] the corresponding elements [...] until the first 7572 // index i where xi == yi yields [...] false. If no such index exists, 7573 // V is true. Otherwise, V is false. 7574 // 7575 // Join the comparisons with '&&'s and return the result. Use a right 7576 // fold (traversing the conditions right-to-left), because that 7577 // short-circuits more naturally. 7578 auto OldStmts = std::move(Stmts.Stmts); 7579 Stmts.Stmts.clear(); 7580 ExprResult CmpSoFar; 7581 // Finish a particular comparison chain. 7582 auto FinishCmp = [&] { 7583 if (Expr *Prior = CmpSoFar.get()) { 7584 // Convert the last expression to 'return ...;' 7585 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7586 RetVal = CmpSoFar; 7587 // Convert any prior comparison to 'if (!(...)) return false;' 7588 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7589 return true; 7590 CmpSoFar = ExprResult(); 7591 } 7592 return false; 7593 }; 7594 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7595 Expr *E = dyn_cast<Expr>(EAsStmt); 7596 if (!E) { 7597 // Found an array comparison. 7598 if (FinishCmp() || Stmts.add(EAsStmt)) 7599 return StmtError(); 7600 continue; 7601 } 7602 7603 if (CmpSoFar.isUnset()) { 7604 CmpSoFar = E; 7605 continue; 7606 } 7607 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7608 if (CmpSoFar.isInvalid()) 7609 return StmtError(); 7610 } 7611 if (FinishCmp()) 7612 return StmtError(); 7613 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7614 // If no such index exists, V is true. 7615 if (RetVal.isUnset()) 7616 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7617 break; 7618 } 7619 7620 case DefaultedComparisonKind::ThreeWay: { 7621 // Per C++2a [class.spaceship]p3, as a fallback add: 7622 // return static_cast<R>(std::strong_ordering::equal); 7623 QualType StrongOrdering = S.CheckComparisonCategoryType( 7624 ComparisonCategoryType::StrongOrdering, Loc, 7625 Sema::ComparisonCategoryUsage::DefaultedOperator); 7626 if (StrongOrdering.isNull()) 7627 return StmtError(); 7628 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7629 .getValueInfo(ComparisonCategoryResult::Equal) 7630 ->VD; 7631 RetVal = getDecl(EqualVD); 7632 if (RetVal.isInvalid()) 7633 return StmtError(); 7634 RetVal = buildStaticCastToR(RetVal.get()); 7635 break; 7636 } 7637 7638 case DefaultedComparisonKind::NotEqual: 7639 case DefaultedComparisonKind::Relational: 7640 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 7641 break; 7642 } 7643 7644 // Build the final return statement. 7645 if (RetVal.isInvalid()) 7646 return StmtError(); 7647 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 7648 if (ReturnStmt.isInvalid()) 7649 return StmtError(); 7650 Stmts.Stmts.push_back(ReturnStmt.get()); 7651 7652 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 7653 } 7654 7655 private: 7656 ExprResult getDecl(ValueDecl *VD) { 7657 return S.BuildDeclarationNameExpr( 7658 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 7659 } 7660 7661 ExprResult getParam(unsigned I) { 7662 ParmVarDecl *PD = FD->getParamDecl(I); 7663 return getDecl(PD); 7664 } 7665 7666 ExprPair getCompleteObject() { 7667 unsigned Param = 0; 7668 ExprResult LHS; 7669 if (isa<CXXMethodDecl>(FD)) { 7670 // LHS is '*this'. 7671 LHS = S.ActOnCXXThis(Loc); 7672 if (!LHS.isInvalid()) 7673 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 7674 } else { 7675 LHS = getParam(Param++); 7676 } 7677 ExprResult RHS = getParam(Param++); 7678 assert(Param == FD->getNumParams()); 7679 return {LHS, RHS}; 7680 } 7681 7682 ExprPair getBase(CXXBaseSpecifier *Base) { 7683 ExprPair Obj = getCompleteObject(); 7684 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7685 return {ExprError(), ExprError()}; 7686 CXXCastPath Path = {Base}; 7687 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 7688 CK_DerivedToBase, VK_LValue, &Path), 7689 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 7690 CK_DerivedToBase, VK_LValue, &Path)}; 7691 } 7692 7693 ExprPair getField(FieldDecl *Field) { 7694 ExprPair Obj = getCompleteObject(); 7695 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7696 return {ExprError(), ExprError()}; 7697 7698 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 7699 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 7700 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 7701 CXXScopeSpec(), Field, Found, NameInfo), 7702 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 7703 CXXScopeSpec(), Field, Found, NameInfo)}; 7704 } 7705 7706 // FIXME: When expanding a subobject, register a note in the code synthesis 7707 // stack to say which subobject we're comparing. 7708 7709 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 7710 if (Cond.isInvalid()) 7711 return StmtError(); 7712 7713 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 7714 if (NotCond.isInvalid()) 7715 return StmtError(); 7716 7717 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 7718 assert(!False.isInvalid() && "should never fail"); 7719 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 7720 if (ReturnFalse.isInvalid()) 7721 return StmtError(); 7722 7723 return S.ActOnIfStmt(Loc, false, nullptr, 7724 S.ActOnCondition(nullptr, Loc, NotCond.get(), 7725 Sema::ConditionKind::Boolean), 7726 ReturnFalse.get(), SourceLocation(), nullptr); 7727 } 7728 7729 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 7730 ExprPair Subobj) { 7731 QualType SizeType = S.Context.getSizeType(); 7732 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 7733 7734 // Build 'size_t i$n = 0'. 7735 IdentifierInfo *IterationVarName = nullptr; 7736 { 7737 SmallString<8> Str; 7738 llvm::raw_svector_ostream OS(Str); 7739 OS << "i" << ArrayDepth; 7740 IterationVarName = &S.Context.Idents.get(OS.str()); 7741 } 7742 VarDecl *IterationVar = VarDecl::Create( 7743 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 7744 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 7745 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7746 IterationVar->setInit( 7747 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7748 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 7749 7750 auto IterRef = [&] { 7751 ExprResult Ref = S.BuildDeclarationNameExpr( 7752 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 7753 IterationVar); 7754 assert(!Ref.isInvalid() && "can't reference our own variable?"); 7755 return Ref.get(); 7756 }; 7757 7758 // Build 'i$n != Size'. 7759 ExprResult Cond = S.CreateBuiltinBinOp( 7760 Loc, BO_NE, IterRef(), 7761 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 7762 assert(!Cond.isInvalid() && "should never fail"); 7763 7764 // Build '++i$n'. 7765 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 7766 assert(!Inc.isInvalid() && "should never fail"); 7767 7768 // Build 'a[i$n]' and 'b[i$n]'. 7769 auto Index = [&](ExprResult E) { 7770 if (E.isInvalid()) 7771 return ExprError(); 7772 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 7773 }; 7774 Subobj.first = Index(Subobj.first); 7775 Subobj.second = Index(Subobj.second); 7776 7777 // Compare the array elements. 7778 ++ArrayDepth; 7779 StmtResult Substmt = visitSubobject(Type, Subobj); 7780 --ArrayDepth; 7781 7782 if (Substmt.isInvalid()) 7783 return StmtError(); 7784 7785 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 7786 // For outer levels or for an 'operator<=>' we already have a suitable 7787 // statement that returns as necessary. 7788 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 7789 assert(DCK == DefaultedComparisonKind::Equal && 7790 "should have non-expression statement"); 7791 Substmt = buildIfNotCondReturnFalse(ElemCmp); 7792 if (Substmt.isInvalid()) 7793 return StmtError(); 7794 } 7795 7796 // Build 'for (...) ...' 7797 return S.ActOnForStmt(Loc, Loc, Init, 7798 S.ActOnCondition(nullptr, Loc, Cond.get(), 7799 Sema::ConditionKind::Boolean), 7800 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 7801 Substmt.get()); 7802 } 7803 7804 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 7805 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7806 return StmtError(); 7807 7808 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7809 ExprResult Op = S.CreateOverloadedBinOp( 7810 Loc, BinaryOperator::getOverloadedOpcode(OO), Fns, 7811 Obj.first.get(), Obj.second.get(), /*PerformADL=*/true, 7812 /*AllowRewrittenCandidates=*/true, FD); 7813 if (Op.isInvalid()) 7814 return StmtError(); 7815 7816 switch (DCK) { 7817 case DefaultedComparisonKind::None: 7818 llvm_unreachable("not a defaulted comparison"); 7819 7820 case DefaultedComparisonKind::Equal: 7821 // Per C++2a [class.eq]p2, each comparison is individually contextually 7822 // converted to bool. 7823 Op = S.PerformContextuallyConvertToBool(Op.get()); 7824 if (Op.isInvalid()) 7825 return StmtError(); 7826 return Op.get(); 7827 7828 case DefaultedComparisonKind::ThreeWay: { 7829 // Per C++2a [class.spaceship]p3, form: 7830 // if (R cmp = static_cast<R>(op); cmp != 0) 7831 // return cmp; 7832 QualType R = FD->getReturnType(); 7833 Op = buildStaticCastToR(Op.get()); 7834 if (Op.isInvalid()) 7835 return StmtError(); 7836 7837 // R cmp = ...; 7838 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 7839 VarDecl *VD = 7840 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 7841 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 7842 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 7843 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 7844 7845 // cmp != 0 7846 ExprResult VDRef = getDecl(VD); 7847 if (VDRef.isInvalid()) 7848 return StmtError(); 7849 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 7850 Expr *Zero = 7851 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 7852 ExprResult Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), 7853 Zero, true, true, FD); 7854 if (Comp.isInvalid()) 7855 return StmtError(); 7856 Sema::ConditionResult Cond = S.ActOnCondition( 7857 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 7858 if (Cond.isInvalid()) 7859 return StmtError(); 7860 7861 // return cmp; 7862 VDRef = getDecl(VD); 7863 if (VDRef.isInvalid()) 7864 return StmtError(); 7865 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 7866 if (ReturnStmt.isInvalid()) 7867 return StmtError(); 7868 7869 // if (...) 7870 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond, 7871 ReturnStmt.get(), /*ElseLoc=*/SourceLocation(), 7872 /*Else=*/nullptr); 7873 } 7874 7875 case DefaultedComparisonKind::NotEqual: 7876 case DefaultedComparisonKind::Relational: 7877 // C++2a [class.compare.secondary]p2: 7878 // Otherwise, the operator function yields x @ y. 7879 return Op.get(); 7880 } 7881 llvm_unreachable(""); 7882 } 7883 7884 /// Build "static_cast<R>(E)". 7885 ExprResult buildStaticCastToR(Expr *E) { 7886 QualType R = FD->getReturnType(); 7887 assert(!R->isUndeducedType() && "type should have been deduced already"); 7888 7889 // Don't bother forming a no-op cast in the common case. 7890 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 7891 return E; 7892 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 7893 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 7894 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 7895 } 7896 }; 7897 } 7898 7899 /// Perform the unqualified lookups that might be needed to form a defaulted 7900 /// comparison function for the given operator. 7901 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 7902 UnresolvedSetImpl &Operators, 7903 OverloadedOperatorKind Op) { 7904 auto Lookup = [&](OverloadedOperatorKind OO) { 7905 Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators); 7906 }; 7907 7908 // Every defaulted operator looks up itself. 7909 Lookup(Op); 7910 // ... and the rewritten form of itself, if any. 7911 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 7912 Lookup(ExtraOp); 7913 7914 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 7915 // synthesize a three-way comparison from '<' and '=='. In a dependent 7916 // context, we also need to look up '==' in case we implicitly declare a 7917 // defaulted 'operator=='. 7918 if (Op == OO_Spaceship) { 7919 Lookup(OO_ExclaimEqual); 7920 Lookup(OO_Less); 7921 Lookup(OO_EqualEqual); 7922 } 7923 } 7924 7925 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 7926 DefaultedComparisonKind DCK) { 7927 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 7928 7929 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 7930 assert(RD && "defaulted comparison is not defaulted in a class"); 7931 7932 // Perform any unqualified lookups we're going to need to default this 7933 // function. 7934 if (S) { 7935 UnresolvedSet<32> Operators; 7936 lookupOperatorsForDefaultedComparison(*this, S, Operators, 7937 FD->getOverloadedOperator()); 7938 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 7939 Context, Operators.pairs())); 7940 } 7941 7942 // C++2a [class.compare.default]p1: 7943 // A defaulted comparison operator function for some class C shall be a 7944 // non-template function declared in the member-specification of C that is 7945 // -- a non-static const member of C having one parameter of type 7946 // const C&, or 7947 // -- a friend of C having two parameters of type const C& or two 7948 // parameters of type C. 7949 QualType ExpectedParmType1 = Context.getRecordType(RD); 7950 QualType ExpectedParmType2 = 7951 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 7952 if (isa<CXXMethodDecl>(FD)) 7953 ExpectedParmType1 = ExpectedParmType2; 7954 for (const ParmVarDecl *Param : FD->parameters()) { 7955 if (!Param->getType()->isDependentType() && 7956 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 7957 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 7958 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 7959 // corresponding defaulted 'operator<=>' already. 7960 if (!FD->isImplicit()) { 7961 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 7962 << (int)DCK << Param->getType() << ExpectedParmType1 7963 << !isa<CXXMethodDecl>(FD) 7964 << ExpectedParmType2 << Param->getSourceRange(); 7965 } 7966 return true; 7967 } 7968 } 7969 if (FD->getNumParams() == 2 && 7970 !Context.hasSameType(FD->getParamDecl(0)->getType(), 7971 FD->getParamDecl(1)->getType())) { 7972 if (!FD->isImplicit()) { 7973 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 7974 << (int)DCK 7975 << FD->getParamDecl(0)->getType() 7976 << FD->getParamDecl(0)->getSourceRange() 7977 << FD->getParamDecl(1)->getType() 7978 << FD->getParamDecl(1)->getSourceRange(); 7979 } 7980 return true; 7981 } 7982 7983 // ... non-static const member ... 7984 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 7985 assert(!MD->isStatic() && "comparison function cannot be a static member"); 7986 if (!MD->isConst()) { 7987 SourceLocation InsertLoc; 7988 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 7989 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 7990 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 7991 // corresponding defaulted 'operator<=>' already. 7992 if (!MD->isImplicit()) { 7993 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 7994 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 7995 } 7996 7997 // Add the 'const' to the type to recover. 7998 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 7999 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8000 EPI.TypeQuals.addConst(); 8001 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8002 FPT->getParamTypes(), EPI)); 8003 } 8004 } else { 8005 // A non-member function declared in a class must be a friend. 8006 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8007 } 8008 8009 // C++2a [class.eq]p1, [class.rel]p1: 8010 // A [defaulted comparison other than <=>] shall have a declared return 8011 // type bool. 8012 if (DCK != DefaultedComparisonKind::ThreeWay && 8013 !FD->getDeclaredReturnType()->isDependentType() && 8014 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8015 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8016 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8017 << FD->getReturnTypeSourceRange(); 8018 return true; 8019 } 8020 // C++2a [class.spaceship]p2 [P2002R0]: 8021 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8022 // R shall not contain a placeholder type. 8023 if (DCK == DefaultedComparisonKind::ThreeWay && 8024 FD->getDeclaredReturnType()->getContainedDeducedType() && 8025 !Context.hasSameType(FD->getDeclaredReturnType(), 8026 Context.getAutoDeductType())) { 8027 Diag(FD->getLocation(), 8028 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8029 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8030 << FD->getReturnTypeSourceRange(); 8031 return true; 8032 } 8033 8034 // For a defaulted function in a dependent class, defer all remaining checks 8035 // until instantiation. 8036 if (RD->isDependentType()) 8037 return false; 8038 8039 // Determine whether the function should be defined as deleted. 8040 DefaultedComparisonInfo Info = 8041 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8042 8043 bool First = FD == FD->getCanonicalDecl(); 8044 8045 // If we want to delete the function, then do so; there's nothing else to 8046 // check in that case. 8047 if (Info.Deleted) { 8048 if (!First) { 8049 // C++11 [dcl.fct.def.default]p4: 8050 // [For a] user-provided explicitly-defaulted function [...] if such a 8051 // function is implicitly defined as deleted, the program is ill-formed. 8052 // 8053 // This is really just a consequence of the general rule that you can 8054 // only delete a function on its first declaration. 8055 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8056 << FD->isImplicit() << (int)DCK; 8057 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8058 DefaultedComparisonAnalyzer::ExplainDeleted) 8059 .visit(); 8060 return true; 8061 } 8062 8063 SetDeclDeleted(FD, FD->getLocation()); 8064 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8065 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8066 << (int)DCK; 8067 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8068 DefaultedComparisonAnalyzer::ExplainDeleted) 8069 .visit(); 8070 } 8071 return false; 8072 } 8073 8074 // C++2a [class.spaceship]p2: 8075 // The return type is deduced as the common comparison type of R0, R1, ... 8076 if (DCK == DefaultedComparisonKind::ThreeWay && 8077 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8078 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8079 if (RetLoc.isInvalid()) 8080 RetLoc = FD->getBeginLoc(); 8081 // FIXME: Should we really care whether we have the complete type and the 8082 // 'enumerator' constants here? A forward declaration seems sufficient. 8083 QualType Cat = CheckComparisonCategoryType( 8084 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8085 if (Cat.isNull()) 8086 return true; 8087 Context.adjustDeducedFunctionResultType( 8088 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8089 } 8090 8091 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8092 // An explicitly-defaulted function that is not defined as deleted may be 8093 // declared constexpr or consteval only if it is constexpr-compatible. 8094 // C++2a [class.compare.default]p3 [P2002R0]: 8095 // A defaulted comparison function is constexpr-compatible if it satisfies 8096 // the requirements for a constexpr function [...] 8097 // The only relevant requirements are that the parameter and return types are 8098 // literal types. The remaining conditions are checked by the analyzer. 8099 if (FD->isConstexpr()) { 8100 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8101 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8102 !Info.Constexpr) { 8103 Diag(FD->getBeginLoc(), 8104 diag::err_incorrect_defaulted_comparison_constexpr) 8105 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8106 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8107 DefaultedComparisonAnalyzer::ExplainConstexpr) 8108 .visit(); 8109 } 8110 } 8111 8112 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8113 // If a constexpr-compatible function is explicitly defaulted on its first 8114 // declaration, it is implicitly considered to be constexpr. 8115 // FIXME: Only applying this to the first declaration seems problematic, as 8116 // simple reorderings can affect the meaning of the program. 8117 if (First && !FD->isConstexpr() && Info.Constexpr) 8118 FD->setConstexprKind(CSK_constexpr); 8119 8120 // C++2a [except.spec]p3: 8121 // If a declaration of a function does not have a noexcept-specifier 8122 // [and] is defaulted on its first declaration, [...] the exception 8123 // specification is as specified below 8124 if (FD->getExceptionSpecType() == EST_None) { 8125 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8126 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8127 EPI.ExceptionSpec.Type = EST_Unevaluated; 8128 EPI.ExceptionSpec.SourceDecl = FD; 8129 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8130 FPT->getParamTypes(), EPI)); 8131 } 8132 8133 return false; 8134 } 8135 8136 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8137 FunctionDecl *Spaceship) { 8138 Sema::CodeSynthesisContext Ctx; 8139 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8140 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8141 Ctx.Entity = Spaceship; 8142 pushCodeSynthesisContext(Ctx); 8143 8144 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8145 EqualEqual->setImplicit(); 8146 8147 popCodeSynthesisContext(); 8148 } 8149 8150 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8151 DefaultedComparisonKind DCK) { 8152 assert(FD->isDefaulted() && !FD->isDeleted() && 8153 !FD->doesThisDeclarationHaveABody()); 8154 if (FD->willHaveBody() || FD->isInvalidDecl()) 8155 return; 8156 8157 SynthesizedFunctionScope Scope(*this, FD); 8158 8159 // Add a context note for diagnostics produced after this point. 8160 Scope.addContextNote(UseLoc); 8161 8162 { 8163 // Build and set up the function body. 8164 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8165 SourceLocation BodyLoc = 8166 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8167 StmtResult Body = 8168 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8169 if (Body.isInvalid()) { 8170 FD->setInvalidDecl(); 8171 return; 8172 } 8173 FD->setBody(Body.get()); 8174 FD->markUsed(Context); 8175 } 8176 8177 // The exception specification is needed because we are defining the 8178 // function. Note that this will reuse the body we just built. 8179 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8180 8181 if (ASTMutationListener *L = getASTMutationListener()) 8182 L->CompletedImplicitDefinition(FD); 8183 } 8184 8185 static Sema::ImplicitExceptionSpecification 8186 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8187 FunctionDecl *FD, 8188 Sema::DefaultedComparisonKind DCK) { 8189 ComputingExceptionSpec CES(S, FD, Loc); 8190 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8191 8192 if (FD->isInvalidDecl()) 8193 return ExceptSpec; 8194 8195 // The common case is that we just defined the comparison function. In that 8196 // case, just look at whether the body can throw. 8197 if (FD->hasBody()) { 8198 ExceptSpec.CalledStmt(FD->getBody()); 8199 } else { 8200 // Otherwise, build a body so we can check it. This should ideally only 8201 // happen when we're not actually marking the function referenced. (This is 8202 // only really important for efficiency: we don't want to build and throw 8203 // away bodies for comparison functions more than we strictly need to.) 8204 8205 // Pretend to synthesize the function body in an unevaluated context. 8206 // Note that we can't actually just go ahead and define the function here: 8207 // we are not permitted to mark its callees as referenced. 8208 Sema::SynthesizedFunctionScope Scope(S, FD); 8209 EnterExpressionEvaluationContext Context( 8210 S, Sema::ExpressionEvaluationContext::Unevaluated); 8211 8212 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8213 SourceLocation BodyLoc = 8214 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8215 StmtResult Body = 8216 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8217 if (!Body.isInvalid()) 8218 ExceptSpec.CalledStmt(Body.get()); 8219 8220 // FIXME: Can we hold onto this body and just transform it to potentially 8221 // evaluated when we're asked to define the function rather than rebuilding 8222 // it? Either that, or we should only build the bits of the body that we 8223 // need (the expressions, not the statements). 8224 } 8225 8226 return ExceptSpec; 8227 } 8228 8229 void Sema::CheckDelayedMemberExceptionSpecs() { 8230 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8231 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8232 8233 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8234 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8235 8236 // Perform any deferred checking of exception specifications for virtual 8237 // destructors. 8238 for (auto &Check : Overriding) 8239 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8240 8241 // Perform any deferred checking of exception specifications for befriended 8242 // special members. 8243 for (auto &Check : Equivalent) 8244 CheckEquivalentExceptionSpec(Check.second, Check.first); 8245 } 8246 8247 namespace { 8248 /// CRTP base class for visiting operations performed by a special member 8249 /// function (or inherited constructor). 8250 template<typename Derived> 8251 struct SpecialMemberVisitor { 8252 Sema &S; 8253 CXXMethodDecl *MD; 8254 Sema::CXXSpecialMember CSM; 8255 Sema::InheritedConstructorInfo *ICI; 8256 8257 // Properties of the special member, computed for convenience. 8258 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8259 8260 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8261 Sema::InheritedConstructorInfo *ICI) 8262 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8263 switch (CSM) { 8264 case Sema::CXXDefaultConstructor: 8265 case Sema::CXXCopyConstructor: 8266 case Sema::CXXMoveConstructor: 8267 IsConstructor = true; 8268 break; 8269 case Sema::CXXCopyAssignment: 8270 case Sema::CXXMoveAssignment: 8271 IsAssignment = true; 8272 break; 8273 case Sema::CXXDestructor: 8274 break; 8275 case Sema::CXXInvalid: 8276 llvm_unreachable("invalid special member kind"); 8277 } 8278 8279 if (MD->getNumParams()) { 8280 if (const ReferenceType *RT = 8281 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8282 ConstArg = RT->getPointeeType().isConstQualified(); 8283 } 8284 } 8285 8286 Derived &getDerived() { return static_cast<Derived&>(*this); } 8287 8288 /// Is this a "move" special member? 8289 bool isMove() const { 8290 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8291 } 8292 8293 /// Look up the corresponding special member in the given class. 8294 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8295 unsigned Quals, bool IsMutable) { 8296 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8297 ConstArg && !IsMutable); 8298 } 8299 8300 /// Look up the constructor for the specified base class to see if it's 8301 /// overridden due to this being an inherited constructor. 8302 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8303 if (!ICI) 8304 return {}; 8305 assert(CSM == Sema::CXXDefaultConstructor); 8306 auto *BaseCtor = 8307 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8308 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8309 return MD; 8310 return {}; 8311 } 8312 8313 /// A base or member subobject. 8314 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8315 8316 /// Get the location to use for a subobject in diagnostics. 8317 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8318 // FIXME: For an indirect virtual base, the direct base leading to 8319 // the indirect virtual base would be a more useful choice. 8320 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8321 return B->getBaseTypeLoc(); 8322 else 8323 return Subobj.get<FieldDecl*>()->getLocation(); 8324 } 8325 8326 enum BasesToVisit { 8327 /// Visit all non-virtual (direct) bases. 8328 VisitNonVirtualBases, 8329 /// Visit all direct bases, virtual or not. 8330 VisitDirectBases, 8331 /// Visit all non-virtual bases, and all virtual bases if the class 8332 /// is not abstract. 8333 VisitPotentiallyConstructedBases, 8334 /// Visit all direct or virtual bases. 8335 VisitAllBases 8336 }; 8337 8338 // Visit the bases and members of the class. 8339 bool visit(BasesToVisit Bases) { 8340 CXXRecordDecl *RD = MD->getParent(); 8341 8342 if (Bases == VisitPotentiallyConstructedBases) 8343 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8344 8345 for (auto &B : RD->bases()) 8346 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8347 getDerived().visitBase(&B)) 8348 return true; 8349 8350 if (Bases == VisitAllBases) 8351 for (auto &B : RD->vbases()) 8352 if (getDerived().visitBase(&B)) 8353 return true; 8354 8355 for (auto *F : RD->fields()) 8356 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8357 getDerived().visitField(F)) 8358 return true; 8359 8360 return false; 8361 } 8362 }; 8363 } 8364 8365 namespace { 8366 struct SpecialMemberDeletionInfo 8367 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8368 bool Diagnose; 8369 8370 SourceLocation Loc; 8371 8372 bool AllFieldsAreConst; 8373 8374 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8375 Sema::CXXSpecialMember CSM, 8376 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8377 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8378 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8379 8380 bool inUnion() const { return MD->getParent()->isUnion(); } 8381 8382 Sema::CXXSpecialMember getEffectiveCSM() { 8383 return ICI ? Sema::CXXInvalid : CSM; 8384 } 8385 8386 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8387 8388 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8389 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8390 8391 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8392 bool shouldDeleteForField(FieldDecl *FD); 8393 bool shouldDeleteForAllConstMembers(); 8394 8395 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8396 unsigned Quals); 8397 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8398 Sema::SpecialMemberOverloadResult SMOR, 8399 bool IsDtorCallInCtor); 8400 8401 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8402 }; 8403 } 8404 8405 /// Is the given special member inaccessible when used on the given 8406 /// sub-object. 8407 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8408 CXXMethodDecl *target) { 8409 /// If we're operating on a base class, the object type is the 8410 /// type of this special member. 8411 QualType objectTy; 8412 AccessSpecifier access = target->getAccess(); 8413 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8414 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8415 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8416 8417 // If we're operating on a field, the object type is the type of the field. 8418 } else { 8419 objectTy = S.Context.getTypeDeclType(target->getParent()); 8420 } 8421 8422 return S.isMemberAccessibleForDeletion( 8423 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8424 } 8425 8426 /// Check whether we should delete a special member due to the implicit 8427 /// definition containing a call to a special member of a subobject. 8428 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8429 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8430 bool IsDtorCallInCtor) { 8431 CXXMethodDecl *Decl = SMOR.getMethod(); 8432 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8433 8434 int DiagKind = -1; 8435 8436 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8437 DiagKind = !Decl ? 0 : 1; 8438 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8439 DiagKind = 2; 8440 else if (!isAccessible(Subobj, Decl)) 8441 DiagKind = 3; 8442 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8443 !Decl->isTrivial()) { 8444 // A member of a union must have a trivial corresponding special member. 8445 // As a weird special case, a destructor call from a union's constructor 8446 // must be accessible and non-deleted, but need not be trivial. Such a 8447 // destructor is never actually called, but is semantically checked as 8448 // if it were. 8449 DiagKind = 4; 8450 } 8451 8452 if (DiagKind == -1) 8453 return false; 8454 8455 if (Diagnose) { 8456 if (Field) { 8457 S.Diag(Field->getLocation(), 8458 diag::note_deleted_special_member_class_subobject) 8459 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8460 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8461 } else { 8462 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8463 S.Diag(Base->getBeginLoc(), 8464 diag::note_deleted_special_member_class_subobject) 8465 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8466 << Base->getType() << DiagKind << IsDtorCallInCtor 8467 << /*IsObjCPtr*/false; 8468 } 8469 8470 if (DiagKind == 1) 8471 S.NoteDeletedFunction(Decl); 8472 // FIXME: Explain inaccessibility if DiagKind == 3. 8473 } 8474 8475 return true; 8476 } 8477 8478 /// Check whether we should delete a special member function due to having a 8479 /// direct or virtual base class or non-static data member of class type M. 8480 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8481 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8482 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8483 bool IsMutable = Field && Field->isMutable(); 8484 8485 // C++11 [class.ctor]p5: 8486 // -- any direct or virtual base class, or non-static data member with no 8487 // brace-or-equal-initializer, has class type M (or array thereof) and 8488 // either M has no default constructor or overload resolution as applied 8489 // to M's default constructor results in an ambiguity or in a function 8490 // that is deleted or inaccessible 8491 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8492 // -- a direct or virtual base class B that cannot be copied/moved because 8493 // overload resolution, as applied to B's corresponding special member, 8494 // results in an ambiguity or a function that is deleted or inaccessible 8495 // from the defaulted special member 8496 // C++11 [class.dtor]p5: 8497 // -- any direct or virtual base class [...] has a type with a destructor 8498 // that is deleted or inaccessible 8499 if (!(CSM == Sema::CXXDefaultConstructor && 8500 Field && Field->hasInClassInitializer()) && 8501 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8502 false)) 8503 return true; 8504 8505 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8506 // -- any direct or virtual base class or non-static data member has a 8507 // type with a destructor that is deleted or inaccessible 8508 if (IsConstructor) { 8509 Sema::SpecialMemberOverloadResult SMOR = 8510 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8511 false, false, false, false, false); 8512 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8513 return true; 8514 } 8515 8516 return false; 8517 } 8518 8519 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8520 FieldDecl *FD, QualType FieldType) { 8521 // The defaulted special functions are defined as deleted if this is a variant 8522 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8523 // type under ARC. 8524 if (!FieldType.hasNonTrivialObjCLifetime()) 8525 return false; 8526 8527 // Don't make the defaulted default constructor defined as deleted if the 8528 // member has an in-class initializer. 8529 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8530 return false; 8531 8532 if (Diagnose) { 8533 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8534 S.Diag(FD->getLocation(), 8535 diag::note_deleted_special_member_class_subobject) 8536 << getEffectiveCSM() << ParentClass << /*IsField*/true 8537 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8538 } 8539 8540 return true; 8541 } 8542 8543 /// Check whether we should delete a special member function due to the class 8544 /// having a particular direct or virtual base class. 8545 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8546 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8547 // If program is correct, BaseClass cannot be null, but if it is, the error 8548 // must be reported elsewhere. 8549 if (!BaseClass) 8550 return false; 8551 // If we have an inheriting constructor, check whether we're calling an 8552 // inherited constructor instead of a default constructor. 8553 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8554 if (auto *BaseCtor = SMOR.getMethod()) { 8555 // Note that we do not check access along this path; other than that, 8556 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8557 // FIXME: Check that the base has a usable destructor! Sink this into 8558 // shouldDeleteForClassSubobject. 8559 if (BaseCtor->isDeleted() && Diagnose) { 8560 S.Diag(Base->getBeginLoc(), 8561 diag::note_deleted_special_member_class_subobject) 8562 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8563 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8564 << /*IsObjCPtr*/false; 8565 S.NoteDeletedFunction(BaseCtor); 8566 } 8567 return BaseCtor->isDeleted(); 8568 } 8569 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8570 } 8571 8572 /// Check whether we should delete a special member function due to the class 8573 /// having a particular non-static data member. 8574 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8575 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8576 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8577 8578 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8579 return true; 8580 8581 if (CSM == Sema::CXXDefaultConstructor) { 8582 // For a default constructor, all references must be initialized in-class 8583 // and, if a union, it must have a non-const member. 8584 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8585 if (Diagnose) 8586 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8587 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8588 return true; 8589 } 8590 // C++11 [class.ctor]p5: any non-variant non-static data member of 8591 // const-qualified type (or array thereof) with no 8592 // brace-or-equal-initializer does not have a user-provided default 8593 // constructor. 8594 if (!inUnion() && FieldType.isConstQualified() && 8595 !FD->hasInClassInitializer() && 8596 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8597 if (Diagnose) 8598 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8599 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8600 return true; 8601 } 8602 8603 if (inUnion() && !FieldType.isConstQualified()) 8604 AllFieldsAreConst = false; 8605 } else if (CSM == Sema::CXXCopyConstructor) { 8606 // For a copy constructor, data members must not be of rvalue reference 8607 // type. 8608 if (FieldType->isRValueReferenceType()) { 8609 if (Diagnose) 8610 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8611 << MD->getParent() << FD << FieldType; 8612 return true; 8613 } 8614 } else if (IsAssignment) { 8615 // For an assignment operator, data members must not be of reference type. 8616 if (FieldType->isReferenceType()) { 8617 if (Diagnose) 8618 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8619 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8620 return true; 8621 } 8622 if (!FieldRecord && FieldType.isConstQualified()) { 8623 // C++11 [class.copy]p23: 8624 // -- a non-static data member of const non-class type (or array thereof) 8625 if (Diagnose) 8626 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8627 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8628 return true; 8629 } 8630 } 8631 8632 if (FieldRecord) { 8633 // Some additional restrictions exist on the variant members. 8634 if (!inUnion() && FieldRecord->isUnion() && 8635 FieldRecord->isAnonymousStructOrUnion()) { 8636 bool AllVariantFieldsAreConst = true; 8637 8638 // FIXME: Handle anonymous unions declared within anonymous unions. 8639 for (auto *UI : FieldRecord->fields()) { 8640 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 8641 8642 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 8643 return true; 8644 8645 if (!UnionFieldType.isConstQualified()) 8646 AllVariantFieldsAreConst = false; 8647 8648 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 8649 if (UnionFieldRecord && 8650 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 8651 UnionFieldType.getCVRQualifiers())) 8652 return true; 8653 } 8654 8655 // At least one member in each anonymous union must be non-const 8656 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 8657 !FieldRecord->field_empty()) { 8658 if (Diagnose) 8659 S.Diag(FieldRecord->getLocation(), 8660 diag::note_deleted_default_ctor_all_const) 8661 << !!ICI << MD->getParent() << /*anonymous union*/1; 8662 return true; 8663 } 8664 8665 // Don't check the implicit member of the anonymous union type. 8666 // This is technically non-conformant, but sanity demands it. 8667 return false; 8668 } 8669 8670 if (shouldDeleteForClassSubobject(FieldRecord, FD, 8671 FieldType.getCVRQualifiers())) 8672 return true; 8673 } 8674 8675 return false; 8676 } 8677 8678 /// C++11 [class.ctor] p5: 8679 /// A defaulted default constructor for a class X is defined as deleted if 8680 /// X is a union and all of its variant members are of const-qualified type. 8681 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 8682 // This is a silly definition, because it gives an empty union a deleted 8683 // default constructor. Don't do that. 8684 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 8685 bool AnyFields = false; 8686 for (auto *F : MD->getParent()->fields()) 8687 if ((AnyFields = !F->isUnnamedBitfield())) 8688 break; 8689 if (!AnyFields) 8690 return false; 8691 if (Diagnose) 8692 S.Diag(MD->getParent()->getLocation(), 8693 diag::note_deleted_default_ctor_all_const) 8694 << !!ICI << MD->getParent() << /*not anonymous union*/0; 8695 return true; 8696 } 8697 return false; 8698 } 8699 8700 /// Determine whether a defaulted special member function should be defined as 8701 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 8702 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 8703 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 8704 InheritedConstructorInfo *ICI, 8705 bool Diagnose) { 8706 if (MD->isInvalidDecl()) 8707 return false; 8708 CXXRecordDecl *RD = MD->getParent(); 8709 assert(!RD->isDependentType() && "do deletion after instantiation"); 8710 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 8711 return false; 8712 8713 // C++11 [expr.lambda.prim]p19: 8714 // The closure type associated with a lambda-expression has a 8715 // deleted (8.4.3) default constructor and a deleted copy 8716 // assignment operator. 8717 // C++2a adds back these operators if the lambda has no lambda-capture. 8718 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 8719 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 8720 if (Diagnose) 8721 Diag(RD->getLocation(), diag::note_lambda_decl); 8722 return true; 8723 } 8724 8725 // For an anonymous struct or union, the copy and assignment special members 8726 // will never be used, so skip the check. For an anonymous union declared at 8727 // namespace scope, the constructor and destructor are used. 8728 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 8729 RD->isAnonymousStructOrUnion()) 8730 return false; 8731 8732 // C++11 [class.copy]p7, p18: 8733 // If the class definition declares a move constructor or move assignment 8734 // operator, an implicitly declared copy constructor or copy assignment 8735 // operator is defined as deleted. 8736 if (MD->isImplicit() && 8737 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 8738 CXXMethodDecl *UserDeclaredMove = nullptr; 8739 8740 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 8741 // deletion of the corresponding copy operation, not both copy operations. 8742 // MSVC 2015 has adopted the standards conforming behavior. 8743 bool DeletesOnlyMatchingCopy = 8744 getLangOpts().MSVCCompat && 8745 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 8746 8747 if (RD->hasUserDeclaredMoveConstructor() && 8748 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 8749 if (!Diagnose) return true; 8750 8751 // Find any user-declared move constructor. 8752 for (auto *I : RD->ctors()) { 8753 if (I->isMoveConstructor()) { 8754 UserDeclaredMove = I; 8755 break; 8756 } 8757 } 8758 assert(UserDeclaredMove); 8759 } else if (RD->hasUserDeclaredMoveAssignment() && 8760 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 8761 if (!Diagnose) return true; 8762 8763 // Find any user-declared move assignment operator. 8764 for (auto *I : RD->methods()) { 8765 if (I->isMoveAssignmentOperator()) { 8766 UserDeclaredMove = I; 8767 break; 8768 } 8769 } 8770 assert(UserDeclaredMove); 8771 } 8772 8773 if (UserDeclaredMove) { 8774 Diag(UserDeclaredMove->getLocation(), 8775 diag::note_deleted_copy_user_declared_move) 8776 << (CSM == CXXCopyAssignment) << RD 8777 << UserDeclaredMove->isMoveAssignmentOperator(); 8778 return true; 8779 } 8780 } 8781 8782 // Do access control from the special member function 8783 ContextRAII MethodContext(*this, MD); 8784 8785 // C++11 [class.dtor]p5: 8786 // -- for a virtual destructor, lookup of the non-array deallocation function 8787 // results in an ambiguity or in a function that is deleted or inaccessible 8788 if (CSM == CXXDestructor && MD->isVirtual()) { 8789 FunctionDecl *OperatorDelete = nullptr; 8790 DeclarationName Name = 8791 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 8792 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 8793 OperatorDelete, /*Diagnose*/false)) { 8794 if (Diagnose) 8795 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 8796 return true; 8797 } 8798 } 8799 8800 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 8801 8802 // Per DR1611, do not consider virtual bases of constructors of abstract 8803 // classes, since we are not going to construct them. 8804 // Per DR1658, do not consider virtual bases of destructors of abstract 8805 // classes either. 8806 // Per DR2180, for assignment operators we only assign (and thus only 8807 // consider) direct bases. 8808 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 8809 : SMI.VisitPotentiallyConstructedBases)) 8810 return true; 8811 8812 if (SMI.shouldDeleteForAllConstMembers()) 8813 return true; 8814 8815 if (getLangOpts().CUDA) { 8816 // We should delete the special member in CUDA mode if target inference 8817 // failed. 8818 // For inherited constructors (non-null ICI), CSM may be passed so that MD 8819 // is treated as certain special member, which may not reflect what special 8820 // member MD really is. However inferCUDATargetForImplicitSpecialMember 8821 // expects CSM to match MD, therefore recalculate CSM. 8822 assert(ICI || CSM == getSpecialMember(MD)); 8823 auto RealCSM = CSM; 8824 if (ICI) 8825 RealCSM = getSpecialMember(MD); 8826 8827 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 8828 SMI.ConstArg, Diagnose); 8829 } 8830 8831 return false; 8832 } 8833 8834 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 8835 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 8836 assert(DFK && "not a defaultable function"); 8837 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 8838 8839 if (DFK.isSpecialMember()) { 8840 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 8841 nullptr, /*Diagnose=*/true); 8842 } else { 8843 DefaultedComparisonAnalyzer( 8844 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 8845 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 8846 .visit(); 8847 } 8848 } 8849 8850 /// Perform lookup for a special member of the specified kind, and determine 8851 /// whether it is trivial. If the triviality can be determined without the 8852 /// lookup, skip it. This is intended for use when determining whether a 8853 /// special member of a containing object is trivial, and thus does not ever 8854 /// perform overload resolution for default constructors. 8855 /// 8856 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 8857 /// member that was most likely to be intended to be trivial, if any. 8858 /// 8859 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 8860 /// determine whether the special member is trivial. 8861 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 8862 Sema::CXXSpecialMember CSM, unsigned Quals, 8863 bool ConstRHS, 8864 Sema::TrivialABIHandling TAH, 8865 CXXMethodDecl **Selected) { 8866 if (Selected) 8867 *Selected = nullptr; 8868 8869 switch (CSM) { 8870 case Sema::CXXInvalid: 8871 llvm_unreachable("not a special member"); 8872 8873 case Sema::CXXDefaultConstructor: 8874 // C++11 [class.ctor]p5: 8875 // A default constructor is trivial if: 8876 // - all the [direct subobjects] have trivial default constructors 8877 // 8878 // Note, no overload resolution is performed in this case. 8879 if (RD->hasTrivialDefaultConstructor()) 8880 return true; 8881 8882 if (Selected) { 8883 // If there's a default constructor which could have been trivial, dig it 8884 // out. Otherwise, if there's any user-provided default constructor, point 8885 // to that as an example of why there's not a trivial one. 8886 CXXConstructorDecl *DefCtor = nullptr; 8887 if (RD->needsImplicitDefaultConstructor()) 8888 S.DeclareImplicitDefaultConstructor(RD); 8889 for (auto *CI : RD->ctors()) { 8890 if (!CI->isDefaultConstructor()) 8891 continue; 8892 DefCtor = CI; 8893 if (!DefCtor->isUserProvided()) 8894 break; 8895 } 8896 8897 *Selected = DefCtor; 8898 } 8899 8900 return false; 8901 8902 case Sema::CXXDestructor: 8903 // C++11 [class.dtor]p5: 8904 // A destructor is trivial if: 8905 // - all the direct [subobjects] have trivial destructors 8906 if (RD->hasTrivialDestructor() || 8907 (TAH == Sema::TAH_ConsiderTrivialABI && 8908 RD->hasTrivialDestructorForCall())) 8909 return true; 8910 8911 if (Selected) { 8912 if (RD->needsImplicitDestructor()) 8913 S.DeclareImplicitDestructor(RD); 8914 *Selected = RD->getDestructor(); 8915 } 8916 8917 return false; 8918 8919 case Sema::CXXCopyConstructor: 8920 // C++11 [class.copy]p12: 8921 // A copy constructor is trivial if: 8922 // - the constructor selected to copy each direct [subobject] is trivial 8923 if (RD->hasTrivialCopyConstructor() || 8924 (TAH == Sema::TAH_ConsiderTrivialABI && 8925 RD->hasTrivialCopyConstructorForCall())) { 8926 if (Quals == Qualifiers::Const) 8927 // We must either select the trivial copy constructor or reach an 8928 // ambiguity; no need to actually perform overload resolution. 8929 return true; 8930 } else if (!Selected) { 8931 return false; 8932 } 8933 // In C++98, we are not supposed to perform overload resolution here, but we 8934 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 8935 // cases like B as having a non-trivial copy constructor: 8936 // struct A { template<typename T> A(T&); }; 8937 // struct B { mutable A a; }; 8938 goto NeedOverloadResolution; 8939 8940 case Sema::CXXCopyAssignment: 8941 // C++11 [class.copy]p25: 8942 // A copy assignment operator is trivial if: 8943 // - the assignment operator selected to copy each direct [subobject] is 8944 // trivial 8945 if (RD->hasTrivialCopyAssignment()) { 8946 if (Quals == Qualifiers::Const) 8947 return true; 8948 } else if (!Selected) { 8949 return false; 8950 } 8951 // In C++98, we are not supposed to perform overload resolution here, but we 8952 // treat that as a language defect. 8953 goto NeedOverloadResolution; 8954 8955 case Sema::CXXMoveConstructor: 8956 case Sema::CXXMoveAssignment: 8957 NeedOverloadResolution: 8958 Sema::SpecialMemberOverloadResult SMOR = 8959 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 8960 8961 // The standard doesn't describe how to behave if the lookup is ambiguous. 8962 // We treat it as not making the member non-trivial, just like the standard 8963 // mandates for the default constructor. This should rarely matter, because 8964 // the member will also be deleted. 8965 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8966 return true; 8967 8968 if (!SMOR.getMethod()) { 8969 assert(SMOR.getKind() == 8970 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 8971 return false; 8972 } 8973 8974 // We deliberately don't check if we found a deleted special member. We're 8975 // not supposed to! 8976 if (Selected) 8977 *Selected = SMOR.getMethod(); 8978 8979 if (TAH == Sema::TAH_ConsiderTrivialABI && 8980 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 8981 return SMOR.getMethod()->isTrivialForCall(); 8982 return SMOR.getMethod()->isTrivial(); 8983 } 8984 8985 llvm_unreachable("unknown special method kind"); 8986 } 8987 8988 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 8989 for (auto *CI : RD->ctors()) 8990 if (!CI->isImplicit()) 8991 return CI; 8992 8993 // Look for constructor templates. 8994 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 8995 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 8996 if (CXXConstructorDecl *CD = 8997 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 8998 return CD; 8999 } 9000 9001 return nullptr; 9002 } 9003 9004 /// The kind of subobject we are checking for triviality. The values of this 9005 /// enumeration are used in diagnostics. 9006 enum TrivialSubobjectKind { 9007 /// The subobject is a base class. 9008 TSK_BaseClass, 9009 /// The subobject is a non-static data member. 9010 TSK_Field, 9011 /// The object is actually the complete object. 9012 TSK_CompleteObject 9013 }; 9014 9015 /// Check whether the special member selected for a given type would be trivial. 9016 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9017 QualType SubType, bool ConstRHS, 9018 Sema::CXXSpecialMember CSM, 9019 TrivialSubobjectKind Kind, 9020 Sema::TrivialABIHandling TAH, bool Diagnose) { 9021 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9022 if (!SubRD) 9023 return true; 9024 9025 CXXMethodDecl *Selected; 9026 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9027 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9028 return true; 9029 9030 if (Diagnose) { 9031 if (ConstRHS) 9032 SubType.addConst(); 9033 9034 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9035 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9036 << Kind << SubType.getUnqualifiedType(); 9037 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9038 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9039 } else if (!Selected) 9040 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9041 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9042 else if (Selected->isUserProvided()) { 9043 if (Kind == TSK_CompleteObject) 9044 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9045 << Kind << SubType.getUnqualifiedType() << CSM; 9046 else { 9047 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9048 << Kind << SubType.getUnqualifiedType() << CSM; 9049 S.Diag(Selected->getLocation(), diag::note_declared_at); 9050 } 9051 } else { 9052 if (Kind != TSK_CompleteObject) 9053 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9054 << Kind << SubType.getUnqualifiedType() << CSM; 9055 9056 // Explain why the defaulted or deleted special member isn't trivial. 9057 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9058 Diagnose); 9059 } 9060 } 9061 9062 return false; 9063 } 9064 9065 /// Check whether the members of a class type allow a special member to be 9066 /// trivial. 9067 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9068 Sema::CXXSpecialMember CSM, 9069 bool ConstArg, 9070 Sema::TrivialABIHandling TAH, 9071 bool Diagnose) { 9072 for (const auto *FI : RD->fields()) { 9073 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9074 continue; 9075 9076 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9077 9078 // Pretend anonymous struct or union members are members of this class. 9079 if (FI->isAnonymousStructOrUnion()) { 9080 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9081 CSM, ConstArg, TAH, Diagnose)) 9082 return false; 9083 continue; 9084 } 9085 9086 // C++11 [class.ctor]p5: 9087 // A default constructor is trivial if [...] 9088 // -- no non-static data member of its class has a 9089 // brace-or-equal-initializer 9090 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9091 if (Diagnose) 9092 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 9093 return false; 9094 } 9095 9096 // Objective C ARC 4.3.5: 9097 // [...] nontrivally ownership-qualified types are [...] not trivially 9098 // default constructible, copy constructible, move constructible, copy 9099 // assignable, move assignable, or destructible [...] 9100 if (FieldType.hasNonTrivialObjCLifetime()) { 9101 if (Diagnose) 9102 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9103 << RD << FieldType.getObjCLifetime(); 9104 return false; 9105 } 9106 9107 bool ConstRHS = ConstArg && !FI->isMutable(); 9108 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9109 CSM, TSK_Field, TAH, Diagnose)) 9110 return false; 9111 } 9112 9113 return true; 9114 } 9115 9116 /// Diagnose why the specified class does not have a trivial special member of 9117 /// the given kind. 9118 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9119 QualType Ty = Context.getRecordType(RD); 9120 9121 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9122 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9123 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9124 /*Diagnose*/true); 9125 } 9126 9127 /// Determine whether a defaulted or deleted special member function is trivial, 9128 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9129 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9130 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9131 TrivialABIHandling TAH, bool Diagnose) { 9132 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9133 9134 CXXRecordDecl *RD = MD->getParent(); 9135 9136 bool ConstArg = false; 9137 9138 // C++11 [class.copy]p12, p25: [DR1593] 9139 // A [special member] is trivial if [...] its parameter-type-list is 9140 // equivalent to the parameter-type-list of an implicit declaration [...] 9141 switch (CSM) { 9142 case CXXDefaultConstructor: 9143 case CXXDestructor: 9144 // Trivial default constructors and destructors cannot have parameters. 9145 break; 9146 9147 case CXXCopyConstructor: 9148 case CXXCopyAssignment: { 9149 // Trivial copy operations always have const, non-volatile parameter types. 9150 ConstArg = true; 9151 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9152 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9153 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9154 if (Diagnose) 9155 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9156 << Param0->getSourceRange() << Param0->getType() 9157 << Context.getLValueReferenceType( 9158 Context.getRecordType(RD).withConst()); 9159 return false; 9160 } 9161 break; 9162 } 9163 9164 case CXXMoveConstructor: 9165 case CXXMoveAssignment: { 9166 // Trivial move operations always have non-cv-qualified parameters. 9167 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9168 const RValueReferenceType *RT = 9169 Param0->getType()->getAs<RValueReferenceType>(); 9170 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9171 if (Diagnose) 9172 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9173 << Param0->getSourceRange() << Param0->getType() 9174 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9175 return false; 9176 } 9177 break; 9178 } 9179 9180 case CXXInvalid: 9181 llvm_unreachable("not a special member"); 9182 } 9183 9184 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9185 if (Diagnose) 9186 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9187 diag::note_nontrivial_default_arg) 9188 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9189 return false; 9190 } 9191 if (MD->isVariadic()) { 9192 if (Diagnose) 9193 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9194 return false; 9195 } 9196 9197 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9198 // A copy/move [constructor or assignment operator] is trivial if 9199 // -- the [member] selected to copy/move each direct base class subobject 9200 // is trivial 9201 // 9202 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9203 // A [default constructor or destructor] is trivial if 9204 // -- all the direct base classes have trivial [default constructors or 9205 // destructors] 9206 for (const auto &BI : RD->bases()) 9207 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9208 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9209 return false; 9210 9211 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9212 // A copy/move [constructor or assignment operator] for a class X is 9213 // trivial if 9214 // -- for each non-static data member of X that is of class type (or array 9215 // thereof), the constructor selected to copy/move that member is 9216 // trivial 9217 // 9218 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9219 // A [default constructor or destructor] is trivial if 9220 // -- for all of the non-static data members of its class that are of class 9221 // type (or array thereof), each such class has a trivial [default 9222 // constructor or destructor] 9223 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9224 return false; 9225 9226 // C++11 [class.dtor]p5: 9227 // A destructor is trivial if [...] 9228 // -- the destructor is not virtual 9229 if (CSM == CXXDestructor && MD->isVirtual()) { 9230 if (Diagnose) 9231 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9232 return false; 9233 } 9234 9235 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9236 // A [special member] for class X is trivial if [...] 9237 // -- class X has no virtual functions and no virtual base classes 9238 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9239 if (!Diagnose) 9240 return false; 9241 9242 if (RD->getNumVBases()) { 9243 // Check for virtual bases. We already know that the corresponding 9244 // member in all bases is trivial, so vbases must all be direct. 9245 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9246 assert(BS.isVirtual()); 9247 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9248 return false; 9249 } 9250 9251 // Must have a virtual method. 9252 for (const auto *MI : RD->methods()) { 9253 if (MI->isVirtual()) { 9254 SourceLocation MLoc = MI->getBeginLoc(); 9255 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9256 return false; 9257 } 9258 } 9259 9260 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9261 } 9262 9263 // Looks like it's trivial! 9264 return true; 9265 } 9266 9267 namespace { 9268 struct FindHiddenVirtualMethod { 9269 Sema *S; 9270 CXXMethodDecl *Method; 9271 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9272 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9273 9274 private: 9275 /// Check whether any most overridden method from MD in Methods 9276 static bool CheckMostOverridenMethods( 9277 const CXXMethodDecl *MD, 9278 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9279 if (MD->size_overridden_methods() == 0) 9280 return Methods.count(MD->getCanonicalDecl()); 9281 for (const CXXMethodDecl *O : MD->overridden_methods()) 9282 if (CheckMostOverridenMethods(O, Methods)) 9283 return true; 9284 return false; 9285 } 9286 9287 public: 9288 /// Member lookup function that determines whether a given C++ 9289 /// method overloads virtual methods in a base class without overriding any, 9290 /// to be used with CXXRecordDecl::lookupInBases(). 9291 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9292 RecordDecl *BaseRecord = 9293 Specifier->getType()->castAs<RecordType>()->getDecl(); 9294 9295 DeclarationName Name = Method->getDeclName(); 9296 assert(Name.getNameKind() == DeclarationName::Identifier); 9297 9298 bool foundSameNameMethod = false; 9299 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9300 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9301 Path.Decls = Path.Decls.slice(1)) { 9302 NamedDecl *D = Path.Decls.front(); 9303 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9304 MD = MD->getCanonicalDecl(); 9305 foundSameNameMethod = true; 9306 // Interested only in hidden virtual methods. 9307 if (!MD->isVirtual()) 9308 continue; 9309 // If the method we are checking overrides a method from its base 9310 // don't warn about the other overloaded methods. Clang deviates from 9311 // GCC by only diagnosing overloads of inherited virtual functions that 9312 // do not override any other virtual functions in the base. GCC's 9313 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9314 // function from a base class. These cases may be better served by a 9315 // warning (not specific to virtual functions) on call sites when the 9316 // call would select a different function from the base class, were it 9317 // visible. 9318 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9319 if (!S->IsOverload(Method, MD, false)) 9320 return true; 9321 // Collect the overload only if its hidden. 9322 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9323 overloadedMethods.push_back(MD); 9324 } 9325 } 9326 9327 if (foundSameNameMethod) 9328 OverloadedMethods.append(overloadedMethods.begin(), 9329 overloadedMethods.end()); 9330 return foundSameNameMethod; 9331 } 9332 }; 9333 } // end anonymous namespace 9334 9335 /// Add the most overriden methods from MD to Methods 9336 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9337 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9338 if (MD->size_overridden_methods() == 0) 9339 Methods.insert(MD->getCanonicalDecl()); 9340 else 9341 for (const CXXMethodDecl *O : MD->overridden_methods()) 9342 AddMostOverridenMethods(O, Methods); 9343 } 9344 9345 /// Check if a method overloads virtual methods in a base class without 9346 /// overriding any. 9347 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9348 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9349 if (!MD->getDeclName().isIdentifier()) 9350 return; 9351 9352 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9353 /*bool RecordPaths=*/false, 9354 /*bool DetectVirtual=*/false); 9355 FindHiddenVirtualMethod FHVM; 9356 FHVM.Method = MD; 9357 FHVM.S = this; 9358 9359 // Keep the base methods that were overridden or introduced in the subclass 9360 // by 'using' in a set. A base method not in this set is hidden. 9361 CXXRecordDecl *DC = MD->getParent(); 9362 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9363 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9364 NamedDecl *ND = *I; 9365 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9366 ND = shad->getTargetDecl(); 9367 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9368 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9369 } 9370 9371 if (DC->lookupInBases(FHVM, Paths)) 9372 OverloadedMethods = FHVM.OverloadedMethods; 9373 } 9374 9375 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9376 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9377 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9378 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9379 PartialDiagnostic PD = PDiag( 9380 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9381 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9382 Diag(overloadedMD->getLocation(), PD); 9383 } 9384 } 9385 9386 /// Diagnose methods which overload virtual methods in a base class 9387 /// without overriding any. 9388 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9389 if (MD->isInvalidDecl()) 9390 return; 9391 9392 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9393 return; 9394 9395 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9396 FindHiddenVirtualMethods(MD, OverloadedMethods); 9397 if (!OverloadedMethods.empty()) { 9398 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9399 << MD << (OverloadedMethods.size() > 1); 9400 9401 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9402 } 9403 } 9404 9405 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9406 auto PrintDiagAndRemoveAttr = [&]() { 9407 // No diagnostics if this is a template instantiation. 9408 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 9409 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9410 diag::ext_cannot_use_trivial_abi) << &RD; 9411 RD.dropAttr<TrivialABIAttr>(); 9412 }; 9413 9414 // Ill-formed if the struct has virtual functions. 9415 if (RD.isPolymorphic()) { 9416 PrintDiagAndRemoveAttr(); 9417 return; 9418 } 9419 9420 for (const auto &B : RD.bases()) { 9421 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9422 // virtual base. 9423 if ((!B.getType()->isDependentType() && 9424 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 9425 B.isVirtual()) { 9426 PrintDiagAndRemoveAttr(); 9427 return; 9428 } 9429 } 9430 9431 for (const auto *FD : RD.fields()) { 9432 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9433 // non-trivial for the purpose of calls. 9434 QualType FT = FD->getType(); 9435 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9436 PrintDiagAndRemoveAttr(); 9437 return; 9438 } 9439 9440 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9441 if (!RT->isDependentType() && 9442 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9443 PrintDiagAndRemoveAttr(); 9444 return; 9445 } 9446 } 9447 } 9448 9449 void Sema::ActOnFinishCXXMemberSpecification( 9450 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9451 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9452 if (!TagDecl) 9453 return; 9454 9455 AdjustDeclIfTemplate(TagDecl); 9456 9457 for (const ParsedAttr &AL : AttrList) { 9458 if (AL.getKind() != ParsedAttr::AT_Visibility) 9459 continue; 9460 AL.setInvalid(); 9461 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9462 } 9463 9464 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9465 // strict aliasing violation! 9466 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9467 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9468 9469 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9470 } 9471 9472 /// Find the equality comparison functions that should be implicitly declared 9473 /// in a given class definition, per C++2a [class.compare.default]p3. 9474 static void findImplicitlyDeclaredEqualityComparisons( 9475 ASTContext &Ctx, CXXRecordDecl *RD, 9476 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9477 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9478 if (!RD->lookup(EqEq).empty()) 9479 // Member operator== explicitly declared: no implicit operator==s. 9480 return; 9481 9482 // Traverse friends looking for an '==' or a '<=>'. 9483 for (FriendDecl *Friend : RD->friends()) { 9484 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9485 if (!FD) continue; 9486 9487 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9488 // Friend operator== explicitly declared: no implicit operator==s. 9489 Spaceships.clear(); 9490 return; 9491 } 9492 9493 if (FD->getOverloadedOperator() == OO_Spaceship && 9494 FD->isExplicitlyDefaulted()) 9495 Spaceships.push_back(FD); 9496 } 9497 9498 // Look for members named 'operator<=>'. 9499 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9500 for (NamedDecl *ND : RD->lookup(Cmp)) { 9501 // Note that we could find a non-function here (either a function template 9502 // or a using-declaration). Neither case results in an implicit 9503 // 'operator=='. 9504 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9505 if (FD->isExplicitlyDefaulted()) 9506 Spaceships.push_back(FD); 9507 } 9508 } 9509 9510 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9511 /// special functions, such as the default constructor, copy 9512 /// constructor, or destructor, to the given C++ class (C++ 9513 /// [special]p1). This routine can only be executed just before the 9514 /// definition of the class is complete. 9515 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9516 if (ClassDecl->needsImplicitDefaultConstructor()) { 9517 ++getASTContext().NumImplicitDefaultConstructors; 9518 9519 if (ClassDecl->hasInheritedConstructor()) 9520 DeclareImplicitDefaultConstructor(ClassDecl); 9521 } 9522 9523 if (ClassDecl->needsImplicitCopyConstructor()) { 9524 ++getASTContext().NumImplicitCopyConstructors; 9525 9526 // If the properties or semantics of the copy constructor couldn't be 9527 // determined while the class was being declared, force a declaration 9528 // of it now. 9529 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9530 ClassDecl->hasInheritedConstructor()) 9531 DeclareImplicitCopyConstructor(ClassDecl); 9532 // For the MS ABI we need to know whether the copy ctor is deleted. A 9533 // prerequisite for deleting the implicit copy ctor is that the class has a 9534 // move ctor or move assignment that is either user-declared or whose 9535 // semantics are inherited from a subobject. FIXME: We should provide a more 9536 // direct way for CodeGen to ask whether the constructor was deleted. 9537 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9538 (ClassDecl->hasUserDeclaredMoveConstructor() || 9539 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9540 ClassDecl->hasUserDeclaredMoveAssignment() || 9541 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9542 DeclareImplicitCopyConstructor(ClassDecl); 9543 } 9544 9545 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 9546 ++getASTContext().NumImplicitMoveConstructors; 9547 9548 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9549 ClassDecl->hasInheritedConstructor()) 9550 DeclareImplicitMoveConstructor(ClassDecl); 9551 } 9552 9553 if (ClassDecl->needsImplicitCopyAssignment()) { 9554 ++getASTContext().NumImplicitCopyAssignmentOperators; 9555 9556 // If we have a dynamic class, then the copy assignment operator may be 9557 // virtual, so we have to declare it immediately. This ensures that, e.g., 9558 // it shows up in the right place in the vtable and that we diagnose 9559 // problems with the implicit exception specification. 9560 if (ClassDecl->isDynamicClass() || 9561 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9562 ClassDecl->hasInheritedAssignment()) 9563 DeclareImplicitCopyAssignment(ClassDecl); 9564 } 9565 9566 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9567 ++getASTContext().NumImplicitMoveAssignmentOperators; 9568 9569 // Likewise for the move assignment operator. 9570 if (ClassDecl->isDynamicClass() || 9571 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9572 ClassDecl->hasInheritedAssignment()) 9573 DeclareImplicitMoveAssignment(ClassDecl); 9574 } 9575 9576 if (ClassDecl->needsImplicitDestructor()) { 9577 ++getASTContext().NumImplicitDestructors; 9578 9579 // If we have a dynamic class, then the destructor may be virtual, so we 9580 // have to declare the destructor immediately. This ensures that, e.g., it 9581 // shows up in the right place in the vtable and that we diagnose problems 9582 // with the implicit exception specification. 9583 if (ClassDecl->isDynamicClass() || 9584 ClassDecl->needsOverloadResolutionForDestructor()) 9585 DeclareImplicitDestructor(ClassDecl); 9586 } 9587 9588 // C++2a [class.compare.default]p3: 9589 // If the member-specification does not explicitly declare any member or 9590 // friend named operator==, an == operator function is declared implicitly 9591 // for each defaulted three-way comparison operator function defined in the 9592 // member-specification 9593 // FIXME: Consider doing this lazily. 9594 if (getLangOpts().CPlusPlus2a) { 9595 llvm::SmallVector<FunctionDecl*, 4> DefaultedSpaceships; 9596 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 9597 DefaultedSpaceships); 9598 for (auto *FD : DefaultedSpaceships) 9599 DeclareImplicitEqualityComparison(ClassDecl, FD); 9600 } 9601 } 9602 9603 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 9604 if (!D) 9605 return 0; 9606 9607 // The order of template parameters is not important here. All names 9608 // get added to the same scope. 9609 SmallVector<TemplateParameterList *, 4> ParameterLists; 9610 9611 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9612 D = TD->getTemplatedDecl(); 9613 9614 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 9615 ParameterLists.push_back(PSD->getTemplateParameters()); 9616 9617 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 9618 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 9619 ParameterLists.push_back(DD->getTemplateParameterList(i)); 9620 9621 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9622 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 9623 ParameterLists.push_back(FTD->getTemplateParameters()); 9624 } 9625 } 9626 9627 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9628 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 9629 ParameterLists.push_back(TD->getTemplateParameterList(i)); 9630 9631 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 9632 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 9633 ParameterLists.push_back(CTD->getTemplateParameters()); 9634 } 9635 } 9636 9637 unsigned Count = 0; 9638 for (TemplateParameterList *Params : ParameterLists) { 9639 if (Params->size() > 0) 9640 // Ignore explicit specializations; they don't contribute to the template 9641 // depth. 9642 ++Count; 9643 for (NamedDecl *Param : *Params) { 9644 if (Param->getDeclName()) { 9645 S->AddDecl(Param); 9646 IdResolver.AddDecl(Param); 9647 } 9648 } 9649 } 9650 9651 return Count; 9652 } 9653 9654 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 9655 if (!RecordD) return; 9656 AdjustDeclIfTemplate(RecordD); 9657 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 9658 PushDeclContext(S, Record); 9659 } 9660 9661 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 9662 if (!RecordD) return; 9663 PopDeclContext(); 9664 } 9665 9666 /// This is used to implement the constant expression evaluation part of the 9667 /// attribute enable_if extension. There is nothing in standard C++ which would 9668 /// require reentering parameters. 9669 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 9670 if (!Param) 9671 return; 9672 9673 S->AddDecl(Param); 9674 if (Param->getDeclName()) 9675 IdResolver.AddDecl(Param); 9676 } 9677 9678 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 9679 /// parsing a top-level (non-nested) C++ class, and we are now 9680 /// parsing those parts of the given Method declaration that could 9681 /// not be parsed earlier (C++ [class.mem]p2), such as default 9682 /// arguments. This action should enter the scope of the given 9683 /// Method declaration as if we had just parsed the qualified method 9684 /// name. However, it should not bring the parameters into scope; 9685 /// that will be performed by ActOnDelayedCXXMethodParameter. 9686 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 9687 } 9688 9689 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 9690 /// C++ method declaration. We're (re-)introducing the given 9691 /// function parameter into scope for use in parsing later parts of 9692 /// the method declaration. For example, we could see an 9693 /// ActOnParamDefaultArgument event for this parameter. 9694 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 9695 if (!ParamD) 9696 return; 9697 9698 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 9699 9700 // If this parameter has an unparsed default argument, clear it out 9701 // to make way for the parsed default argument. 9702 if (Param->hasUnparsedDefaultArg()) 9703 Param->setDefaultArg(nullptr); 9704 9705 S->AddDecl(Param); 9706 if (Param->getDeclName()) 9707 IdResolver.AddDecl(Param); 9708 } 9709 9710 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 9711 /// processing the delayed method declaration for Method. The method 9712 /// declaration is now considered finished. There may be a separate 9713 /// ActOnStartOfFunctionDef action later (not necessarily 9714 /// immediately!) for this method, if it was also defined inside the 9715 /// class body. 9716 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 9717 if (!MethodD) 9718 return; 9719 9720 AdjustDeclIfTemplate(MethodD); 9721 9722 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 9723 9724 // Now that we have our default arguments, check the constructor 9725 // again. It could produce additional diagnostics or affect whether 9726 // the class has implicitly-declared destructors, among other 9727 // things. 9728 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 9729 CheckConstructor(Constructor); 9730 9731 // Check the default arguments, which we may have added. 9732 if (!Method->isInvalidDecl()) 9733 CheckCXXDefaultArguments(Method); 9734 } 9735 9736 // Emit the given diagnostic for each non-address-space qualifier. 9737 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 9738 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 9739 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9740 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 9741 bool DiagOccured = false; 9742 FTI.MethodQualifiers->forEachQualifier( 9743 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 9744 SourceLocation SL) { 9745 // This diagnostic should be emitted on any qualifier except an addr 9746 // space qualifier. However, forEachQualifier currently doesn't visit 9747 // addr space qualifiers, so there's no way to write this condition 9748 // right now; we just diagnose on everything. 9749 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 9750 DiagOccured = true; 9751 }); 9752 if (DiagOccured) 9753 D.setInvalidType(); 9754 } 9755 } 9756 9757 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 9758 /// the well-formedness of the constructor declarator @p D with type @p 9759 /// R. If there are any errors in the declarator, this routine will 9760 /// emit diagnostics and set the invalid bit to true. In any case, the type 9761 /// will be updated to reflect a well-formed type for the constructor and 9762 /// returned. 9763 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 9764 StorageClass &SC) { 9765 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9766 9767 // C++ [class.ctor]p3: 9768 // A constructor shall not be virtual (10.3) or static (9.4). A 9769 // constructor can be invoked for a const, volatile or const 9770 // volatile object. A constructor shall not be declared const, 9771 // volatile, or const volatile (9.3.2). 9772 if (isVirtual) { 9773 if (!D.isInvalidType()) 9774 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 9775 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 9776 << SourceRange(D.getIdentifierLoc()); 9777 D.setInvalidType(); 9778 } 9779 if (SC == SC_Static) { 9780 if (!D.isInvalidType()) 9781 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 9782 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 9783 << SourceRange(D.getIdentifierLoc()); 9784 D.setInvalidType(); 9785 SC = SC_None; 9786 } 9787 9788 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 9789 diagnoseIgnoredQualifiers( 9790 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 9791 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 9792 D.getDeclSpec().getRestrictSpecLoc(), 9793 D.getDeclSpec().getAtomicSpecLoc()); 9794 D.setInvalidType(); 9795 } 9796 9797 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 9798 9799 // C++0x [class.ctor]p4: 9800 // A constructor shall not be declared with a ref-qualifier. 9801 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9802 if (FTI.hasRefQualifier()) { 9803 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 9804 << FTI.RefQualifierIsLValueRef 9805 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 9806 D.setInvalidType(); 9807 } 9808 9809 // Rebuild the function type "R" without any type qualifiers (in 9810 // case any of the errors above fired) and with "void" as the 9811 // return type, since constructors don't have return types. 9812 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 9813 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 9814 return R; 9815 9816 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 9817 EPI.TypeQuals = Qualifiers(); 9818 EPI.RefQualifier = RQ_None; 9819 9820 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 9821 } 9822 9823 /// CheckConstructor - Checks a fully-formed constructor for 9824 /// well-formedness, issuing any diagnostics required. Returns true if 9825 /// the constructor declarator is invalid. 9826 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 9827 CXXRecordDecl *ClassDecl 9828 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 9829 if (!ClassDecl) 9830 return Constructor->setInvalidDecl(); 9831 9832 // C++ [class.copy]p3: 9833 // A declaration of a constructor for a class X is ill-formed if 9834 // its first parameter is of type (optionally cv-qualified) X and 9835 // either there are no other parameters or else all other 9836 // parameters have default arguments. 9837 if (!Constructor->isInvalidDecl() && 9838 ((Constructor->getNumParams() == 1) || 9839 (Constructor->getNumParams() > 1 && 9840 Constructor->getParamDecl(1)->hasDefaultArg())) && 9841 Constructor->getTemplateSpecializationKind() 9842 != TSK_ImplicitInstantiation) { 9843 QualType ParamType = Constructor->getParamDecl(0)->getType(); 9844 QualType ClassTy = Context.getTagDeclType(ClassDecl); 9845 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 9846 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 9847 const char *ConstRef 9848 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 9849 : " const &"; 9850 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 9851 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 9852 9853 // FIXME: Rather that making the constructor invalid, we should endeavor 9854 // to fix the type. 9855 Constructor->setInvalidDecl(); 9856 } 9857 } 9858 } 9859 9860 /// CheckDestructor - Checks a fully-formed destructor definition for 9861 /// well-formedness, issuing any diagnostics required. Returns true 9862 /// on error. 9863 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 9864 CXXRecordDecl *RD = Destructor->getParent(); 9865 9866 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 9867 SourceLocation Loc; 9868 9869 if (!Destructor->isImplicit()) 9870 Loc = Destructor->getLocation(); 9871 else 9872 Loc = RD->getLocation(); 9873 9874 // If we have a virtual destructor, look up the deallocation function 9875 if (FunctionDecl *OperatorDelete = 9876 FindDeallocationFunctionForDestructor(Loc, RD)) { 9877 Expr *ThisArg = nullptr; 9878 9879 // If the notional 'delete this' expression requires a non-trivial 9880 // conversion from 'this' to the type of a destroying operator delete's 9881 // first parameter, perform that conversion now. 9882 if (OperatorDelete->isDestroyingOperatorDelete()) { 9883 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 9884 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 9885 // C++ [class.dtor]p13: 9886 // ... as if for the expression 'delete this' appearing in a 9887 // non-virtual destructor of the destructor's class. 9888 ContextRAII SwitchContext(*this, Destructor); 9889 ExprResult This = 9890 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 9891 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 9892 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 9893 if (This.isInvalid()) { 9894 // FIXME: Register this as a context note so that it comes out 9895 // in the right order. 9896 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 9897 return true; 9898 } 9899 ThisArg = This.get(); 9900 } 9901 } 9902 9903 DiagnoseUseOfDecl(OperatorDelete, Loc); 9904 MarkFunctionReferenced(Loc, OperatorDelete); 9905 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 9906 } 9907 } 9908 9909 return false; 9910 } 9911 9912 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 9913 /// the well-formednes of the destructor declarator @p D with type @p 9914 /// R. If there are any errors in the declarator, this routine will 9915 /// emit diagnostics and set the declarator to invalid. Even if this happens, 9916 /// will be updated to reflect a well-formed type for the destructor and 9917 /// returned. 9918 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 9919 StorageClass& SC) { 9920 // C++ [class.dtor]p1: 9921 // [...] A typedef-name that names a class is a class-name 9922 // (7.1.3); however, a typedef-name that names a class shall not 9923 // be used as the identifier in the declarator for a destructor 9924 // declaration. 9925 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 9926 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 9927 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 9928 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 9929 else if (const TemplateSpecializationType *TST = 9930 DeclaratorType->getAs<TemplateSpecializationType>()) 9931 if (TST->isTypeAlias()) 9932 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 9933 << DeclaratorType << 1; 9934 9935 // C++ [class.dtor]p2: 9936 // A destructor is used to destroy objects of its class type. A 9937 // destructor takes no parameters, and no return type can be 9938 // specified for it (not even void). The address of a destructor 9939 // shall not be taken. A destructor shall not be static. A 9940 // destructor can be invoked for a const, volatile or const 9941 // volatile object. A destructor shall not be declared const, 9942 // volatile or const volatile (9.3.2). 9943 if (SC == SC_Static) { 9944 if (!D.isInvalidType()) 9945 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 9946 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 9947 << SourceRange(D.getIdentifierLoc()) 9948 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9949 9950 SC = SC_None; 9951 } 9952 if (!D.isInvalidType()) { 9953 // Destructors don't have return types, but the parser will 9954 // happily parse something like: 9955 // 9956 // class X { 9957 // float ~X(); 9958 // }; 9959 // 9960 // The return type will be eliminated later. 9961 if (D.getDeclSpec().hasTypeSpecifier()) 9962 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 9963 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 9964 << SourceRange(D.getIdentifierLoc()); 9965 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 9966 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 9967 SourceLocation(), 9968 D.getDeclSpec().getConstSpecLoc(), 9969 D.getDeclSpec().getVolatileSpecLoc(), 9970 D.getDeclSpec().getRestrictSpecLoc(), 9971 D.getDeclSpec().getAtomicSpecLoc()); 9972 D.setInvalidType(); 9973 } 9974 } 9975 9976 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 9977 9978 // C++0x [class.dtor]p2: 9979 // A destructor shall not be declared with a ref-qualifier. 9980 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9981 if (FTI.hasRefQualifier()) { 9982 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 9983 << FTI.RefQualifierIsLValueRef 9984 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 9985 D.setInvalidType(); 9986 } 9987 9988 // Make sure we don't have any parameters. 9989 if (FTIHasNonVoidParameters(FTI)) { 9990 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 9991 9992 // Delete the parameters. 9993 FTI.freeParams(); 9994 D.setInvalidType(); 9995 } 9996 9997 // Make sure the destructor isn't variadic. 9998 if (FTI.isVariadic) { 9999 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10000 D.setInvalidType(); 10001 } 10002 10003 // Rebuild the function type "R" without any type qualifiers or 10004 // parameters (in case any of the errors above fired) and with 10005 // "void" as the return type, since destructors don't have return 10006 // types. 10007 if (!D.isInvalidType()) 10008 return R; 10009 10010 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 10011 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10012 EPI.Variadic = false; 10013 EPI.TypeQuals = Qualifiers(); 10014 EPI.RefQualifier = RQ_None; 10015 return Context.getFunctionType(Context.VoidTy, None, EPI); 10016 } 10017 10018 static void extendLeft(SourceRange &R, SourceRange Before) { 10019 if (Before.isInvalid()) 10020 return; 10021 R.setBegin(Before.getBegin()); 10022 if (R.getEnd().isInvalid()) 10023 R.setEnd(Before.getEnd()); 10024 } 10025 10026 static void extendRight(SourceRange &R, SourceRange After) { 10027 if (After.isInvalid()) 10028 return; 10029 if (R.getBegin().isInvalid()) 10030 R.setBegin(After.getBegin()); 10031 R.setEnd(After.getEnd()); 10032 } 10033 10034 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10035 /// well-formednes of the conversion function declarator @p D with 10036 /// type @p R. If there are any errors in the declarator, this routine 10037 /// will emit diagnostics and return true. Otherwise, it will return 10038 /// false. Either way, the type @p R will be updated to reflect a 10039 /// well-formed type for the conversion operator. 10040 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10041 StorageClass& SC) { 10042 // C++ [class.conv.fct]p1: 10043 // Neither parameter types nor return type can be specified. The 10044 // type of a conversion function (8.3.5) is "function taking no 10045 // parameter returning conversion-type-id." 10046 if (SC == SC_Static) { 10047 if (!D.isInvalidType()) 10048 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10049 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10050 << D.getName().getSourceRange(); 10051 D.setInvalidType(); 10052 SC = SC_None; 10053 } 10054 10055 TypeSourceInfo *ConvTSI = nullptr; 10056 QualType ConvType = 10057 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10058 10059 const DeclSpec &DS = D.getDeclSpec(); 10060 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10061 // Conversion functions don't have return types, but the parser will 10062 // happily parse something like: 10063 // 10064 // class X { 10065 // float operator bool(); 10066 // }; 10067 // 10068 // The return type will be changed later anyway. 10069 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10070 << SourceRange(DS.getTypeSpecTypeLoc()) 10071 << SourceRange(D.getIdentifierLoc()); 10072 D.setInvalidType(); 10073 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10074 // It's also plausible that the user writes type qualifiers in the wrong 10075 // place, such as: 10076 // struct S { const operator int(); }; 10077 // FIXME: we could provide a fixit to move the qualifiers onto the 10078 // conversion type. 10079 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10080 << SourceRange(D.getIdentifierLoc()) << 0; 10081 D.setInvalidType(); 10082 } 10083 10084 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 10085 10086 // Make sure we don't have any parameters. 10087 if (Proto->getNumParams() > 0) { 10088 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10089 10090 // Delete the parameters. 10091 D.getFunctionTypeInfo().freeParams(); 10092 D.setInvalidType(); 10093 } else if (Proto->isVariadic()) { 10094 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10095 D.setInvalidType(); 10096 } 10097 10098 // Diagnose "&operator bool()" and other such nonsense. This 10099 // is actually a gcc extension which we don't support. 10100 if (Proto->getReturnType() != ConvType) { 10101 bool NeedsTypedef = false; 10102 SourceRange Before, After; 10103 10104 // Walk the chunks and extract information on them for our diagnostic. 10105 bool PastFunctionChunk = false; 10106 for (auto &Chunk : D.type_objects()) { 10107 switch (Chunk.Kind) { 10108 case DeclaratorChunk::Function: 10109 if (!PastFunctionChunk) { 10110 if (Chunk.Fun.HasTrailingReturnType) { 10111 TypeSourceInfo *TRT = nullptr; 10112 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10113 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10114 } 10115 PastFunctionChunk = true; 10116 break; 10117 } 10118 LLVM_FALLTHROUGH; 10119 case DeclaratorChunk::Array: 10120 NeedsTypedef = true; 10121 extendRight(After, Chunk.getSourceRange()); 10122 break; 10123 10124 case DeclaratorChunk::Pointer: 10125 case DeclaratorChunk::BlockPointer: 10126 case DeclaratorChunk::Reference: 10127 case DeclaratorChunk::MemberPointer: 10128 case DeclaratorChunk::Pipe: 10129 extendLeft(Before, Chunk.getSourceRange()); 10130 break; 10131 10132 case DeclaratorChunk::Paren: 10133 extendLeft(Before, Chunk.Loc); 10134 extendRight(After, Chunk.EndLoc); 10135 break; 10136 } 10137 } 10138 10139 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10140 After.isValid() ? After.getBegin() : 10141 D.getIdentifierLoc(); 10142 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10143 DB << Before << After; 10144 10145 if (!NeedsTypedef) { 10146 DB << /*don't need a typedef*/0; 10147 10148 // If we can provide a correct fix-it hint, do so. 10149 if (After.isInvalid() && ConvTSI) { 10150 SourceLocation InsertLoc = 10151 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10152 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10153 << FixItHint::CreateInsertionFromRange( 10154 InsertLoc, CharSourceRange::getTokenRange(Before)) 10155 << FixItHint::CreateRemoval(Before); 10156 } 10157 } else if (!Proto->getReturnType()->isDependentType()) { 10158 DB << /*typedef*/1 << Proto->getReturnType(); 10159 } else if (getLangOpts().CPlusPlus11) { 10160 DB << /*alias template*/2 << Proto->getReturnType(); 10161 } else { 10162 DB << /*might not be fixable*/3; 10163 } 10164 10165 // Recover by incorporating the other type chunks into the result type. 10166 // Note, this does *not* change the name of the function. This is compatible 10167 // with the GCC extension: 10168 // struct S { &operator int(); } s; 10169 // int &r = s.operator int(); // ok in GCC 10170 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10171 ConvType = Proto->getReturnType(); 10172 } 10173 10174 // C++ [class.conv.fct]p4: 10175 // The conversion-type-id shall not represent a function type nor 10176 // an array type. 10177 if (ConvType->isArrayType()) { 10178 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10179 ConvType = Context.getPointerType(ConvType); 10180 D.setInvalidType(); 10181 } else if (ConvType->isFunctionType()) { 10182 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10183 ConvType = Context.getPointerType(ConvType); 10184 D.setInvalidType(); 10185 } 10186 10187 // Rebuild the function type "R" without any parameters (in case any 10188 // of the errors above fired) and with the conversion type as the 10189 // return type. 10190 if (D.isInvalidType()) 10191 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10192 10193 // C++0x explicit conversion operators. 10194 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) 10195 Diag(DS.getExplicitSpecLoc(), 10196 getLangOpts().CPlusPlus11 10197 ? diag::warn_cxx98_compat_explicit_conversion_functions 10198 : diag::ext_explicit_conversion_functions) 10199 << SourceRange(DS.getExplicitSpecRange()); 10200 } 10201 10202 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10203 /// the declaration of the given C++ conversion function. This routine 10204 /// is responsible for recording the conversion function in the C++ 10205 /// class, if possible. 10206 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10207 assert(Conversion && "Expected to receive a conversion function declaration"); 10208 10209 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10210 10211 // Make sure we aren't redeclaring the conversion function. 10212 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10213 10214 // C++ [class.conv.fct]p1: 10215 // [...] A conversion function is never used to convert a 10216 // (possibly cv-qualified) object to the (possibly cv-qualified) 10217 // same object type (or a reference to it), to a (possibly 10218 // cv-qualified) base class of that type (or a reference to it), 10219 // or to (possibly cv-qualified) void. 10220 // FIXME: Suppress this warning if the conversion function ends up being a 10221 // virtual function that overrides a virtual function in a base class. 10222 QualType ClassType 10223 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10224 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10225 ConvType = ConvTypeRef->getPointeeType(); 10226 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10227 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10228 /* Suppress diagnostics for instantiations. */; 10229 else if (ConvType->isRecordType()) { 10230 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10231 if (ConvType == ClassType) 10232 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10233 << ClassType; 10234 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10235 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10236 << ClassType << ConvType; 10237 } else if (ConvType->isVoidType()) { 10238 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10239 << ClassType << ConvType; 10240 } 10241 10242 if (FunctionTemplateDecl *ConversionTemplate 10243 = Conversion->getDescribedFunctionTemplate()) 10244 return ConversionTemplate; 10245 10246 return Conversion; 10247 } 10248 10249 namespace { 10250 /// Utility class to accumulate and print a diagnostic listing the invalid 10251 /// specifier(s) on a declaration. 10252 struct BadSpecifierDiagnoser { 10253 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10254 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10255 ~BadSpecifierDiagnoser() { 10256 Diagnostic << Specifiers; 10257 } 10258 10259 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10260 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10261 } 10262 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10263 return check(SpecLoc, 10264 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10265 } 10266 void check(SourceLocation SpecLoc, const char *Spec) { 10267 if (SpecLoc.isInvalid()) return; 10268 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10269 if (!Specifiers.empty()) Specifiers += " "; 10270 Specifiers += Spec; 10271 } 10272 10273 Sema &S; 10274 Sema::SemaDiagnosticBuilder Diagnostic; 10275 std::string Specifiers; 10276 }; 10277 } 10278 10279 /// Check the validity of a declarator that we parsed for a deduction-guide. 10280 /// These aren't actually declarators in the grammar, so we need to check that 10281 /// the user didn't specify any pieces that are not part of the deduction-guide 10282 /// grammar. 10283 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10284 StorageClass &SC) { 10285 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10286 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10287 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10288 10289 // C++ [temp.deduct.guide]p3: 10290 // A deduction-gide shall be declared in the same scope as the 10291 // corresponding class template. 10292 if (!CurContext->getRedeclContext()->Equals( 10293 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10294 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10295 << GuidedTemplateDecl; 10296 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10297 } 10298 10299 auto &DS = D.getMutableDeclSpec(); 10300 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10301 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10302 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10303 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10304 BadSpecifierDiagnoser Diagnoser( 10305 *this, D.getIdentifierLoc(), 10306 diag::err_deduction_guide_invalid_specifier); 10307 10308 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10309 DS.ClearStorageClassSpecs(); 10310 SC = SC_None; 10311 10312 // 'explicit' is permitted. 10313 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10314 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10315 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10316 DS.ClearConstexprSpec(); 10317 10318 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10319 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10320 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10321 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10322 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10323 DS.ClearTypeQualifiers(); 10324 10325 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10326 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10327 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10328 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10329 DS.ClearTypeSpecType(); 10330 } 10331 10332 if (D.isInvalidType()) 10333 return; 10334 10335 // Check the declarator is simple enough. 10336 bool FoundFunction = false; 10337 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10338 if (Chunk.Kind == DeclaratorChunk::Paren) 10339 continue; 10340 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10341 Diag(D.getDeclSpec().getBeginLoc(), 10342 diag::err_deduction_guide_with_complex_decl) 10343 << D.getSourceRange(); 10344 break; 10345 } 10346 if (!Chunk.Fun.hasTrailingReturnType()) { 10347 Diag(D.getName().getBeginLoc(), 10348 diag::err_deduction_guide_no_trailing_return_type); 10349 break; 10350 } 10351 10352 // Check that the return type is written as a specialization of 10353 // the template specified as the deduction-guide's name. 10354 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10355 TypeSourceInfo *TSI = nullptr; 10356 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10357 assert(TSI && "deduction guide has valid type but invalid return type?"); 10358 bool AcceptableReturnType = false; 10359 bool MightInstantiateToSpecialization = false; 10360 if (auto RetTST = 10361 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10362 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10363 bool TemplateMatches = 10364 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10365 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10366 AcceptableReturnType = true; 10367 else { 10368 // This could still instantiate to the right type, unless we know it 10369 // names the wrong class template. 10370 auto *TD = SpecifiedName.getAsTemplateDecl(); 10371 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10372 !TemplateMatches); 10373 } 10374 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10375 MightInstantiateToSpecialization = true; 10376 } 10377 10378 if (!AcceptableReturnType) { 10379 Diag(TSI->getTypeLoc().getBeginLoc(), 10380 diag::err_deduction_guide_bad_trailing_return_type) 10381 << GuidedTemplate << TSI->getType() 10382 << MightInstantiateToSpecialization 10383 << TSI->getTypeLoc().getSourceRange(); 10384 } 10385 10386 // Keep going to check that we don't have any inner declarator pieces (we 10387 // could still have a function returning a pointer to a function). 10388 FoundFunction = true; 10389 } 10390 10391 if (D.isFunctionDefinition()) 10392 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10393 } 10394 10395 //===----------------------------------------------------------------------===// 10396 // Namespace Handling 10397 //===----------------------------------------------------------------------===// 10398 10399 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10400 /// reopened. 10401 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10402 SourceLocation Loc, 10403 IdentifierInfo *II, bool *IsInline, 10404 NamespaceDecl *PrevNS) { 10405 assert(*IsInline != PrevNS->isInline()); 10406 10407 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10408 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10409 // inline namespaces, with the intention of bringing names into namespace std. 10410 // 10411 // We support this just well enough to get that case working; this is not 10412 // sufficient to support reopening namespaces as inline in general. 10413 if (*IsInline && II && II->getName().startswith("__atomic") && 10414 S.getSourceManager().isInSystemHeader(Loc)) { 10415 // Mark all prior declarations of the namespace as inline. 10416 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10417 NS = NS->getPreviousDecl()) 10418 NS->setInline(*IsInline); 10419 // Patch up the lookup table for the containing namespace. This isn't really 10420 // correct, but it's good enough for this particular case. 10421 for (auto *I : PrevNS->decls()) 10422 if (auto *ND = dyn_cast<NamedDecl>(I)) 10423 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10424 return; 10425 } 10426 10427 if (PrevNS->isInline()) 10428 // The user probably just forgot the 'inline', so suggest that it 10429 // be added back. 10430 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10431 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10432 else 10433 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10434 10435 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10436 *IsInline = PrevNS->isInline(); 10437 } 10438 10439 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10440 /// definition. 10441 Decl *Sema::ActOnStartNamespaceDef( 10442 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10443 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10444 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10445 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10446 // For anonymous namespace, take the location of the left brace. 10447 SourceLocation Loc = II ? IdentLoc : LBrace; 10448 bool IsInline = InlineLoc.isValid(); 10449 bool IsInvalid = false; 10450 bool IsStd = false; 10451 bool AddToKnown = false; 10452 Scope *DeclRegionScope = NamespcScope->getParent(); 10453 10454 NamespaceDecl *PrevNS = nullptr; 10455 if (II) { 10456 // C++ [namespace.def]p2: 10457 // The identifier in an original-namespace-definition shall not 10458 // have been previously defined in the declarative region in 10459 // which the original-namespace-definition appears. The 10460 // identifier in an original-namespace-definition is the name of 10461 // the namespace. Subsequently in that declarative region, it is 10462 // treated as an original-namespace-name. 10463 // 10464 // Since namespace names are unique in their scope, and we don't 10465 // look through using directives, just look for any ordinary names 10466 // as if by qualified name lookup. 10467 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10468 ForExternalRedeclaration); 10469 LookupQualifiedName(R, CurContext->getRedeclContext()); 10470 NamedDecl *PrevDecl = 10471 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10472 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10473 10474 if (PrevNS) { 10475 // This is an extended namespace definition. 10476 if (IsInline != PrevNS->isInline()) 10477 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10478 &IsInline, PrevNS); 10479 } else if (PrevDecl) { 10480 // This is an invalid name redefinition. 10481 Diag(Loc, diag::err_redefinition_different_kind) 10482 << II; 10483 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10484 IsInvalid = true; 10485 // Continue on to push Namespc as current DeclContext and return it. 10486 } else if (II->isStr("std") && 10487 CurContext->getRedeclContext()->isTranslationUnit()) { 10488 // This is the first "real" definition of the namespace "std", so update 10489 // our cache of the "std" namespace to point at this definition. 10490 PrevNS = getStdNamespace(); 10491 IsStd = true; 10492 AddToKnown = !IsInline; 10493 } else { 10494 // We've seen this namespace for the first time. 10495 AddToKnown = !IsInline; 10496 } 10497 } else { 10498 // Anonymous namespaces. 10499 10500 // Determine whether the parent already has an anonymous namespace. 10501 DeclContext *Parent = CurContext->getRedeclContext(); 10502 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10503 PrevNS = TU->getAnonymousNamespace(); 10504 } else { 10505 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10506 PrevNS = ND->getAnonymousNamespace(); 10507 } 10508 10509 if (PrevNS && IsInline != PrevNS->isInline()) 10510 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10511 &IsInline, PrevNS); 10512 } 10513 10514 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10515 StartLoc, Loc, II, PrevNS); 10516 if (IsInvalid) 10517 Namespc->setInvalidDecl(); 10518 10519 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10520 AddPragmaAttributes(DeclRegionScope, Namespc); 10521 10522 // FIXME: Should we be merging attributes? 10523 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10524 PushNamespaceVisibilityAttr(Attr, Loc); 10525 10526 if (IsStd) 10527 StdNamespace = Namespc; 10528 if (AddToKnown) 10529 KnownNamespaces[Namespc] = false; 10530 10531 if (II) { 10532 PushOnScopeChains(Namespc, DeclRegionScope); 10533 } else { 10534 // Link the anonymous namespace into its parent. 10535 DeclContext *Parent = CurContext->getRedeclContext(); 10536 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10537 TU->setAnonymousNamespace(Namespc); 10538 } else { 10539 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10540 } 10541 10542 CurContext->addDecl(Namespc); 10543 10544 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10545 // behaves as if it were replaced by 10546 // namespace unique { /* empty body */ } 10547 // using namespace unique; 10548 // namespace unique { namespace-body } 10549 // where all occurrences of 'unique' in a translation unit are 10550 // replaced by the same identifier and this identifier differs 10551 // from all other identifiers in the entire program. 10552 10553 // We just create the namespace with an empty name and then add an 10554 // implicit using declaration, just like the standard suggests. 10555 // 10556 // CodeGen enforces the "universally unique" aspect by giving all 10557 // declarations semantically contained within an anonymous 10558 // namespace internal linkage. 10559 10560 if (!PrevNS) { 10561 UD = UsingDirectiveDecl::Create(Context, Parent, 10562 /* 'using' */ LBrace, 10563 /* 'namespace' */ SourceLocation(), 10564 /* qualifier */ NestedNameSpecifierLoc(), 10565 /* identifier */ SourceLocation(), 10566 Namespc, 10567 /* Ancestor */ Parent); 10568 UD->setImplicit(); 10569 Parent->addDecl(UD); 10570 } 10571 } 10572 10573 ActOnDocumentableDecl(Namespc); 10574 10575 // Although we could have an invalid decl (i.e. the namespace name is a 10576 // redefinition), push it as current DeclContext and try to continue parsing. 10577 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10578 // for the namespace has the declarations that showed up in that particular 10579 // namespace definition. 10580 PushDeclContext(NamespcScope, Namespc); 10581 return Namespc; 10582 } 10583 10584 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 10585 /// is a namespace alias, returns the namespace it points to. 10586 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 10587 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 10588 return AD->getNamespace(); 10589 return dyn_cast_or_null<NamespaceDecl>(D); 10590 } 10591 10592 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 10593 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 10594 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 10595 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 10596 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 10597 Namespc->setRBraceLoc(RBrace); 10598 PopDeclContext(); 10599 if (Namespc->hasAttr<VisibilityAttr>()) 10600 PopPragmaVisibility(true, RBrace); 10601 // If this namespace contains an export-declaration, export it now. 10602 if (DeferredExportedNamespaces.erase(Namespc)) 10603 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 10604 } 10605 10606 CXXRecordDecl *Sema::getStdBadAlloc() const { 10607 return cast_or_null<CXXRecordDecl>( 10608 StdBadAlloc.get(Context.getExternalSource())); 10609 } 10610 10611 EnumDecl *Sema::getStdAlignValT() const { 10612 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 10613 } 10614 10615 NamespaceDecl *Sema::getStdNamespace() const { 10616 return cast_or_null<NamespaceDecl>( 10617 StdNamespace.get(Context.getExternalSource())); 10618 } 10619 10620 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 10621 if (!StdExperimentalNamespaceCache) { 10622 if (auto Std = getStdNamespace()) { 10623 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 10624 SourceLocation(), LookupNamespaceName); 10625 if (!LookupQualifiedName(Result, Std) || 10626 !(StdExperimentalNamespaceCache = 10627 Result.getAsSingle<NamespaceDecl>())) 10628 Result.suppressDiagnostics(); 10629 } 10630 } 10631 return StdExperimentalNamespaceCache; 10632 } 10633 10634 namespace { 10635 10636 enum UnsupportedSTLSelect { 10637 USS_InvalidMember, 10638 USS_MissingMember, 10639 USS_NonTrivial, 10640 USS_Other 10641 }; 10642 10643 struct InvalidSTLDiagnoser { 10644 Sema &S; 10645 SourceLocation Loc; 10646 QualType TyForDiags; 10647 10648 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 10649 const VarDecl *VD = nullptr) { 10650 { 10651 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 10652 << TyForDiags << ((int)Sel); 10653 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 10654 assert(!Name.empty()); 10655 D << Name; 10656 } 10657 } 10658 if (Sel == USS_InvalidMember) { 10659 S.Diag(VD->getLocation(), diag::note_var_declared_here) 10660 << VD << VD->getSourceRange(); 10661 } 10662 return QualType(); 10663 } 10664 }; 10665 } // namespace 10666 10667 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 10668 SourceLocation Loc, 10669 ComparisonCategoryUsage Usage) { 10670 assert(getLangOpts().CPlusPlus && 10671 "Looking for comparison category type outside of C++."); 10672 10673 // Use an elaborated type for diagnostics which has a name containing the 10674 // prepended 'std' namespace but not any inline namespace names. 10675 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 10676 auto *NNS = 10677 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 10678 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 10679 }; 10680 10681 // Check if we've already successfully checked the comparison category type 10682 // before. If so, skip checking it again. 10683 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 10684 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 10685 // The only thing we need to check is that the type has a reachable 10686 // definition in the current context. 10687 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 10688 return QualType(); 10689 10690 return Info->getType(); 10691 } 10692 10693 // If lookup failed 10694 if (!Info) { 10695 std::string NameForDiags = "std::"; 10696 NameForDiags += ComparisonCategories::getCategoryString(Kind); 10697 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 10698 << NameForDiags << (int)Usage; 10699 return QualType(); 10700 } 10701 10702 assert(Info->Kind == Kind); 10703 assert(Info->Record); 10704 10705 // Update the Record decl in case we encountered a forward declaration on our 10706 // first pass. FIXME: This is a bit of a hack. 10707 if (Info->Record->hasDefinition()) 10708 Info->Record = Info->Record->getDefinition(); 10709 10710 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 10711 return QualType(); 10712 10713 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 10714 10715 if (!Info->Record->isTriviallyCopyable()) 10716 return UnsupportedSTLError(USS_NonTrivial); 10717 10718 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 10719 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 10720 // Tolerate empty base classes. 10721 if (Base->isEmpty()) 10722 continue; 10723 // Reject STL implementations which have at least one non-empty base. 10724 return UnsupportedSTLError(); 10725 } 10726 10727 // Check that the STL has implemented the types using a single integer field. 10728 // This expectation allows better codegen for builtin operators. We require: 10729 // (1) The class has exactly one field. 10730 // (2) The field is an integral or enumeration type. 10731 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 10732 if (std::distance(FIt, FEnd) != 1 || 10733 !FIt->getType()->isIntegralOrEnumerationType()) { 10734 return UnsupportedSTLError(); 10735 } 10736 10737 // Build each of the require values and store them in Info. 10738 for (ComparisonCategoryResult CCR : 10739 ComparisonCategories::getPossibleResultsForType(Kind)) { 10740 StringRef MemName = ComparisonCategories::getResultString(CCR); 10741 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 10742 10743 if (!ValInfo) 10744 return UnsupportedSTLError(USS_MissingMember, MemName); 10745 10746 VarDecl *VD = ValInfo->VD; 10747 assert(VD && "should not be null!"); 10748 10749 // Attempt to diagnose reasons why the STL definition of this type 10750 // might be foobar, including it failing to be a constant expression. 10751 // TODO Handle more ways the lookup or result can be invalid. 10752 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 10753 !VD->checkInitIsICE()) 10754 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 10755 10756 // Attempt to evaluate the var decl as a constant expression and extract 10757 // the value of its first field as a ICE. If this fails, the STL 10758 // implementation is not supported. 10759 if (!ValInfo->hasValidIntValue()) 10760 return UnsupportedSTLError(); 10761 10762 MarkVariableReferenced(Loc, VD); 10763 } 10764 10765 // We've successfully built the required types and expressions. Update 10766 // the cache and return the newly cached value. 10767 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 10768 return Info->getType(); 10769 } 10770 10771 /// Retrieve the special "std" namespace, which may require us to 10772 /// implicitly define the namespace. 10773 NamespaceDecl *Sema::getOrCreateStdNamespace() { 10774 if (!StdNamespace) { 10775 // The "std" namespace has not yet been defined, so build one implicitly. 10776 StdNamespace = NamespaceDecl::Create(Context, 10777 Context.getTranslationUnitDecl(), 10778 /*Inline=*/false, 10779 SourceLocation(), SourceLocation(), 10780 &PP.getIdentifierTable().get("std"), 10781 /*PrevDecl=*/nullptr); 10782 getStdNamespace()->setImplicit(true); 10783 } 10784 10785 return getStdNamespace(); 10786 } 10787 10788 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 10789 assert(getLangOpts().CPlusPlus && 10790 "Looking for std::initializer_list outside of C++."); 10791 10792 // We're looking for implicit instantiations of 10793 // template <typename E> class std::initializer_list. 10794 10795 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 10796 return false; 10797 10798 ClassTemplateDecl *Template = nullptr; 10799 const TemplateArgument *Arguments = nullptr; 10800 10801 if (const RecordType *RT = Ty->getAs<RecordType>()) { 10802 10803 ClassTemplateSpecializationDecl *Specialization = 10804 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 10805 if (!Specialization) 10806 return false; 10807 10808 Template = Specialization->getSpecializedTemplate(); 10809 Arguments = Specialization->getTemplateArgs().data(); 10810 } else if (const TemplateSpecializationType *TST = 10811 Ty->getAs<TemplateSpecializationType>()) { 10812 Template = dyn_cast_or_null<ClassTemplateDecl>( 10813 TST->getTemplateName().getAsTemplateDecl()); 10814 Arguments = TST->getArgs(); 10815 } 10816 if (!Template) 10817 return false; 10818 10819 if (!StdInitializerList) { 10820 // Haven't recognized std::initializer_list yet, maybe this is it. 10821 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 10822 if (TemplateClass->getIdentifier() != 10823 &PP.getIdentifierTable().get("initializer_list") || 10824 !getStdNamespace()->InEnclosingNamespaceSetOf( 10825 TemplateClass->getDeclContext())) 10826 return false; 10827 // This is a template called std::initializer_list, but is it the right 10828 // template? 10829 TemplateParameterList *Params = Template->getTemplateParameters(); 10830 if (Params->getMinRequiredArguments() != 1) 10831 return false; 10832 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 10833 return false; 10834 10835 // It's the right template. 10836 StdInitializerList = Template; 10837 } 10838 10839 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 10840 return false; 10841 10842 // This is an instance of std::initializer_list. Find the argument type. 10843 if (Element) 10844 *Element = Arguments[0].getAsType(); 10845 return true; 10846 } 10847 10848 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 10849 NamespaceDecl *Std = S.getStdNamespace(); 10850 if (!Std) { 10851 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 10852 return nullptr; 10853 } 10854 10855 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 10856 Loc, Sema::LookupOrdinaryName); 10857 if (!S.LookupQualifiedName(Result, Std)) { 10858 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 10859 return nullptr; 10860 } 10861 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 10862 if (!Template) { 10863 Result.suppressDiagnostics(); 10864 // We found something weird. Complain about the first thing we found. 10865 NamedDecl *Found = *Result.begin(); 10866 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 10867 return nullptr; 10868 } 10869 10870 // We found some template called std::initializer_list. Now verify that it's 10871 // correct. 10872 TemplateParameterList *Params = Template->getTemplateParameters(); 10873 if (Params->getMinRequiredArguments() != 1 || 10874 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 10875 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 10876 return nullptr; 10877 } 10878 10879 return Template; 10880 } 10881 10882 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 10883 if (!StdInitializerList) { 10884 StdInitializerList = LookupStdInitializerList(*this, Loc); 10885 if (!StdInitializerList) 10886 return QualType(); 10887 } 10888 10889 TemplateArgumentListInfo Args(Loc, Loc); 10890 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 10891 Context.getTrivialTypeSourceInfo(Element, 10892 Loc))); 10893 return Context.getCanonicalType( 10894 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 10895 } 10896 10897 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 10898 // C++ [dcl.init.list]p2: 10899 // A constructor is an initializer-list constructor if its first parameter 10900 // is of type std::initializer_list<E> or reference to possibly cv-qualified 10901 // std::initializer_list<E> for some type E, and either there are no other 10902 // parameters or else all other parameters have default arguments. 10903 if (Ctor->getNumParams() < 1 || 10904 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 10905 return false; 10906 10907 QualType ArgType = Ctor->getParamDecl(0)->getType(); 10908 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 10909 ArgType = RT->getPointeeType().getUnqualifiedType(); 10910 10911 return isStdInitializerList(ArgType, nullptr); 10912 } 10913 10914 /// Determine whether a using statement is in a context where it will be 10915 /// apply in all contexts. 10916 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 10917 switch (CurContext->getDeclKind()) { 10918 case Decl::TranslationUnit: 10919 return true; 10920 case Decl::LinkageSpec: 10921 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 10922 default: 10923 return false; 10924 } 10925 } 10926 10927 namespace { 10928 10929 // Callback to only accept typo corrections that are namespaces. 10930 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 10931 public: 10932 bool ValidateCandidate(const TypoCorrection &candidate) override { 10933 if (NamedDecl *ND = candidate.getCorrectionDecl()) 10934 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 10935 return false; 10936 } 10937 10938 std::unique_ptr<CorrectionCandidateCallback> clone() override { 10939 return std::make_unique<NamespaceValidatorCCC>(*this); 10940 } 10941 }; 10942 10943 } 10944 10945 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 10946 CXXScopeSpec &SS, 10947 SourceLocation IdentLoc, 10948 IdentifierInfo *Ident) { 10949 R.clear(); 10950 NamespaceValidatorCCC CCC{}; 10951 if (TypoCorrection Corrected = 10952 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 10953 Sema::CTK_ErrorRecovery)) { 10954 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 10955 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 10956 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 10957 Ident->getName().equals(CorrectedStr); 10958 S.diagnoseTypo(Corrected, 10959 S.PDiag(diag::err_using_directive_member_suggest) 10960 << Ident << DC << DroppedSpecifier << SS.getRange(), 10961 S.PDiag(diag::note_namespace_defined_here)); 10962 } else { 10963 S.diagnoseTypo(Corrected, 10964 S.PDiag(diag::err_using_directive_suggest) << Ident, 10965 S.PDiag(diag::note_namespace_defined_here)); 10966 } 10967 R.addDecl(Corrected.getFoundDecl()); 10968 return true; 10969 } 10970 return false; 10971 } 10972 10973 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 10974 SourceLocation NamespcLoc, CXXScopeSpec &SS, 10975 SourceLocation IdentLoc, 10976 IdentifierInfo *NamespcName, 10977 const ParsedAttributesView &AttrList) { 10978 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 10979 assert(NamespcName && "Invalid NamespcName."); 10980 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 10981 10982 // This can only happen along a recovery path. 10983 while (S->isTemplateParamScope()) 10984 S = S->getParent(); 10985 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 10986 10987 UsingDirectiveDecl *UDir = nullptr; 10988 NestedNameSpecifier *Qualifier = nullptr; 10989 if (SS.isSet()) 10990 Qualifier = SS.getScopeRep(); 10991 10992 // Lookup namespace name. 10993 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 10994 LookupParsedName(R, S, &SS); 10995 if (R.isAmbiguous()) 10996 return nullptr; 10997 10998 if (R.empty()) { 10999 R.clear(); 11000 // Allow "using namespace std;" or "using namespace ::std;" even if 11001 // "std" hasn't been defined yet, for GCC compatibility. 11002 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11003 NamespcName->isStr("std")) { 11004 Diag(IdentLoc, diag::ext_using_undefined_std); 11005 R.addDecl(getOrCreateStdNamespace()); 11006 R.resolveKind(); 11007 } 11008 // Otherwise, attempt typo correction. 11009 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11010 } 11011 11012 if (!R.empty()) { 11013 NamedDecl *Named = R.getRepresentativeDecl(); 11014 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11015 assert(NS && "expected namespace decl"); 11016 11017 // The use of a nested name specifier may trigger deprecation warnings. 11018 DiagnoseUseOfDecl(Named, IdentLoc); 11019 11020 // C++ [namespace.udir]p1: 11021 // A using-directive specifies that the names in the nominated 11022 // namespace can be used in the scope in which the 11023 // using-directive appears after the using-directive. During 11024 // unqualified name lookup (3.4.1), the names appear as if they 11025 // were declared in the nearest enclosing namespace which 11026 // contains both the using-directive and the nominated 11027 // namespace. [Note: in this context, "contains" means "contains 11028 // directly or indirectly". ] 11029 11030 // Find enclosing context containing both using-directive and 11031 // nominated namespace. 11032 DeclContext *CommonAncestor = NS; 11033 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11034 CommonAncestor = CommonAncestor->getParent(); 11035 11036 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11037 SS.getWithLocInContext(Context), 11038 IdentLoc, Named, CommonAncestor); 11039 11040 if (IsUsingDirectiveInToplevelContext(CurContext) && 11041 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11042 Diag(IdentLoc, diag::warn_using_directive_in_header); 11043 } 11044 11045 PushUsingDirective(S, UDir); 11046 } else { 11047 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11048 } 11049 11050 if (UDir) 11051 ProcessDeclAttributeList(S, UDir, AttrList); 11052 11053 return UDir; 11054 } 11055 11056 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11057 // If the scope has an associated entity and the using directive is at 11058 // namespace or translation unit scope, add the UsingDirectiveDecl into 11059 // its lookup structure so qualified name lookup can find it. 11060 DeclContext *Ctx = S->getEntity(); 11061 if (Ctx && !Ctx->isFunctionOrMethod()) 11062 Ctx->addDecl(UDir); 11063 else 11064 // Otherwise, it is at block scope. The using-directives will affect lookup 11065 // only to the end of the scope. 11066 S->PushUsingDirective(UDir); 11067 } 11068 11069 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11070 SourceLocation UsingLoc, 11071 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11072 UnqualifiedId &Name, 11073 SourceLocation EllipsisLoc, 11074 const ParsedAttributesView &AttrList) { 11075 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11076 11077 if (SS.isEmpty()) { 11078 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11079 return nullptr; 11080 } 11081 11082 switch (Name.getKind()) { 11083 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11084 case UnqualifiedIdKind::IK_Identifier: 11085 case UnqualifiedIdKind::IK_OperatorFunctionId: 11086 case UnqualifiedIdKind::IK_LiteralOperatorId: 11087 case UnqualifiedIdKind::IK_ConversionFunctionId: 11088 break; 11089 11090 case UnqualifiedIdKind::IK_ConstructorName: 11091 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11092 // C++11 inheriting constructors. 11093 Diag(Name.getBeginLoc(), 11094 getLangOpts().CPlusPlus11 11095 ? diag::warn_cxx98_compat_using_decl_constructor 11096 : diag::err_using_decl_constructor) 11097 << SS.getRange(); 11098 11099 if (getLangOpts().CPlusPlus11) break; 11100 11101 return nullptr; 11102 11103 case UnqualifiedIdKind::IK_DestructorName: 11104 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11105 return nullptr; 11106 11107 case UnqualifiedIdKind::IK_TemplateId: 11108 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11109 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11110 return nullptr; 11111 11112 case UnqualifiedIdKind::IK_DeductionGuideName: 11113 llvm_unreachable("cannot parse qualified deduction guide name"); 11114 } 11115 11116 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11117 DeclarationName TargetName = TargetNameInfo.getName(); 11118 if (!TargetName) 11119 return nullptr; 11120 11121 // Warn about access declarations. 11122 if (UsingLoc.isInvalid()) { 11123 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11124 ? diag::err_access_decl 11125 : diag::warn_access_decl_deprecated) 11126 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11127 } 11128 11129 if (EllipsisLoc.isInvalid()) { 11130 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11131 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11132 return nullptr; 11133 } else { 11134 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11135 !TargetNameInfo.containsUnexpandedParameterPack()) { 11136 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11137 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11138 EllipsisLoc = SourceLocation(); 11139 } 11140 } 11141 11142 NamedDecl *UD = 11143 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11144 SS, TargetNameInfo, EllipsisLoc, AttrList, 11145 /*IsInstantiation*/false); 11146 if (UD) 11147 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11148 11149 return UD; 11150 } 11151 11152 /// Determine whether a using declaration considers the given 11153 /// declarations as "equivalent", e.g., if they are redeclarations of 11154 /// the same entity or are both typedefs of the same type. 11155 static bool 11156 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11157 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11158 return true; 11159 11160 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11161 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11162 return Context.hasSameType(TD1->getUnderlyingType(), 11163 TD2->getUnderlyingType()); 11164 11165 return false; 11166 } 11167 11168 11169 /// Determines whether to create a using shadow decl for a particular 11170 /// decl, given the set of decls existing prior to this using lookup. 11171 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11172 const LookupResult &Previous, 11173 UsingShadowDecl *&PrevShadow) { 11174 // Diagnose finding a decl which is not from a base class of the 11175 // current class. We do this now because there are cases where this 11176 // function will silently decide not to build a shadow decl, which 11177 // will pre-empt further diagnostics. 11178 // 11179 // We don't need to do this in C++11 because we do the check once on 11180 // the qualifier. 11181 // 11182 // FIXME: diagnose the following if we care enough: 11183 // struct A { int foo; }; 11184 // struct B : A { using A::foo; }; 11185 // template <class T> struct C : A {}; 11186 // template <class T> struct D : C<T> { using B::foo; } // <--- 11187 // This is invalid (during instantiation) in C++03 because B::foo 11188 // resolves to the using decl in B, which is not a base class of D<T>. 11189 // We can't diagnose it immediately because C<T> is an unknown 11190 // specialization. The UsingShadowDecl in D<T> then points directly 11191 // to A::foo, which will look well-formed when we instantiate. 11192 // The right solution is to not collapse the shadow-decl chain. 11193 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11194 DeclContext *OrigDC = Orig->getDeclContext(); 11195 11196 // Handle enums and anonymous structs. 11197 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11198 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11199 while (OrigRec->isAnonymousStructOrUnion()) 11200 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11201 11202 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11203 if (OrigDC == CurContext) { 11204 Diag(Using->getLocation(), 11205 diag::err_using_decl_nested_name_specifier_is_current_class) 11206 << Using->getQualifierLoc().getSourceRange(); 11207 Diag(Orig->getLocation(), diag::note_using_decl_target); 11208 Using->setInvalidDecl(); 11209 return true; 11210 } 11211 11212 Diag(Using->getQualifierLoc().getBeginLoc(), 11213 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11214 << Using->getQualifier() 11215 << cast<CXXRecordDecl>(CurContext) 11216 << Using->getQualifierLoc().getSourceRange(); 11217 Diag(Orig->getLocation(), diag::note_using_decl_target); 11218 Using->setInvalidDecl(); 11219 return true; 11220 } 11221 } 11222 11223 if (Previous.empty()) return false; 11224 11225 NamedDecl *Target = Orig; 11226 if (isa<UsingShadowDecl>(Target)) 11227 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11228 11229 // If the target happens to be one of the previous declarations, we 11230 // don't have a conflict. 11231 // 11232 // FIXME: but we might be increasing its access, in which case we 11233 // should redeclare it. 11234 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11235 bool FoundEquivalentDecl = false; 11236 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11237 I != E; ++I) { 11238 NamedDecl *D = (*I)->getUnderlyingDecl(); 11239 // We can have UsingDecls in our Previous results because we use the same 11240 // LookupResult for checking whether the UsingDecl itself is a valid 11241 // redeclaration. 11242 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11243 continue; 11244 11245 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11246 // C++ [class.mem]p19: 11247 // If T is the name of a class, then [every named member other than 11248 // a non-static data member] shall have a name different from T 11249 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11250 !isa<IndirectFieldDecl>(Target) && 11251 !isa<UnresolvedUsingValueDecl>(Target) && 11252 DiagnoseClassNameShadow( 11253 CurContext, 11254 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11255 return true; 11256 } 11257 11258 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11259 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11260 PrevShadow = Shadow; 11261 FoundEquivalentDecl = true; 11262 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11263 // We don't conflict with an existing using shadow decl of an equivalent 11264 // declaration, but we're not a redeclaration of it. 11265 FoundEquivalentDecl = true; 11266 } 11267 11268 if (isVisible(D)) 11269 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11270 } 11271 11272 if (FoundEquivalentDecl) 11273 return false; 11274 11275 if (FunctionDecl *FD = Target->getAsFunction()) { 11276 NamedDecl *OldDecl = nullptr; 11277 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11278 /*IsForUsingDecl*/ true)) { 11279 case Ovl_Overload: 11280 return false; 11281 11282 case Ovl_NonFunction: 11283 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11284 break; 11285 11286 // We found a decl with the exact signature. 11287 case Ovl_Match: 11288 // If we're in a record, we want to hide the target, so we 11289 // return true (without a diagnostic) to tell the caller not to 11290 // build a shadow decl. 11291 if (CurContext->isRecord()) 11292 return true; 11293 11294 // If we're not in a record, this is an error. 11295 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11296 break; 11297 } 11298 11299 Diag(Target->getLocation(), diag::note_using_decl_target); 11300 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11301 Using->setInvalidDecl(); 11302 return true; 11303 } 11304 11305 // Target is not a function. 11306 11307 if (isa<TagDecl>(Target)) { 11308 // No conflict between a tag and a non-tag. 11309 if (!Tag) return false; 11310 11311 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11312 Diag(Target->getLocation(), diag::note_using_decl_target); 11313 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11314 Using->setInvalidDecl(); 11315 return true; 11316 } 11317 11318 // No conflict between a tag and a non-tag. 11319 if (!NonTag) return false; 11320 11321 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11322 Diag(Target->getLocation(), diag::note_using_decl_target); 11323 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11324 Using->setInvalidDecl(); 11325 return true; 11326 } 11327 11328 /// Determine whether a direct base class is a virtual base class. 11329 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11330 if (!Derived->getNumVBases()) 11331 return false; 11332 for (auto &B : Derived->bases()) 11333 if (B.getType()->getAsCXXRecordDecl() == Base) 11334 return B.isVirtual(); 11335 llvm_unreachable("not a direct base class"); 11336 } 11337 11338 /// Builds a shadow declaration corresponding to a 'using' declaration. 11339 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11340 UsingDecl *UD, 11341 NamedDecl *Orig, 11342 UsingShadowDecl *PrevDecl) { 11343 // If we resolved to another shadow declaration, just coalesce them. 11344 NamedDecl *Target = Orig; 11345 if (isa<UsingShadowDecl>(Target)) { 11346 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11347 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11348 } 11349 11350 NamedDecl *NonTemplateTarget = Target; 11351 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11352 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11353 11354 UsingShadowDecl *Shadow; 11355 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11356 bool IsVirtualBase = 11357 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11358 UD->getQualifier()->getAsRecordDecl()); 11359 Shadow = ConstructorUsingShadowDecl::Create( 11360 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11361 } else { 11362 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11363 Target); 11364 } 11365 UD->addShadowDecl(Shadow); 11366 11367 Shadow->setAccess(UD->getAccess()); 11368 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11369 Shadow->setInvalidDecl(); 11370 11371 Shadow->setPreviousDecl(PrevDecl); 11372 11373 if (S) 11374 PushOnScopeChains(Shadow, S); 11375 else 11376 CurContext->addDecl(Shadow); 11377 11378 11379 return Shadow; 11380 } 11381 11382 /// Hides a using shadow declaration. This is required by the current 11383 /// using-decl implementation when a resolvable using declaration in a 11384 /// class is followed by a declaration which would hide or override 11385 /// one or more of the using decl's targets; for example: 11386 /// 11387 /// struct Base { void foo(int); }; 11388 /// struct Derived : Base { 11389 /// using Base::foo; 11390 /// void foo(int); 11391 /// }; 11392 /// 11393 /// The governing language is C++03 [namespace.udecl]p12: 11394 /// 11395 /// When a using-declaration brings names from a base class into a 11396 /// derived class scope, member functions in the derived class 11397 /// override and/or hide member functions with the same name and 11398 /// parameter types in a base class (rather than conflicting). 11399 /// 11400 /// There are two ways to implement this: 11401 /// (1) optimistically create shadow decls when they're not hidden 11402 /// by existing declarations, or 11403 /// (2) don't create any shadow decls (or at least don't make them 11404 /// visible) until we've fully parsed/instantiated the class. 11405 /// The problem with (1) is that we might have to retroactively remove 11406 /// a shadow decl, which requires several O(n) operations because the 11407 /// decl structures are (very reasonably) not designed for removal. 11408 /// (2) avoids this but is very fiddly and phase-dependent. 11409 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11410 if (Shadow->getDeclName().getNameKind() == 11411 DeclarationName::CXXConversionFunctionName) 11412 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11413 11414 // Remove it from the DeclContext... 11415 Shadow->getDeclContext()->removeDecl(Shadow); 11416 11417 // ...and the scope, if applicable... 11418 if (S) { 11419 S->RemoveDecl(Shadow); 11420 IdResolver.RemoveDecl(Shadow); 11421 } 11422 11423 // ...and the using decl. 11424 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11425 11426 // TODO: complain somehow if Shadow was used. It shouldn't 11427 // be possible for this to happen, because...? 11428 } 11429 11430 /// Find the base specifier for a base class with the given type. 11431 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11432 QualType DesiredBase, 11433 bool &AnyDependentBases) { 11434 // Check whether the named type is a direct base class. 11435 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11436 .getUnqualifiedType(); 11437 for (auto &Base : Derived->bases()) { 11438 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11439 if (CanonicalDesiredBase == BaseType) 11440 return &Base; 11441 if (BaseType->isDependentType()) 11442 AnyDependentBases = true; 11443 } 11444 return nullptr; 11445 } 11446 11447 namespace { 11448 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11449 public: 11450 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11451 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11452 : HasTypenameKeyword(HasTypenameKeyword), 11453 IsInstantiation(IsInstantiation), OldNNS(NNS), 11454 RequireMemberOf(RequireMemberOf) {} 11455 11456 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11457 NamedDecl *ND = Candidate.getCorrectionDecl(); 11458 11459 // Keywords are not valid here. 11460 if (!ND || isa<NamespaceDecl>(ND)) 11461 return false; 11462 11463 // Completely unqualified names are invalid for a 'using' declaration. 11464 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11465 return false; 11466 11467 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11468 // reject. 11469 11470 if (RequireMemberOf) { 11471 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11472 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11473 // No-one ever wants a using-declaration to name an injected-class-name 11474 // of a base class, unless they're declaring an inheriting constructor. 11475 ASTContext &Ctx = ND->getASTContext(); 11476 if (!Ctx.getLangOpts().CPlusPlus11) 11477 return false; 11478 QualType FoundType = Ctx.getRecordType(FoundRecord); 11479 11480 // Check that the injected-class-name is named as a member of its own 11481 // type; we don't want to suggest 'using Derived::Base;', since that 11482 // means something else. 11483 NestedNameSpecifier *Specifier = 11484 Candidate.WillReplaceSpecifier() 11485 ? Candidate.getCorrectionSpecifier() 11486 : OldNNS; 11487 if (!Specifier->getAsType() || 11488 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11489 return false; 11490 11491 // Check that this inheriting constructor declaration actually names a 11492 // direct base class of the current class. 11493 bool AnyDependentBases = false; 11494 if (!findDirectBaseWithType(RequireMemberOf, 11495 Ctx.getRecordType(FoundRecord), 11496 AnyDependentBases) && 11497 !AnyDependentBases) 11498 return false; 11499 } else { 11500 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11501 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11502 return false; 11503 11504 // FIXME: Check that the base class member is accessible? 11505 } 11506 } else { 11507 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11508 if (FoundRecord && FoundRecord->isInjectedClassName()) 11509 return false; 11510 } 11511 11512 if (isa<TypeDecl>(ND)) 11513 return HasTypenameKeyword || !IsInstantiation; 11514 11515 return !HasTypenameKeyword; 11516 } 11517 11518 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11519 return std::make_unique<UsingValidatorCCC>(*this); 11520 } 11521 11522 private: 11523 bool HasTypenameKeyword; 11524 bool IsInstantiation; 11525 NestedNameSpecifier *OldNNS; 11526 CXXRecordDecl *RequireMemberOf; 11527 }; 11528 } // end anonymous namespace 11529 11530 /// Builds a using declaration. 11531 /// 11532 /// \param IsInstantiation - Whether this call arises from an 11533 /// instantiation of an unresolved using declaration. We treat 11534 /// the lookup differently for these declarations. 11535 NamedDecl *Sema::BuildUsingDeclaration( 11536 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11537 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11538 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11539 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11540 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11541 SourceLocation IdentLoc = NameInfo.getLoc(); 11542 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11543 11544 // FIXME: We ignore attributes for now. 11545 11546 // For an inheriting constructor declaration, the name of the using 11547 // declaration is the name of a constructor in this class, not in the 11548 // base class. 11549 DeclarationNameInfo UsingName = NameInfo; 11550 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11551 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11552 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11553 Context.getCanonicalType(Context.getRecordType(RD)))); 11554 11555 // Do the redeclaration lookup in the current scope. 11556 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11557 ForVisibleRedeclaration); 11558 Previous.setHideTags(false); 11559 if (S) { 11560 LookupName(Previous, S); 11561 11562 // It is really dumb that we have to do this. 11563 LookupResult::Filter F = Previous.makeFilter(); 11564 while (F.hasNext()) { 11565 NamedDecl *D = F.next(); 11566 if (!isDeclInScope(D, CurContext, S)) 11567 F.erase(); 11568 // If we found a local extern declaration that's not ordinarily visible, 11569 // and this declaration is being added to a non-block scope, ignore it. 11570 // We're only checking for scope conflicts here, not also for violations 11571 // of the linkage rules. 11572 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11573 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11574 F.erase(); 11575 } 11576 F.done(); 11577 } else { 11578 assert(IsInstantiation && "no scope in non-instantiation"); 11579 if (CurContext->isRecord()) 11580 LookupQualifiedName(Previous, CurContext); 11581 else { 11582 // No redeclaration check is needed here; in non-member contexts we 11583 // diagnosed all possible conflicts with other using-declarations when 11584 // building the template: 11585 // 11586 // For a dependent non-type using declaration, the only valid case is 11587 // if we instantiate to a single enumerator. We check for conflicts 11588 // between shadow declarations we introduce, and we check in the template 11589 // definition for conflicts between a non-type using declaration and any 11590 // other declaration, which together covers all cases. 11591 // 11592 // A dependent typename using declaration will never successfully 11593 // instantiate, since it will always name a class member, so we reject 11594 // that in the template definition. 11595 } 11596 } 11597 11598 // Check for invalid redeclarations. 11599 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 11600 SS, IdentLoc, Previous)) 11601 return nullptr; 11602 11603 // Check for bad qualifiers. 11604 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 11605 IdentLoc)) 11606 return nullptr; 11607 11608 DeclContext *LookupContext = computeDeclContext(SS); 11609 NamedDecl *D; 11610 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11611 if (!LookupContext || EllipsisLoc.isValid()) { 11612 if (HasTypenameKeyword) { 11613 // FIXME: not all declaration name kinds are legal here 11614 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 11615 UsingLoc, TypenameLoc, 11616 QualifierLoc, 11617 IdentLoc, NameInfo.getName(), 11618 EllipsisLoc); 11619 } else { 11620 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 11621 QualifierLoc, NameInfo, EllipsisLoc); 11622 } 11623 D->setAccess(AS); 11624 CurContext->addDecl(D); 11625 return D; 11626 } 11627 11628 auto Build = [&](bool Invalid) { 11629 UsingDecl *UD = 11630 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 11631 UsingName, HasTypenameKeyword); 11632 UD->setAccess(AS); 11633 CurContext->addDecl(UD); 11634 UD->setInvalidDecl(Invalid); 11635 return UD; 11636 }; 11637 auto BuildInvalid = [&]{ return Build(true); }; 11638 auto BuildValid = [&]{ return Build(false); }; 11639 11640 if (RequireCompleteDeclContext(SS, LookupContext)) 11641 return BuildInvalid(); 11642 11643 // Look up the target name. 11644 LookupResult R(*this, NameInfo, LookupOrdinaryName); 11645 11646 // Unlike most lookups, we don't always want to hide tag 11647 // declarations: tag names are visible through the using declaration 11648 // even if hidden by ordinary names, *except* in a dependent context 11649 // where it's important for the sanity of two-phase lookup. 11650 if (!IsInstantiation) 11651 R.setHideTags(false); 11652 11653 // For the purposes of this lookup, we have a base object type 11654 // equal to that of the current context. 11655 if (CurContext->isRecord()) { 11656 R.setBaseObjectType( 11657 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 11658 } 11659 11660 LookupQualifiedName(R, LookupContext); 11661 11662 // Try to correct typos if possible. If constructor name lookup finds no 11663 // results, that means the named class has no explicit constructors, and we 11664 // suppressed declaring implicit ones (probably because it's dependent or 11665 // invalid). 11666 if (R.empty() && 11667 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 11668 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 11669 // it will believe that glibc provides a ::gets in cases where it does not, 11670 // and will try to pull it into namespace std with a using-declaration. 11671 // Just ignore the using-declaration in that case. 11672 auto *II = NameInfo.getName().getAsIdentifierInfo(); 11673 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 11674 CurContext->isStdNamespace() && 11675 isa<TranslationUnitDecl>(LookupContext) && 11676 getSourceManager().isInSystemHeader(UsingLoc)) 11677 return nullptr; 11678 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 11679 dyn_cast<CXXRecordDecl>(CurContext)); 11680 if (TypoCorrection Corrected = 11681 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 11682 CTK_ErrorRecovery)) { 11683 // We reject candidates where DroppedSpecifier == true, hence the 11684 // literal '0' below. 11685 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 11686 << NameInfo.getName() << LookupContext << 0 11687 << SS.getRange()); 11688 11689 // If we picked a correction with no attached Decl we can't do anything 11690 // useful with it, bail out. 11691 NamedDecl *ND = Corrected.getCorrectionDecl(); 11692 if (!ND) 11693 return BuildInvalid(); 11694 11695 // If we corrected to an inheriting constructor, handle it as one. 11696 auto *RD = dyn_cast<CXXRecordDecl>(ND); 11697 if (RD && RD->isInjectedClassName()) { 11698 // The parent of the injected class name is the class itself. 11699 RD = cast<CXXRecordDecl>(RD->getParent()); 11700 11701 // Fix up the information we'll use to build the using declaration. 11702 if (Corrected.WillReplaceSpecifier()) { 11703 NestedNameSpecifierLocBuilder Builder; 11704 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 11705 QualifierLoc.getSourceRange()); 11706 QualifierLoc = Builder.getWithLocInContext(Context); 11707 } 11708 11709 // In this case, the name we introduce is the name of a derived class 11710 // constructor. 11711 auto *CurClass = cast<CXXRecordDecl>(CurContext); 11712 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11713 Context.getCanonicalType(Context.getRecordType(CurClass)))); 11714 UsingName.setNamedTypeInfo(nullptr); 11715 for (auto *Ctor : LookupConstructors(RD)) 11716 R.addDecl(Ctor); 11717 R.resolveKind(); 11718 } else { 11719 // FIXME: Pick up all the declarations if we found an overloaded 11720 // function. 11721 UsingName.setName(ND->getDeclName()); 11722 R.addDecl(ND); 11723 } 11724 } else { 11725 Diag(IdentLoc, diag::err_no_member) 11726 << NameInfo.getName() << LookupContext << SS.getRange(); 11727 return BuildInvalid(); 11728 } 11729 } 11730 11731 if (R.isAmbiguous()) 11732 return BuildInvalid(); 11733 11734 if (HasTypenameKeyword) { 11735 // If we asked for a typename and got a non-type decl, error out. 11736 if (!R.getAsSingle<TypeDecl>()) { 11737 Diag(IdentLoc, diag::err_using_typename_non_type); 11738 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11739 Diag((*I)->getUnderlyingDecl()->getLocation(), 11740 diag::note_using_decl_target); 11741 return BuildInvalid(); 11742 } 11743 } else { 11744 // If we asked for a non-typename and we got a type, error out, 11745 // but only if this is an instantiation of an unresolved using 11746 // decl. Otherwise just silently find the type name. 11747 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 11748 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 11749 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 11750 return BuildInvalid(); 11751 } 11752 } 11753 11754 // C++14 [namespace.udecl]p6: 11755 // A using-declaration shall not name a namespace. 11756 if (R.getAsSingle<NamespaceDecl>()) { 11757 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 11758 << SS.getRange(); 11759 return BuildInvalid(); 11760 } 11761 11762 // C++14 [namespace.udecl]p7: 11763 // A using-declaration shall not name a scoped enumerator. 11764 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 11765 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 11766 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 11767 << SS.getRange(); 11768 return BuildInvalid(); 11769 } 11770 } 11771 11772 UsingDecl *UD = BuildValid(); 11773 11774 // Some additional rules apply to inheriting constructors. 11775 if (UsingName.getName().getNameKind() == 11776 DeclarationName::CXXConstructorName) { 11777 // Suppress access diagnostics; the access check is instead performed at the 11778 // point of use for an inheriting constructor. 11779 R.suppressDiagnostics(); 11780 if (CheckInheritingConstructorUsingDecl(UD)) 11781 return UD; 11782 } 11783 11784 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 11785 UsingShadowDecl *PrevDecl = nullptr; 11786 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 11787 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 11788 } 11789 11790 return UD; 11791 } 11792 11793 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 11794 ArrayRef<NamedDecl *> Expansions) { 11795 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 11796 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 11797 isa<UsingPackDecl>(InstantiatedFrom)); 11798 11799 auto *UPD = 11800 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 11801 UPD->setAccess(InstantiatedFrom->getAccess()); 11802 CurContext->addDecl(UPD); 11803 return UPD; 11804 } 11805 11806 /// Additional checks for a using declaration referring to a constructor name. 11807 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 11808 assert(!UD->hasTypename() && "expecting a constructor name"); 11809 11810 const Type *SourceType = UD->getQualifier()->getAsType(); 11811 assert(SourceType && 11812 "Using decl naming constructor doesn't have type in scope spec."); 11813 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 11814 11815 // Check whether the named type is a direct base class. 11816 bool AnyDependentBases = false; 11817 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 11818 AnyDependentBases); 11819 if (!Base && !AnyDependentBases) { 11820 Diag(UD->getUsingLoc(), 11821 diag::err_using_decl_constructor_not_in_direct_base) 11822 << UD->getNameInfo().getSourceRange() 11823 << QualType(SourceType, 0) << TargetClass; 11824 UD->setInvalidDecl(); 11825 return true; 11826 } 11827 11828 if (Base) 11829 Base->setInheritConstructors(); 11830 11831 return false; 11832 } 11833 11834 /// Checks that the given using declaration is not an invalid 11835 /// redeclaration. Note that this is checking only for the using decl 11836 /// itself, not for any ill-formedness among the UsingShadowDecls. 11837 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 11838 bool HasTypenameKeyword, 11839 const CXXScopeSpec &SS, 11840 SourceLocation NameLoc, 11841 const LookupResult &Prev) { 11842 NestedNameSpecifier *Qual = SS.getScopeRep(); 11843 11844 // C++03 [namespace.udecl]p8: 11845 // C++0x [namespace.udecl]p10: 11846 // A using-declaration is a declaration and can therefore be used 11847 // repeatedly where (and only where) multiple declarations are 11848 // allowed. 11849 // 11850 // That's in non-member contexts. 11851 if (!CurContext->getRedeclContext()->isRecord()) { 11852 // A dependent qualifier outside a class can only ever resolve to an 11853 // enumeration type. Therefore it conflicts with any other non-type 11854 // declaration in the same scope. 11855 // FIXME: How should we check for dependent type-type conflicts at block 11856 // scope? 11857 if (Qual->isDependent() && !HasTypenameKeyword) { 11858 for (auto *D : Prev) { 11859 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 11860 bool OldCouldBeEnumerator = 11861 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 11862 Diag(NameLoc, 11863 OldCouldBeEnumerator ? diag::err_redefinition 11864 : diag::err_redefinition_different_kind) 11865 << Prev.getLookupName(); 11866 Diag(D->getLocation(), diag::note_previous_definition); 11867 return true; 11868 } 11869 } 11870 } 11871 return false; 11872 } 11873 11874 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 11875 NamedDecl *D = *I; 11876 11877 bool DTypename; 11878 NestedNameSpecifier *DQual; 11879 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 11880 DTypename = UD->hasTypename(); 11881 DQual = UD->getQualifier(); 11882 } else if (UnresolvedUsingValueDecl *UD 11883 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 11884 DTypename = false; 11885 DQual = UD->getQualifier(); 11886 } else if (UnresolvedUsingTypenameDecl *UD 11887 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 11888 DTypename = true; 11889 DQual = UD->getQualifier(); 11890 } else continue; 11891 11892 // using decls differ if one says 'typename' and the other doesn't. 11893 // FIXME: non-dependent using decls? 11894 if (HasTypenameKeyword != DTypename) continue; 11895 11896 // using decls differ if they name different scopes (but note that 11897 // template instantiation can cause this check to trigger when it 11898 // didn't before instantiation). 11899 if (Context.getCanonicalNestedNameSpecifier(Qual) != 11900 Context.getCanonicalNestedNameSpecifier(DQual)) 11901 continue; 11902 11903 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 11904 Diag(D->getLocation(), diag::note_using_decl) << 1; 11905 return true; 11906 } 11907 11908 return false; 11909 } 11910 11911 11912 /// Checks that the given nested-name qualifier used in a using decl 11913 /// in the current context is appropriately related to the current 11914 /// scope. If an error is found, diagnoses it and returns true. 11915 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 11916 bool HasTypename, 11917 const CXXScopeSpec &SS, 11918 const DeclarationNameInfo &NameInfo, 11919 SourceLocation NameLoc) { 11920 DeclContext *NamedContext = computeDeclContext(SS); 11921 11922 if (!CurContext->isRecord()) { 11923 // C++03 [namespace.udecl]p3: 11924 // C++0x [namespace.udecl]p8: 11925 // A using-declaration for a class member shall be a member-declaration. 11926 11927 // If we weren't able to compute a valid scope, it might validly be a 11928 // dependent class scope or a dependent enumeration unscoped scope. If 11929 // we have a 'typename' keyword, the scope must resolve to a class type. 11930 if ((HasTypename && !NamedContext) || 11931 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 11932 auto *RD = NamedContext 11933 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 11934 : nullptr; 11935 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 11936 RD = nullptr; 11937 11938 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 11939 << SS.getRange(); 11940 11941 // If we have a complete, non-dependent source type, try to suggest a 11942 // way to get the same effect. 11943 if (!RD) 11944 return true; 11945 11946 // Find what this using-declaration was referring to. 11947 LookupResult R(*this, NameInfo, LookupOrdinaryName); 11948 R.setHideTags(false); 11949 R.suppressDiagnostics(); 11950 LookupQualifiedName(R, RD); 11951 11952 if (R.getAsSingle<TypeDecl>()) { 11953 if (getLangOpts().CPlusPlus11) { 11954 // Convert 'using X::Y;' to 'using Y = X::Y;'. 11955 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 11956 << 0 // alias declaration 11957 << FixItHint::CreateInsertion(SS.getBeginLoc(), 11958 NameInfo.getName().getAsString() + 11959 " = "); 11960 } else { 11961 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 11962 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 11963 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 11964 << 1 // typedef declaration 11965 << FixItHint::CreateReplacement(UsingLoc, "typedef") 11966 << FixItHint::CreateInsertion( 11967 InsertLoc, " " + NameInfo.getName().getAsString()); 11968 } 11969 } else if (R.getAsSingle<VarDecl>()) { 11970 // Don't provide a fixit outside C++11 mode; we don't want to suggest 11971 // repeating the type of the static data member here. 11972 FixItHint FixIt; 11973 if (getLangOpts().CPlusPlus11) { 11974 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 11975 FixIt = FixItHint::CreateReplacement( 11976 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 11977 } 11978 11979 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 11980 << 2 // reference declaration 11981 << FixIt; 11982 } else if (R.getAsSingle<EnumConstantDecl>()) { 11983 // Don't provide a fixit outside C++11 mode; we don't want to suggest 11984 // repeating the type of the enumeration here, and we can't do so if 11985 // the type is anonymous. 11986 FixItHint FixIt; 11987 if (getLangOpts().CPlusPlus11) { 11988 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 11989 FixIt = FixItHint::CreateReplacement( 11990 UsingLoc, 11991 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 11992 } 11993 11994 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 11995 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 11996 << FixIt; 11997 } 11998 return true; 11999 } 12000 12001 // Otherwise, this might be valid. 12002 return false; 12003 } 12004 12005 // The current scope is a record. 12006 12007 // If the named context is dependent, we can't decide much. 12008 if (!NamedContext) { 12009 // FIXME: in C++0x, we can diagnose if we can prove that the 12010 // nested-name-specifier does not refer to a base class, which is 12011 // still possible in some cases. 12012 12013 // Otherwise we have to conservatively report that things might be 12014 // okay. 12015 return false; 12016 } 12017 12018 if (!NamedContext->isRecord()) { 12019 // Ideally this would point at the last name in the specifier, 12020 // but we don't have that level of source info. 12021 Diag(SS.getRange().getBegin(), 12022 diag::err_using_decl_nested_name_specifier_is_not_class) 12023 << SS.getScopeRep() << SS.getRange(); 12024 return true; 12025 } 12026 12027 if (!NamedContext->isDependentContext() && 12028 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12029 return true; 12030 12031 if (getLangOpts().CPlusPlus11) { 12032 // C++11 [namespace.udecl]p3: 12033 // In a using-declaration used as a member-declaration, the 12034 // nested-name-specifier shall name a base class of the class 12035 // being defined. 12036 12037 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12038 cast<CXXRecordDecl>(NamedContext))) { 12039 if (CurContext == NamedContext) { 12040 Diag(NameLoc, 12041 diag::err_using_decl_nested_name_specifier_is_current_class) 12042 << SS.getRange(); 12043 return true; 12044 } 12045 12046 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12047 Diag(SS.getRange().getBegin(), 12048 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12049 << SS.getScopeRep() 12050 << cast<CXXRecordDecl>(CurContext) 12051 << SS.getRange(); 12052 } 12053 return true; 12054 } 12055 12056 return false; 12057 } 12058 12059 // C++03 [namespace.udecl]p4: 12060 // A using-declaration used as a member-declaration shall refer 12061 // to a member of a base class of the class being defined [etc.]. 12062 12063 // Salient point: SS doesn't have to name a base class as long as 12064 // lookup only finds members from base classes. Therefore we can 12065 // diagnose here only if we can prove that that can't happen, 12066 // i.e. if the class hierarchies provably don't intersect. 12067 12068 // TODO: it would be nice if "definitely valid" results were cached 12069 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12070 // need to be repeated. 12071 12072 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12073 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12074 Bases.insert(Base); 12075 return true; 12076 }; 12077 12078 // Collect all bases. Return false if we find a dependent base. 12079 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12080 return false; 12081 12082 // Returns true if the base is dependent or is one of the accumulated base 12083 // classes. 12084 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12085 return !Bases.count(Base); 12086 }; 12087 12088 // Return false if the class has a dependent base or if it or one 12089 // of its bases is present in the base set of the current context. 12090 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12091 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12092 return false; 12093 12094 Diag(SS.getRange().getBegin(), 12095 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12096 << SS.getScopeRep() 12097 << cast<CXXRecordDecl>(CurContext) 12098 << SS.getRange(); 12099 12100 return true; 12101 } 12102 12103 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12104 MultiTemplateParamsArg TemplateParamLists, 12105 SourceLocation UsingLoc, UnqualifiedId &Name, 12106 const ParsedAttributesView &AttrList, 12107 TypeResult Type, Decl *DeclFromDeclSpec) { 12108 // Skip up to the relevant declaration scope. 12109 while (S->isTemplateParamScope()) 12110 S = S->getParent(); 12111 assert((S->getFlags() & Scope::DeclScope) && 12112 "got alias-declaration outside of declaration scope"); 12113 12114 if (Type.isInvalid()) 12115 return nullptr; 12116 12117 bool Invalid = false; 12118 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12119 TypeSourceInfo *TInfo = nullptr; 12120 GetTypeFromParser(Type.get(), &TInfo); 12121 12122 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12123 return nullptr; 12124 12125 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12126 UPPC_DeclarationType)) { 12127 Invalid = true; 12128 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12129 TInfo->getTypeLoc().getBeginLoc()); 12130 } 12131 12132 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12133 TemplateParamLists.size() 12134 ? forRedeclarationInCurContext() 12135 : ForVisibleRedeclaration); 12136 LookupName(Previous, S); 12137 12138 // Warn about shadowing the name of a template parameter. 12139 if (Previous.isSingleResult() && 12140 Previous.getFoundDecl()->isTemplateParameter()) { 12141 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12142 Previous.clear(); 12143 } 12144 12145 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12146 "name in alias declaration must be an identifier"); 12147 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12148 Name.StartLocation, 12149 Name.Identifier, TInfo); 12150 12151 NewTD->setAccess(AS); 12152 12153 if (Invalid) 12154 NewTD->setInvalidDecl(); 12155 12156 ProcessDeclAttributeList(S, NewTD, AttrList); 12157 AddPragmaAttributes(S, NewTD); 12158 12159 CheckTypedefForVariablyModifiedType(S, NewTD); 12160 Invalid |= NewTD->isInvalidDecl(); 12161 12162 bool Redeclaration = false; 12163 12164 NamedDecl *NewND; 12165 if (TemplateParamLists.size()) { 12166 TypeAliasTemplateDecl *OldDecl = nullptr; 12167 TemplateParameterList *OldTemplateParams = nullptr; 12168 12169 if (TemplateParamLists.size() != 1) { 12170 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12171 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12172 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12173 } 12174 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12175 12176 // Check that we can declare a template here. 12177 if (CheckTemplateDeclScope(S, TemplateParams)) 12178 return nullptr; 12179 12180 // Only consider previous declarations in the same scope. 12181 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12182 /*ExplicitInstantiationOrSpecialization*/false); 12183 if (!Previous.empty()) { 12184 Redeclaration = true; 12185 12186 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12187 if (!OldDecl && !Invalid) { 12188 Diag(UsingLoc, diag::err_redefinition_different_kind) 12189 << Name.Identifier; 12190 12191 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12192 if (OldD->getLocation().isValid()) 12193 Diag(OldD->getLocation(), diag::note_previous_definition); 12194 12195 Invalid = true; 12196 } 12197 12198 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12199 if (TemplateParameterListsAreEqual(TemplateParams, 12200 OldDecl->getTemplateParameters(), 12201 /*Complain=*/true, 12202 TPL_TemplateMatch)) 12203 OldTemplateParams = 12204 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12205 else 12206 Invalid = true; 12207 12208 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12209 if (!Invalid && 12210 !Context.hasSameType(OldTD->getUnderlyingType(), 12211 NewTD->getUnderlyingType())) { 12212 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12213 // but we can't reasonably accept it. 12214 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12215 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12216 if (OldTD->getLocation().isValid()) 12217 Diag(OldTD->getLocation(), diag::note_previous_definition); 12218 Invalid = true; 12219 } 12220 } 12221 } 12222 12223 // Merge any previous default template arguments into our parameters, 12224 // and check the parameter list. 12225 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12226 TPC_TypeAliasTemplate)) 12227 return nullptr; 12228 12229 TypeAliasTemplateDecl *NewDecl = 12230 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12231 Name.Identifier, TemplateParams, 12232 NewTD); 12233 NewTD->setDescribedAliasTemplate(NewDecl); 12234 12235 NewDecl->setAccess(AS); 12236 12237 if (Invalid) 12238 NewDecl->setInvalidDecl(); 12239 else if (OldDecl) { 12240 NewDecl->setPreviousDecl(OldDecl); 12241 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12242 } 12243 12244 NewND = NewDecl; 12245 } else { 12246 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12247 setTagNameForLinkagePurposes(TD, NewTD); 12248 handleTagNumbering(TD, S); 12249 } 12250 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12251 NewND = NewTD; 12252 } 12253 12254 PushOnScopeChains(NewND, S); 12255 ActOnDocumentableDecl(NewND); 12256 return NewND; 12257 } 12258 12259 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12260 SourceLocation AliasLoc, 12261 IdentifierInfo *Alias, CXXScopeSpec &SS, 12262 SourceLocation IdentLoc, 12263 IdentifierInfo *Ident) { 12264 12265 // Lookup the namespace name. 12266 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12267 LookupParsedName(R, S, &SS); 12268 12269 if (R.isAmbiguous()) 12270 return nullptr; 12271 12272 if (R.empty()) { 12273 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12274 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12275 return nullptr; 12276 } 12277 } 12278 assert(!R.isAmbiguous() && !R.empty()); 12279 NamedDecl *ND = R.getRepresentativeDecl(); 12280 12281 // Check if we have a previous declaration with the same name. 12282 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12283 ForVisibleRedeclaration); 12284 LookupName(PrevR, S); 12285 12286 // Check we're not shadowing a template parameter. 12287 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12288 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12289 PrevR.clear(); 12290 } 12291 12292 // Filter out any other lookup result from an enclosing scope. 12293 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12294 /*AllowInlineNamespace*/false); 12295 12296 // Find the previous declaration and check that we can redeclare it. 12297 NamespaceAliasDecl *Prev = nullptr; 12298 if (PrevR.isSingleResult()) { 12299 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12300 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12301 // We already have an alias with the same name that points to the same 12302 // namespace; check that it matches. 12303 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12304 Prev = AD; 12305 } else if (isVisible(PrevDecl)) { 12306 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12307 << Alias; 12308 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12309 << AD->getNamespace(); 12310 return nullptr; 12311 } 12312 } else if (isVisible(PrevDecl)) { 12313 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12314 ? diag::err_redefinition 12315 : diag::err_redefinition_different_kind; 12316 Diag(AliasLoc, DiagID) << Alias; 12317 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12318 return nullptr; 12319 } 12320 } 12321 12322 // The use of a nested name specifier may trigger deprecation warnings. 12323 DiagnoseUseOfDecl(ND, IdentLoc); 12324 12325 NamespaceAliasDecl *AliasDecl = 12326 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12327 Alias, SS.getWithLocInContext(Context), 12328 IdentLoc, ND); 12329 if (Prev) 12330 AliasDecl->setPreviousDecl(Prev); 12331 12332 PushOnScopeChains(AliasDecl, S); 12333 return AliasDecl; 12334 } 12335 12336 namespace { 12337 struct SpecialMemberExceptionSpecInfo 12338 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12339 SourceLocation Loc; 12340 Sema::ImplicitExceptionSpecification ExceptSpec; 12341 12342 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12343 Sema::CXXSpecialMember CSM, 12344 Sema::InheritedConstructorInfo *ICI, 12345 SourceLocation Loc) 12346 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12347 12348 bool visitBase(CXXBaseSpecifier *Base); 12349 bool visitField(FieldDecl *FD); 12350 12351 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12352 unsigned Quals); 12353 12354 void visitSubobjectCall(Subobject Subobj, 12355 Sema::SpecialMemberOverloadResult SMOR); 12356 }; 12357 } 12358 12359 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12360 auto *RT = Base->getType()->getAs<RecordType>(); 12361 if (!RT) 12362 return false; 12363 12364 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12365 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12366 if (auto *BaseCtor = SMOR.getMethod()) { 12367 visitSubobjectCall(Base, BaseCtor); 12368 return false; 12369 } 12370 12371 visitClassSubobject(BaseClass, Base, 0); 12372 return false; 12373 } 12374 12375 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12376 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12377 Expr *E = FD->getInClassInitializer(); 12378 if (!E) 12379 // FIXME: It's a little wasteful to build and throw away a 12380 // CXXDefaultInitExpr here. 12381 // FIXME: We should have a single context note pointing at Loc, and 12382 // this location should be MD->getLocation() instead, since that's 12383 // the location where we actually use the default init expression. 12384 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12385 if (E) 12386 ExceptSpec.CalledExpr(E); 12387 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12388 ->getAs<RecordType>()) { 12389 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12390 FD->getType().getCVRQualifiers()); 12391 } 12392 return false; 12393 } 12394 12395 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12396 Subobject Subobj, 12397 unsigned Quals) { 12398 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12399 bool IsMutable = Field && Field->isMutable(); 12400 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12401 } 12402 12403 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12404 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12405 // Note, if lookup fails, it doesn't matter what exception specification we 12406 // choose because the special member will be deleted. 12407 if (CXXMethodDecl *MD = SMOR.getMethod()) 12408 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12409 } 12410 12411 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12412 llvm::APSInt Result; 12413 ExprResult Converted = CheckConvertedConstantExpression( 12414 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12415 ExplicitSpec.setExpr(Converted.get()); 12416 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12417 ExplicitSpec.setKind(Result.getBoolValue() 12418 ? ExplicitSpecKind::ResolvedTrue 12419 : ExplicitSpecKind::ResolvedFalse); 12420 return true; 12421 } 12422 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12423 return false; 12424 } 12425 12426 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12427 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12428 if (!ExplicitExpr->isTypeDependent()) 12429 tryResolveExplicitSpecifier(ES); 12430 return ES; 12431 } 12432 12433 static Sema::ImplicitExceptionSpecification 12434 ComputeDefaultedSpecialMemberExceptionSpec( 12435 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12436 Sema::InheritedConstructorInfo *ICI) { 12437 ComputingExceptionSpec CES(S, MD, Loc); 12438 12439 CXXRecordDecl *ClassDecl = MD->getParent(); 12440 12441 // C++ [except.spec]p14: 12442 // An implicitly declared special member function (Clause 12) shall have an 12443 // exception-specification. [...] 12444 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12445 if (ClassDecl->isInvalidDecl()) 12446 return Info.ExceptSpec; 12447 12448 // FIXME: If this diagnostic fires, we're probably missing a check for 12449 // attempting to resolve an exception specification before it's known 12450 // at a higher level. 12451 if (S.RequireCompleteType(MD->getLocation(), 12452 S.Context.getRecordType(ClassDecl), 12453 diag::err_exception_spec_incomplete_type)) 12454 return Info.ExceptSpec; 12455 12456 // C++1z [except.spec]p7: 12457 // [Look for exceptions thrown by] a constructor selected [...] to 12458 // initialize a potentially constructed subobject, 12459 // C++1z [except.spec]p8: 12460 // The exception specification for an implicitly-declared destructor, or a 12461 // destructor without a noexcept-specifier, is potentially-throwing if and 12462 // only if any of the destructors for any of its potentially constructed 12463 // subojects is potentially throwing. 12464 // FIXME: We respect the first rule but ignore the "potentially constructed" 12465 // in the second rule to resolve a core issue (no number yet) that would have 12466 // us reject: 12467 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12468 // struct B : A {}; 12469 // struct C : B { void f(); }; 12470 // ... due to giving B::~B() a non-throwing exception specification. 12471 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12472 : Info.VisitAllBases); 12473 12474 return Info.ExceptSpec; 12475 } 12476 12477 namespace { 12478 /// RAII object to register a special member as being currently declared. 12479 struct DeclaringSpecialMember { 12480 Sema &S; 12481 Sema::SpecialMemberDecl D; 12482 Sema::ContextRAII SavedContext; 12483 bool WasAlreadyBeingDeclared; 12484 12485 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12486 : S(S), D(RD, CSM), SavedContext(S, RD) { 12487 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12488 if (WasAlreadyBeingDeclared) 12489 // This almost never happens, but if it does, ensure that our cache 12490 // doesn't contain a stale result. 12491 S.SpecialMemberCache.clear(); 12492 else { 12493 // Register a note to be produced if we encounter an error while 12494 // declaring the special member. 12495 Sema::CodeSynthesisContext Ctx; 12496 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12497 // FIXME: We don't have a location to use here. Using the class's 12498 // location maintains the fiction that we declare all special members 12499 // with the class, but (1) it's not clear that lying about that helps our 12500 // users understand what's going on, and (2) there may be outer contexts 12501 // on the stack (some of which are relevant) and printing them exposes 12502 // our lies. 12503 Ctx.PointOfInstantiation = RD->getLocation(); 12504 Ctx.Entity = RD; 12505 Ctx.SpecialMember = CSM; 12506 S.pushCodeSynthesisContext(Ctx); 12507 } 12508 } 12509 ~DeclaringSpecialMember() { 12510 if (!WasAlreadyBeingDeclared) { 12511 S.SpecialMembersBeingDeclared.erase(D); 12512 S.popCodeSynthesisContext(); 12513 } 12514 } 12515 12516 /// Are we already trying to declare this special member? 12517 bool isAlreadyBeingDeclared() const { 12518 return WasAlreadyBeingDeclared; 12519 } 12520 }; 12521 } 12522 12523 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12524 // Look up any existing declarations, but don't trigger declaration of all 12525 // implicit special members with this name. 12526 DeclarationName Name = FD->getDeclName(); 12527 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12528 ForExternalRedeclaration); 12529 for (auto *D : FD->getParent()->lookup(Name)) 12530 if (auto *Acceptable = R.getAcceptableDecl(D)) 12531 R.addDecl(Acceptable); 12532 R.resolveKind(); 12533 R.suppressDiagnostics(); 12534 12535 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12536 } 12537 12538 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12539 QualType ResultTy, 12540 ArrayRef<QualType> Args) { 12541 // Build an exception specification pointing back at this constructor. 12542 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12543 12544 LangAS AS = getDefaultCXXMethodAddrSpace(); 12545 if (AS != LangAS::Default) { 12546 EPI.TypeQuals.addAddressSpace(AS); 12547 } 12548 12549 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12550 SpecialMem->setType(QT); 12551 } 12552 12553 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12554 CXXRecordDecl *ClassDecl) { 12555 // C++ [class.ctor]p5: 12556 // A default constructor for a class X is a constructor of class X 12557 // that can be called without an argument. If there is no 12558 // user-declared constructor for class X, a default constructor is 12559 // implicitly declared. An implicitly-declared default constructor 12560 // is an inline public member of its class. 12561 assert(ClassDecl->needsImplicitDefaultConstructor() && 12562 "Should not build implicit default constructor!"); 12563 12564 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12565 if (DSM.isAlreadyBeingDeclared()) 12566 return nullptr; 12567 12568 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12569 CXXDefaultConstructor, 12570 false); 12571 12572 // Create the actual constructor declaration. 12573 CanQualType ClassType 12574 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12575 SourceLocation ClassLoc = ClassDecl->getLocation(); 12576 DeclarationName Name 12577 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12578 DeclarationNameInfo NameInfo(Name, ClassLoc); 12579 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12580 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12581 /*TInfo=*/nullptr, ExplicitSpecifier(), 12582 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12583 Constexpr ? CSK_constexpr : CSK_unspecified); 12584 DefaultCon->setAccess(AS_public); 12585 DefaultCon->setDefaulted(); 12586 12587 if (getLangOpts().CUDA) { 12588 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 12589 DefaultCon, 12590 /* ConstRHS */ false, 12591 /* Diagnose */ false); 12592 } 12593 12594 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 12595 12596 // We don't need to use SpecialMemberIsTrivial here; triviality for default 12597 // constructors is easy to compute. 12598 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 12599 12600 // Note that we have declared this constructor. 12601 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 12602 12603 Scope *S = getScopeForContext(ClassDecl); 12604 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 12605 12606 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 12607 SetDeclDeleted(DefaultCon, ClassLoc); 12608 12609 if (S) 12610 PushOnScopeChains(DefaultCon, S, false); 12611 ClassDecl->addDecl(DefaultCon); 12612 12613 return DefaultCon; 12614 } 12615 12616 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 12617 CXXConstructorDecl *Constructor) { 12618 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 12619 !Constructor->doesThisDeclarationHaveABody() && 12620 !Constructor->isDeleted()) && 12621 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 12622 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12623 return; 12624 12625 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12626 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 12627 12628 SynthesizedFunctionScope Scope(*this, Constructor); 12629 12630 // The exception specification is needed because we are defining the 12631 // function. 12632 ResolveExceptionSpec(CurrentLocation, 12633 Constructor->getType()->castAs<FunctionProtoType>()); 12634 MarkVTableUsed(CurrentLocation, ClassDecl); 12635 12636 // Add a context note for diagnostics produced after this point. 12637 Scope.addContextNote(CurrentLocation); 12638 12639 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 12640 Constructor->setInvalidDecl(); 12641 return; 12642 } 12643 12644 SourceLocation Loc = Constructor->getEndLoc().isValid() 12645 ? Constructor->getEndLoc() 12646 : Constructor->getLocation(); 12647 Constructor->setBody(new (Context) CompoundStmt(Loc)); 12648 Constructor->markUsed(Context); 12649 12650 if (ASTMutationListener *L = getASTMutationListener()) { 12651 L->CompletedImplicitDefinition(Constructor); 12652 } 12653 12654 DiagnoseUninitializedFields(*this, Constructor); 12655 } 12656 12657 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 12658 // Perform any delayed checks on exception specifications. 12659 CheckDelayedMemberExceptionSpecs(); 12660 } 12661 12662 /// Find or create the fake constructor we synthesize to model constructing an 12663 /// object of a derived class via a constructor of a base class. 12664 CXXConstructorDecl * 12665 Sema::findInheritingConstructor(SourceLocation Loc, 12666 CXXConstructorDecl *BaseCtor, 12667 ConstructorUsingShadowDecl *Shadow) { 12668 CXXRecordDecl *Derived = Shadow->getParent(); 12669 SourceLocation UsingLoc = Shadow->getLocation(); 12670 12671 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 12672 // For now we use the name of the base class constructor as a member of the 12673 // derived class to indicate a (fake) inherited constructor name. 12674 DeclarationName Name = BaseCtor->getDeclName(); 12675 12676 // Check to see if we already have a fake constructor for this inherited 12677 // constructor call. 12678 for (NamedDecl *Ctor : Derived->lookup(Name)) 12679 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 12680 ->getInheritedConstructor() 12681 .getConstructor(), 12682 BaseCtor)) 12683 return cast<CXXConstructorDecl>(Ctor); 12684 12685 DeclarationNameInfo NameInfo(Name, UsingLoc); 12686 TypeSourceInfo *TInfo = 12687 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 12688 FunctionProtoTypeLoc ProtoLoc = 12689 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 12690 12691 // Check the inherited constructor is valid and find the list of base classes 12692 // from which it was inherited. 12693 InheritedConstructorInfo ICI(*this, Loc, Shadow); 12694 12695 bool Constexpr = 12696 BaseCtor->isConstexpr() && 12697 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 12698 false, BaseCtor, &ICI); 12699 12700 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 12701 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 12702 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 12703 /*isImplicitlyDeclared=*/true, 12704 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 12705 InheritedConstructor(Shadow, BaseCtor)); 12706 if (Shadow->isInvalidDecl()) 12707 DerivedCtor->setInvalidDecl(); 12708 12709 // Build an unevaluated exception specification for this fake constructor. 12710 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 12711 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12712 EPI.ExceptionSpec.Type = EST_Unevaluated; 12713 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 12714 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 12715 FPT->getParamTypes(), EPI)); 12716 12717 // Build the parameter declarations. 12718 SmallVector<ParmVarDecl *, 16> ParamDecls; 12719 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 12720 TypeSourceInfo *TInfo = 12721 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 12722 ParmVarDecl *PD = ParmVarDecl::Create( 12723 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 12724 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 12725 PD->setScopeInfo(0, I); 12726 PD->setImplicit(); 12727 // Ensure attributes are propagated onto parameters (this matters for 12728 // format, pass_object_size, ...). 12729 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 12730 ParamDecls.push_back(PD); 12731 ProtoLoc.setParam(I, PD); 12732 } 12733 12734 // Set up the new constructor. 12735 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 12736 DerivedCtor->setAccess(BaseCtor->getAccess()); 12737 DerivedCtor->setParams(ParamDecls); 12738 Derived->addDecl(DerivedCtor); 12739 12740 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 12741 SetDeclDeleted(DerivedCtor, UsingLoc); 12742 12743 return DerivedCtor; 12744 } 12745 12746 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 12747 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 12748 Ctor->getInheritedConstructor().getShadowDecl()); 12749 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 12750 /*Diagnose*/true); 12751 } 12752 12753 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 12754 CXXConstructorDecl *Constructor) { 12755 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12756 assert(Constructor->getInheritedConstructor() && 12757 !Constructor->doesThisDeclarationHaveABody() && 12758 !Constructor->isDeleted()); 12759 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12760 return; 12761 12762 // Initializations are performed "as if by a defaulted default constructor", 12763 // so enter the appropriate scope. 12764 SynthesizedFunctionScope Scope(*this, Constructor); 12765 12766 // The exception specification is needed because we are defining the 12767 // function. 12768 ResolveExceptionSpec(CurrentLocation, 12769 Constructor->getType()->castAs<FunctionProtoType>()); 12770 MarkVTableUsed(CurrentLocation, ClassDecl); 12771 12772 // Add a context note for diagnostics produced after this point. 12773 Scope.addContextNote(CurrentLocation); 12774 12775 ConstructorUsingShadowDecl *Shadow = 12776 Constructor->getInheritedConstructor().getShadowDecl(); 12777 CXXConstructorDecl *InheritedCtor = 12778 Constructor->getInheritedConstructor().getConstructor(); 12779 12780 // [class.inhctor.init]p1: 12781 // initialization proceeds as if a defaulted default constructor is used to 12782 // initialize the D object and each base class subobject from which the 12783 // constructor was inherited 12784 12785 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 12786 CXXRecordDecl *RD = Shadow->getParent(); 12787 SourceLocation InitLoc = Shadow->getLocation(); 12788 12789 // Build explicit initializers for all base classes from which the 12790 // constructor was inherited. 12791 SmallVector<CXXCtorInitializer*, 8> Inits; 12792 for (bool VBase : {false, true}) { 12793 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 12794 if (B.isVirtual() != VBase) 12795 continue; 12796 12797 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 12798 if (!BaseRD) 12799 continue; 12800 12801 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 12802 if (!BaseCtor.first) 12803 continue; 12804 12805 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 12806 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 12807 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 12808 12809 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 12810 Inits.push_back(new (Context) CXXCtorInitializer( 12811 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 12812 SourceLocation())); 12813 } 12814 } 12815 12816 // We now proceed as if for a defaulted default constructor, with the relevant 12817 // initializers replaced. 12818 12819 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 12820 Constructor->setInvalidDecl(); 12821 return; 12822 } 12823 12824 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 12825 Constructor->markUsed(Context); 12826 12827 if (ASTMutationListener *L = getASTMutationListener()) { 12828 L->CompletedImplicitDefinition(Constructor); 12829 } 12830 12831 DiagnoseUninitializedFields(*this, Constructor); 12832 } 12833 12834 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 12835 // C++ [class.dtor]p2: 12836 // If a class has no user-declared destructor, a destructor is 12837 // declared implicitly. An implicitly-declared destructor is an 12838 // inline public member of its class. 12839 assert(ClassDecl->needsImplicitDestructor()); 12840 12841 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 12842 if (DSM.isAlreadyBeingDeclared()) 12843 return nullptr; 12844 12845 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12846 CXXDestructor, 12847 false); 12848 12849 // Create the actual destructor declaration. 12850 CanQualType ClassType 12851 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12852 SourceLocation ClassLoc = ClassDecl->getLocation(); 12853 DeclarationName Name 12854 = Context.DeclarationNames.getCXXDestructorName(ClassType); 12855 DeclarationNameInfo NameInfo(Name, ClassLoc); 12856 CXXDestructorDecl *Destructor = 12857 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 12858 QualType(), nullptr, /*isInline=*/true, 12859 /*isImplicitlyDeclared=*/true, 12860 Constexpr ? CSK_constexpr : CSK_unspecified); 12861 Destructor->setAccess(AS_public); 12862 Destructor->setDefaulted(); 12863 12864 if (getLangOpts().CUDA) { 12865 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 12866 Destructor, 12867 /* ConstRHS */ false, 12868 /* Diagnose */ false); 12869 } 12870 12871 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 12872 12873 // We don't need to use SpecialMemberIsTrivial here; triviality for 12874 // destructors is easy to compute. 12875 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 12876 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 12877 ClassDecl->hasTrivialDestructorForCall()); 12878 12879 // Note that we have declared this destructor. 12880 ++getASTContext().NumImplicitDestructorsDeclared; 12881 12882 Scope *S = getScopeForContext(ClassDecl); 12883 CheckImplicitSpecialMemberDeclaration(S, Destructor); 12884 12885 // We can't check whether an implicit destructor is deleted before we complete 12886 // the definition of the class, because its validity depends on the alignment 12887 // of the class. We'll check this from ActOnFields once the class is complete. 12888 if (ClassDecl->isCompleteDefinition() && 12889 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 12890 SetDeclDeleted(Destructor, ClassLoc); 12891 12892 // Introduce this destructor into its scope. 12893 if (S) 12894 PushOnScopeChains(Destructor, S, false); 12895 ClassDecl->addDecl(Destructor); 12896 12897 return Destructor; 12898 } 12899 12900 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 12901 CXXDestructorDecl *Destructor) { 12902 assert((Destructor->isDefaulted() && 12903 !Destructor->doesThisDeclarationHaveABody() && 12904 !Destructor->isDeleted()) && 12905 "DefineImplicitDestructor - call it for implicit default dtor"); 12906 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 12907 return; 12908 12909 CXXRecordDecl *ClassDecl = Destructor->getParent(); 12910 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 12911 12912 SynthesizedFunctionScope Scope(*this, Destructor); 12913 12914 // The exception specification is needed because we are defining the 12915 // function. 12916 ResolveExceptionSpec(CurrentLocation, 12917 Destructor->getType()->castAs<FunctionProtoType>()); 12918 MarkVTableUsed(CurrentLocation, ClassDecl); 12919 12920 // Add a context note for diagnostics produced after this point. 12921 Scope.addContextNote(CurrentLocation); 12922 12923 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12924 Destructor->getParent()); 12925 12926 if (CheckDestructor(Destructor)) { 12927 Destructor->setInvalidDecl(); 12928 return; 12929 } 12930 12931 SourceLocation Loc = Destructor->getEndLoc().isValid() 12932 ? Destructor->getEndLoc() 12933 : Destructor->getLocation(); 12934 Destructor->setBody(new (Context) CompoundStmt(Loc)); 12935 Destructor->markUsed(Context); 12936 12937 if (ASTMutationListener *L = getASTMutationListener()) { 12938 L->CompletedImplicitDefinition(Destructor); 12939 } 12940 } 12941 12942 /// Perform any semantic analysis which needs to be delayed until all 12943 /// pending class member declarations have been parsed. 12944 void Sema::ActOnFinishCXXMemberDecls() { 12945 // If the context is an invalid C++ class, just suppress these checks. 12946 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 12947 if (Record->isInvalidDecl()) { 12948 DelayedOverridingExceptionSpecChecks.clear(); 12949 DelayedEquivalentExceptionSpecChecks.clear(); 12950 return; 12951 } 12952 checkForMultipleExportedDefaultConstructors(*this, Record); 12953 } 12954 } 12955 12956 void Sema::ActOnFinishCXXNonNestedClass() { 12957 referenceDLLExportedClassMethods(); 12958 12959 if (!DelayedDllExportMemberFunctions.empty()) { 12960 SmallVector<CXXMethodDecl*, 4> WorkList; 12961 std::swap(DelayedDllExportMemberFunctions, WorkList); 12962 for (CXXMethodDecl *M : WorkList) { 12963 DefineImplicitSpecialMember(*this, M, M->getLocation()); 12964 12965 // Pass the method to the consumer to get emitted. This is not necessary 12966 // for explicit instantiation definitions, as they will get emitted 12967 // anyway. 12968 if (M->getParent()->getTemplateSpecializationKind() != 12969 TSK_ExplicitInstantiationDefinition) 12970 ActOnFinishInlineFunctionDef(M); 12971 } 12972 } 12973 } 12974 12975 void Sema::referenceDLLExportedClassMethods() { 12976 if (!DelayedDllExportClasses.empty()) { 12977 // Calling ReferenceDllExportedMembers might cause the current function to 12978 // be called again, so use a local copy of DelayedDllExportClasses. 12979 SmallVector<CXXRecordDecl *, 4> WorkList; 12980 std::swap(DelayedDllExportClasses, WorkList); 12981 for (CXXRecordDecl *Class : WorkList) 12982 ReferenceDllExportedMembers(*this, Class); 12983 } 12984 } 12985 12986 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 12987 assert(getLangOpts().CPlusPlus11 && 12988 "adjusting dtor exception specs was introduced in c++11"); 12989 12990 if (Destructor->isDependentContext()) 12991 return; 12992 12993 // C++11 [class.dtor]p3: 12994 // A declaration of a destructor that does not have an exception- 12995 // specification is implicitly considered to have the same exception- 12996 // specification as an implicit declaration. 12997 const FunctionProtoType *DtorType = Destructor->getType()-> 12998 getAs<FunctionProtoType>(); 12999 if (DtorType->hasExceptionSpec()) 13000 return; 13001 13002 // Replace the destructor's type, building off the existing one. Fortunately, 13003 // the only thing of interest in the destructor type is its extended info. 13004 // The return and arguments are fixed. 13005 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13006 EPI.ExceptionSpec.Type = EST_Unevaluated; 13007 EPI.ExceptionSpec.SourceDecl = Destructor; 13008 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13009 13010 // FIXME: If the destructor has a body that could throw, and the newly created 13011 // spec doesn't allow exceptions, we should emit a warning, because this 13012 // change in behavior can break conforming C++03 programs at runtime. 13013 // However, we don't have a body or an exception specification yet, so it 13014 // needs to be done somewhere else. 13015 } 13016 13017 namespace { 13018 /// An abstract base class for all helper classes used in building the 13019 // copy/move operators. These classes serve as factory functions and help us 13020 // avoid using the same Expr* in the AST twice. 13021 class ExprBuilder { 13022 ExprBuilder(const ExprBuilder&) = delete; 13023 ExprBuilder &operator=(const ExprBuilder&) = delete; 13024 13025 protected: 13026 static Expr *assertNotNull(Expr *E) { 13027 assert(E && "Expression construction must not fail."); 13028 return E; 13029 } 13030 13031 public: 13032 ExprBuilder() {} 13033 virtual ~ExprBuilder() {} 13034 13035 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13036 }; 13037 13038 class RefBuilder: public ExprBuilder { 13039 VarDecl *Var; 13040 QualType VarType; 13041 13042 public: 13043 Expr *build(Sema &S, SourceLocation Loc) const override { 13044 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13045 } 13046 13047 RefBuilder(VarDecl *Var, QualType VarType) 13048 : Var(Var), VarType(VarType) {} 13049 }; 13050 13051 class ThisBuilder: public ExprBuilder { 13052 public: 13053 Expr *build(Sema &S, SourceLocation Loc) const override { 13054 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13055 } 13056 }; 13057 13058 class CastBuilder: public ExprBuilder { 13059 const ExprBuilder &Builder; 13060 QualType Type; 13061 ExprValueKind Kind; 13062 const CXXCastPath &Path; 13063 13064 public: 13065 Expr *build(Sema &S, SourceLocation Loc) const override { 13066 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13067 CK_UncheckedDerivedToBase, Kind, 13068 &Path).get()); 13069 } 13070 13071 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13072 const CXXCastPath &Path) 13073 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13074 }; 13075 13076 class DerefBuilder: public ExprBuilder { 13077 const ExprBuilder &Builder; 13078 13079 public: 13080 Expr *build(Sema &S, SourceLocation Loc) const override { 13081 return assertNotNull( 13082 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13083 } 13084 13085 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13086 }; 13087 13088 class MemberBuilder: public ExprBuilder { 13089 const ExprBuilder &Builder; 13090 QualType Type; 13091 CXXScopeSpec SS; 13092 bool IsArrow; 13093 LookupResult &MemberLookup; 13094 13095 public: 13096 Expr *build(Sema &S, SourceLocation Loc) const override { 13097 return assertNotNull(S.BuildMemberReferenceExpr( 13098 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13099 nullptr, MemberLookup, nullptr, nullptr).get()); 13100 } 13101 13102 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13103 LookupResult &MemberLookup) 13104 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13105 MemberLookup(MemberLookup) {} 13106 }; 13107 13108 class MoveCastBuilder: public ExprBuilder { 13109 const ExprBuilder &Builder; 13110 13111 public: 13112 Expr *build(Sema &S, SourceLocation Loc) const override { 13113 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13114 } 13115 13116 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13117 }; 13118 13119 class LvalueConvBuilder: public ExprBuilder { 13120 const ExprBuilder &Builder; 13121 13122 public: 13123 Expr *build(Sema &S, SourceLocation Loc) const override { 13124 return assertNotNull( 13125 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13126 } 13127 13128 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13129 }; 13130 13131 class SubscriptBuilder: public ExprBuilder { 13132 const ExprBuilder &Base; 13133 const ExprBuilder &Index; 13134 13135 public: 13136 Expr *build(Sema &S, SourceLocation Loc) const override { 13137 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13138 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13139 } 13140 13141 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13142 : Base(Base), Index(Index) {} 13143 }; 13144 13145 } // end anonymous namespace 13146 13147 /// When generating a defaulted copy or move assignment operator, if a field 13148 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13149 /// do so. This optimization only applies for arrays of scalars, and for arrays 13150 /// of class type where the selected copy/move-assignment operator is trivial. 13151 static StmtResult 13152 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13153 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13154 // Compute the size of the memory buffer to be copied. 13155 QualType SizeType = S.Context.getSizeType(); 13156 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13157 S.Context.getTypeSizeInChars(T).getQuantity()); 13158 13159 // Take the address of the field references for "from" and "to". We 13160 // directly construct UnaryOperators here because semantic analysis 13161 // does not permit us to take the address of an xvalue. 13162 Expr *From = FromB.build(S, Loc); 13163 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 13164 S.Context.getPointerType(From->getType()), 13165 VK_RValue, OK_Ordinary, Loc, false); 13166 Expr *To = ToB.build(S, Loc); 13167 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 13168 S.Context.getPointerType(To->getType()), 13169 VK_RValue, OK_Ordinary, Loc, false); 13170 13171 const Type *E = T->getBaseElementTypeUnsafe(); 13172 bool NeedsCollectableMemCpy = 13173 E->isRecordType() && 13174 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13175 13176 // Create a reference to the __builtin_objc_memmove_collectable function 13177 StringRef MemCpyName = NeedsCollectableMemCpy ? 13178 "__builtin_objc_memmove_collectable" : 13179 "__builtin_memcpy"; 13180 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13181 Sema::LookupOrdinaryName); 13182 S.LookupName(R, S.TUScope, true); 13183 13184 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13185 if (!MemCpy) 13186 // Something went horribly wrong earlier, and we will have complained 13187 // about it. 13188 return StmtError(); 13189 13190 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13191 VK_RValue, Loc, nullptr); 13192 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13193 13194 Expr *CallArgs[] = { 13195 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13196 }; 13197 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13198 Loc, CallArgs, Loc); 13199 13200 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13201 return Call.getAs<Stmt>(); 13202 } 13203 13204 /// Builds a statement that copies/moves the given entity from \p From to 13205 /// \c To. 13206 /// 13207 /// This routine is used to copy/move the members of a class with an 13208 /// implicitly-declared copy/move assignment operator. When the entities being 13209 /// copied are arrays, this routine builds for loops to copy them. 13210 /// 13211 /// \param S The Sema object used for type-checking. 13212 /// 13213 /// \param Loc The location where the implicit copy/move is being generated. 13214 /// 13215 /// \param T The type of the expressions being copied/moved. Both expressions 13216 /// must have this type. 13217 /// 13218 /// \param To The expression we are copying/moving to. 13219 /// 13220 /// \param From The expression we are copying/moving from. 13221 /// 13222 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13223 /// Otherwise, it's a non-static member subobject. 13224 /// 13225 /// \param Copying Whether we're copying or moving. 13226 /// 13227 /// \param Depth Internal parameter recording the depth of the recursion. 13228 /// 13229 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13230 /// if a memcpy should be used instead. 13231 static StmtResult 13232 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13233 const ExprBuilder &To, const ExprBuilder &From, 13234 bool CopyingBaseSubobject, bool Copying, 13235 unsigned Depth = 0) { 13236 // C++11 [class.copy]p28: 13237 // Each subobject is assigned in the manner appropriate to its type: 13238 // 13239 // - if the subobject is of class type, as if by a call to operator= with 13240 // the subobject as the object expression and the corresponding 13241 // subobject of x as a single function argument (as if by explicit 13242 // qualification; that is, ignoring any possible virtual overriding 13243 // functions in more derived classes); 13244 // 13245 // C++03 [class.copy]p13: 13246 // - if the subobject is of class type, the copy assignment operator for 13247 // the class is used (as if by explicit qualification; that is, 13248 // ignoring any possible virtual overriding functions in more derived 13249 // classes); 13250 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13251 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13252 13253 // Look for operator=. 13254 DeclarationName Name 13255 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13256 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13257 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13258 13259 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13260 // operator. 13261 if (!S.getLangOpts().CPlusPlus11) { 13262 LookupResult::Filter F = OpLookup.makeFilter(); 13263 while (F.hasNext()) { 13264 NamedDecl *D = F.next(); 13265 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13266 if (Method->isCopyAssignmentOperator() || 13267 (!Copying && Method->isMoveAssignmentOperator())) 13268 continue; 13269 13270 F.erase(); 13271 } 13272 F.done(); 13273 } 13274 13275 // Suppress the protected check (C++ [class.protected]) for each of the 13276 // assignment operators we found. This strange dance is required when 13277 // we're assigning via a base classes's copy-assignment operator. To 13278 // ensure that we're getting the right base class subobject (without 13279 // ambiguities), we need to cast "this" to that subobject type; to 13280 // ensure that we don't go through the virtual call mechanism, we need 13281 // to qualify the operator= name with the base class (see below). However, 13282 // this means that if the base class has a protected copy assignment 13283 // operator, the protected member access check will fail. So, we 13284 // rewrite "protected" access to "public" access in this case, since we 13285 // know by construction that we're calling from a derived class. 13286 if (CopyingBaseSubobject) { 13287 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13288 L != LEnd; ++L) { 13289 if (L.getAccess() == AS_protected) 13290 L.setAccess(AS_public); 13291 } 13292 } 13293 13294 // Create the nested-name-specifier that will be used to qualify the 13295 // reference to operator=; this is required to suppress the virtual 13296 // call mechanism. 13297 CXXScopeSpec SS; 13298 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13299 SS.MakeTrivial(S.Context, 13300 NestedNameSpecifier::Create(S.Context, nullptr, false, 13301 CanonicalT), 13302 Loc); 13303 13304 // Create the reference to operator=. 13305 ExprResult OpEqualRef 13306 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13307 SS, /*TemplateKWLoc=*/SourceLocation(), 13308 /*FirstQualifierInScope=*/nullptr, 13309 OpLookup, 13310 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13311 /*SuppressQualifierCheck=*/true); 13312 if (OpEqualRef.isInvalid()) 13313 return StmtError(); 13314 13315 // Build the call to the assignment operator. 13316 13317 Expr *FromInst = From.build(S, Loc); 13318 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13319 OpEqualRef.getAs<Expr>(), 13320 Loc, FromInst, Loc); 13321 if (Call.isInvalid()) 13322 return StmtError(); 13323 13324 // If we built a call to a trivial 'operator=' while copying an array, 13325 // bail out. We'll replace the whole shebang with a memcpy. 13326 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13327 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13328 return StmtResult((Stmt*)nullptr); 13329 13330 // Convert to an expression-statement, and clean up any produced 13331 // temporaries. 13332 return S.ActOnExprStmt(Call); 13333 } 13334 13335 // - if the subobject is of scalar type, the built-in assignment 13336 // operator is used. 13337 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13338 if (!ArrayTy) { 13339 ExprResult Assignment = S.CreateBuiltinBinOp( 13340 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13341 if (Assignment.isInvalid()) 13342 return StmtError(); 13343 return S.ActOnExprStmt(Assignment); 13344 } 13345 13346 // - if the subobject is an array, each element is assigned, in the 13347 // manner appropriate to the element type; 13348 13349 // Construct a loop over the array bounds, e.g., 13350 // 13351 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13352 // 13353 // that will copy each of the array elements. 13354 QualType SizeType = S.Context.getSizeType(); 13355 13356 // Create the iteration variable. 13357 IdentifierInfo *IterationVarName = nullptr; 13358 { 13359 SmallString<8> Str; 13360 llvm::raw_svector_ostream OS(Str); 13361 OS << "__i" << Depth; 13362 IterationVarName = &S.Context.Idents.get(OS.str()); 13363 } 13364 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13365 IterationVarName, SizeType, 13366 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13367 SC_None); 13368 13369 // Initialize the iteration variable to zero. 13370 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13371 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13372 13373 // Creates a reference to the iteration variable. 13374 RefBuilder IterationVarRef(IterationVar, SizeType); 13375 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13376 13377 // Create the DeclStmt that holds the iteration variable. 13378 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13379 13380 // Subscript the "from" and "to" expressions with the iteration variable. 13381 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13382 MoveCastBuilder FromIndexMove(FromIndexCopy); 13383 const ExprBuilder *FromIndex; 13384 if (Copying) 13385 FromIndex = &FromIndexCopy; 13386 else 13387 FromIndex = &FromIndexMove; 13388 13389 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13390 13391 // Build the copy/move for an individual element of the array. 13392 StmtResult Copy = 13393 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13394 ToIndex, *FromIndex, CopyingBaseSubobject, 13395 Copying, Depth + 1); 13396 // Bail out if copying fails or if we determined that we should use memcpy. 13397 if (Copy.isInvalid() || !Copy.get()) 13398 return Copy; 13399 13400 // Create the comparison against the array bound. 13401 llvm::APInt Upper 13402 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13403 Expr *Comparison 13404 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 13405 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 13406 BO_NE, S.Context.BoolTy, 13407 VK_RValue, OK_Ordinary, Loc, FPOptions()); 13408 13409 // Create the pre-increment of the iteration variable. We can determine 13410 // whether the increment will overflow based on the value of the array 13411 // bound. 13412 Expr *Increment = new (S.Context) 13413 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 13414 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 13415 13416 // Construct the loop that copies all elements of this array. 13417 return S.ActOnForStmt( 13418 Loc, Loc, InitStmt, 13419 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13420 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13421 } 13422 13423 static StmtResult 13424 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13425 const ExprBuilder &To, const ExprBuilder &From, 13426 bool CopyingBaseSubobject, bool Copying) { 13427 // Maybe we should use a memcpy? 13428 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13429 T.isTriviallyCopyableType(S.Context)) 13430 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13431 13432 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13433 CopyingBaseSubobject, 13434 Copying, 0)); 13435 13436 // If we ended up picking a trivial assignment operator for an array of a 13437 // non-trivially-copyable class type, just emit a memcpy. 13438 if (!Result.isInvalid() && !Result.get()) 13439 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13440 13441 return Result; 13442 } 13443 13444 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13445 // Note: The following rules are largely analoguous to the copy 13446 // constructor rules. Note that virtual bases are not taken into account 13447 // for determining the argument type of the operator. Note also that 13448 // operators taking an object instead of a reference are allowed. 13449 assert(ClassDecl->needsImplicitCopyAssignment()); 13450 13451 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13452 if (DSM.isAlreadyBeingDeclared()) 13453 return nullptr; 13454 13455 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13456 LangAS AS = getDefaultCXXMethodAddrSpace(); 13457 if (AS != LangAS::Default) 13458 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13459 QualType RetType = Context.getLValueReferenceType(ArgType); 13460 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13461 if (Const) 13462 ArgType = ArgType.withConst(); 13463 13464 ArgType = Context.getLValueReferenceType(ArgType); 13465 13466 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13467 CXXCopyAssignment, 13468 Const); 13469 13470 // An implicitly-declared copy assignment operator is an inline public 13471 // member of its class. 13472 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13473 SourceLocation ClassLoc = ClassDecl->getLocation(); 13474 DeclarationNameInfo NameInfo(Name, ClassLoc); 13475 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13476 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13477 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13478 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13479 SourceLocation()); 13480 CopyAssignment->setAccess(AS_public); 13481 CopyAssignment->setDefaulted(); 13482 CopyAssignment->setImplicit(); 13483 13484 if (getLangOpts().CUDA) { 13485 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13486 CopyAssignment, 13487 /* ConstRHS */ Const, 13488 /* Diagnose */ false); 13489 } 13490 13491 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13492 13493 // Add the parameter to the operator. 13494 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13495 ClassLoc, ClassLoc, 13496 /*Id=*/nullptr, ArgType, 13497 /*TInfo=*/nullptr, SC_None, 13498 nullptr); 13499 CopyAssignment->setParams(FromParam); 13500 13501 CopyAssignment->setTrivial( 13502 ClassDecl->needsOverloadResolutionForCopyAssignment() 13503 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13504 : ClassDecl->hasTrivialCopyAssignment()); 13505 13506 // Note that we have added this copy-assignment operator. 13507 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13508 13509 Scope *S = getScopeForContext(ClassDecl); 13510 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13511 13512 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 13513 SetDeclDeleted(CopyAssignment, ClassLoc); 13514 13515 if (S) 13516 PushOnScopeChains(CopyAssignment, S, false); 13517 ClassDecl->addDecl(CopyAssignment); 13518 13519 return CopyAssignment; 13520 } 13521 13522 /// Diagnose an implicit copy operation for a class which is odr-used, but 13523 /// which is deprecated because the class has a user-declared copy constructor, 13524 /// copy assignment operator, or destructor. 13525 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13526 assert(CopyOp->isImplicit()); 13527 13528 CXXRecordDecl *RD = CopyOp->getParent(); 13529 CXXMethodDecl *UserDeclaredOperation = nullptr; 13530 13531 // In Microsoft mode, assignment operations don't affect constructors and 13532 // vice versa. 13533 if (RD->hasUserDeclaredDestructor()) { 13534 UserDeclaredOperation = RD->getDestructor(); 13535 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13536 RD->hasUserDeclaredCopyConstructor() && 13537 !S.getLangOpts().MSVCCompat) { 13538 // Find any user-declared copy constructor. 13539 for (auto *I : RD->ctors()) { 13540 if (I->isCopyConstructor()) { 13541 UserDeclaredOperation = I; 13542 break; 13543 } 13544 } 13545 assert(UserDeclaredOperation); 13546 } else if (isa<CXXConstructorDecl>(CopyOp) && 13547 RD->hasUserDeclaredCopyAssignment() && 13548 !S.getLangOpts().MSVCCompat) { 13549 // Find any user-declared move assignment operator. 13550 for (auto *I : RD->methods()) { 13551 if (I->isCopyAssignmentOperator()) { 13552 UserDeclaredOperation = I; 13553 break; 13554 } 13555 } 13556 assert(UserDeclaredOperation); 13557 } 13558 13559 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13560 S.Diag(UserDeclaredOperation->getLocation(), 13561 isa<CXXDestructorDecl>(UserDeclaredOperation) 13562 ? diag::warn_deprecated_copy_dtor_operation 13563 : diag::warn_deprecated_copy_operation) 13564 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 13565 } 13566 } 13567 13568 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 13569 CXXMethodDecl *CopyAssignOperator) { 13570 assert((CopyAssignOperator->isDefaulted() && 13571 CopyAssignOperator->isOverloadedOperator() && 13572 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 13573 !CopyAssignOperator->doesThisDeclarationHaveABody() && 13574 !CopyAssignOperator->isDeleted()) && 13575 "DefineImplicitCopyAssignment called for wrong function"); 13576 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 13577 return; 13578 13579 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 13580 if (ClassDecl->isInvalidDecl()) { 13581 CopyAssignOperator->setInvalidDecl(); 13582 return; 13583 } 13584 13585 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 13586 13587 // The exception specification is needed because we are defining the 13588 // function. 13589 ResolveExceptionSpec(CurrentLocation, 13590 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 13591 13592 // Add a context note for diagnostics produced after this point. 13593 Scope.addContextNote(CurrentLocation); 13594 13595 // C++11 [class.copy]p18: 13596 // The [definition of an implicitly declared copy assignment operator] is 13597 // deprecated if the class has a user-declared copy constructor or a 13598 // user-declared destructor. 13599 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 13600 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 13601 13602 // C++0x [class.copy]p30: 13603 // The implicitly-defined or explicitly-defaulted copy assignment operator 13604 // for a non-union class X performs memberwise copy assignment of its 13605 // subobjects. The direct base classes of X are assigned first, in the 13606 // order of their declaration in the base-specifier-list, and then the 13607 // immediate non-static data members of X are assigned, in the order in 13608 // which they were declared in the class definition. 13609 13610 // The statements that form the synthesized function body. 13611 SmallVector<Stmt*, 8> Statements; 13612 13613 // The parameter for the "other" object, which we are copying from. 13614 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 13615 Qualifiers OtherQuals = Other->getType().getQualifiers(); 13616 QualType OtherRefType = Other->getType(); 13617 if (const LValueReferenceType *OtherRef 13618 = OtherRefType->getAs<LValueReferenceType>()) { 13619 OtherRefType = OtherRef->getPointeeType(); 13620 OtherQuals = OtherRefType.getQualifiers(); 13621 } 13622 13623 // Our location for everything implicitly-generated. 13624 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 13625 ? CopyAssignOperator->getEndLoc() 13626 : CopyAssignOperator->getLocation(); 13627 13628 // Builds a DeclRefExpr for the "other" object. 13629 RefBuilder OtherRef(Other, OtherRefType); 13630 13631 // Builds the "this" pointer. 13632 ThisBuilder This; 13633 13634 // Assign base classes. 13635 bool Invalid = false; 13636 for (auto &Base : ClassDecl->bases()) { 13637 // Form the assignment: 13638 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 13639 QualType BaseType = Base.getType().getUnqualifiedType(); 13640 if (!BaseType->isRecordType()) { 13641 Invalid = true; 13642 continue; 13643 } 13644 13645 CXXCastPath BasePath; 13646 BasePath.push_back(&Base); 13647 13648 // Construct the "from" expression, which is an implicit cast to the 13649 // appropriately-qualified base type. 13650 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 13651 VK_LValue, BasePath); 13652 13653 // Dereference "this". 13654 DerefBuilder DerefThis(This); 13655 CastBuilder To(DerefThis, 13656 Context.getQualifiedType( 13657 BaseType, CopyAssignOperator->getMethodQualifiers()), 13658 VK_LValue, BasePath); 13659 13660 // Build the copy. 13661 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 13662 To, From, 13663 /*CopyingBaseSubobject=*/true, 13664 /*Copying=*/true); 13665 if (Copy.isInvalid()) { 13666 CopyAssignOperator->setInvalidDecl(); 13667 return; 13668 } 13669 13670 // Success! Record the copy. 13671 Statements.push_back(Copy.getAs<Expr>()); 13672 } 13673 13674 // Assign non-static members. 13675 for (auto *Field : ClassDecl->fields()) { 13676 // FIXME: We should form some kind of AST representation for the implied 13677 // memcpy in a union copy operation. 13678 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 13679 continue; 13680 13681 if (Field->isInvalidDecl()) { 13682 Invalid = true; 13683 continue; 13684 } 13685 13686 // Check for members of reference type; we can't copy those. 13687 if (Field->getType()->isReferenceType()) { 13688 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 13689 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 13690 Diag(Field->getLocation(), diag::note_declared_at); 13691 Invalid = true; 13692 continue; 13693 } 13694 13695 // Check for members of const-qualified, non-class type. 13696 QualType BaseType = Context.getBaseElementType(Field->getType()); 13697 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 13698 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 13699 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 13700 Diag(Field->getLocation(), diag::note_declared_at); 13701 Invalid = true; 13702 continue; 13703 } 13704 13705 // Suppress assigning zero-width bitfields. 13706 if (Field->isZeroLengthBitField(Context)) 13707 continue; 13708 13709 QualType FieldType = Field->getType().getNonReferenceType(); 13710 if (FieldType->isIncompleteArrayType()) { 13711 assert(ClassDecl->hasFlexibleArrayMember() && 13712 "Incomplete array type is not valid"); 13713 continue; 13714 } 13715 13716 // Build references to the field in the object we're copying from and to. 13717 CXXScopeSpec SS; // Intentionally empty 13718 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 13719 LookupMemberName); 13720 MemberLookup.addDecl(Field); 13721 MemberLookup.resolveKind(); 13722 13723 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 13724 13725 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 13726 13727 // Build the copy of this field. 13728 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 13729 To, From, 13730 /*CopyingBaseSubobject=*/false, 13731 /*Copying=*/true); 13732 if (Copy.isInvalid()) { 13733 CopyAssignOperator->setInvalidDecl(); 13734 return; 13735 } 13736 13737 // Success! Record the copy. 13738 Statements.push_back(Copy.getAs<Stmt>()); 13739 } 13740 13741 if (!Invalid) { 13742 // Add a "return *this;" 13743 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 13744 13745 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 13746 if (Return.isInvalid()) 13747 Invalid = true; 13748 else 13749 Statements.push_back(Return.getAs<Stmt>()); 13750 } 13751 13752 if (Invalid) { 13753 CopyAssignOperator->setInvalidDecl(); 13754 return; 13755 } 13756 13757 StmtResult Body; 13758 { 13759 CompoundScopeRAII CompoundScope(*this); 13760 Body = ActOnCompoundStmt(Loc, Loc, Statements, 13761 /*isStmtExpr=*/false); 13762 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 13763 } 13764 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 13765 CopyAssignOperator->markUsed(Context); 13766 13767 if (ASTMutationListener *L = getASTMutationListener()) { 13768 L->CompletedImplicitDefinition(CopyAssignOperator); 13769 } 13770 } 13771 13772 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 13773 assert(ClassDecl->needsImplicitMoveAssignment()); 13774 13775 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 13776 if (DSM.isAlreadyBeingDeclared()) 13777 return nullptr; 13778 13779 // Note: The following rules are largely analoguous to the move 13780 // constructor rules. 13781 13782 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13783 LangAS AS = getDefaultCXXMethodAddrSpace(); 13784 if (AS != LangAS::Default) 13785 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13786 QualType RetType = Context.getLValueReferenceType(ArgType); 13787 ArgType = Context.getRValueReferenceType(ArgType); 13788 13789 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13790 CXXMoveAssignment, 13791 false); 13792 13793 // An implicitly-declared move assignment operator is an inline public 13794 // member of its class. 13795 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13796 SourceLocation ClassLoc = ClassDecl->getLocation(); 13797 DeclarationNameInfo NameInfo(Name, ClassLoc); 13798 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 13799 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13800 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13801 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13802 SourceLocation()); 13803 MoveAssignment->setAccess(AS_public); 13804 MoveAssignment->setDefaulted(); 13805 MoveAssignment->setImplicit(); 13806 13807 if (getLangOpts().CUDA) { 13808 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 13809 MoveAssignment, 13810 /* ConstRHS */ false, 13811 /* Diagnose */ false); 13812 } 13813 13814 // Build an exception specification pointing back at this member. 13815 FunctionProtoType::ExtProtoInfo EPI = 13816 getImplicitMethodEPI(*this, MoveAssignment); 13817 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 13818 13819 // Add the parameter to the operator. 13820 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 13821 ClassLoc, ClassLoc, 13822 /*Id=*/nullptr, ArgType, 13823 /*TInfo=*/nullptr, SC_None, 13824 nullptr); 13825 MoveAssignment->setParams(FromParam); 13826 13827 MoveAssignment->setTrivial( 13828 ClassDecl->needsOverloadResolutionForMoveAssignment() 13829 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 13830 : ClassDecl->hasTrivialMoveAssignment()); 13831 13832 // Note that we have added this copy-assignment operator. 13833 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 13834 13835 Scope *S = getScopeForContext(ClassDecl); 13836 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 13837 13838 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 13839 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 13840 SetDeclDeleted(MoveAssignment, ClassLoc); 13841 } 13842 13843 if (S) 13844 PushOnScopeChains(MoveAssignment, S, false); 13845 ClassDecl->addDecl(MoveAssignment); 13846 13847 return MoveAssignment; 13848 } 13849 13850 /// Check if we're implicitly defining a move assignment operator for a class 13851 /// with virtual bases. Such a move assignment might move-assign the virtual 13852 /// base multiple times. 13853 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 13854 SourceLocation CurrentLocation) { 13855 assert(!Class->isDependentContext() && "should not define dependent move"); 13856 13857 // Only a virtual base could get implicitly move-assigned multiple times. 13858 // Only a non-trivial move assignment can observe this. We only want to 13859 // diagnose if we implicitly define an assignment operator that assigns 13860 // two base classes, both of which move-assign the same virtual base. 13861 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 13862 Class->getNumBases() < 2) 13863 return; 13864 13865 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 13866 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 13867 VBaseMap VBases; 13868 13869 for (auto &BI : Class->bases()) { 13870 Worklist.push_back(&BI); 13871 while (!Worklist.empty()) { 13872 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 13873 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 13874 13875 // If the base has no non-trivial move assignment operators, 13876 // we don't care about moves from it. 13877 if (!Base->hasNonTrivialMoveAssignment()) 13878 continue; 13879 13880 // If there's nothing virtual here, skip it. 13881 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 13882 continue; 13883 13884 // If we're not actually going to call a move assignment for this base, 13885 // or the selected move assignment is trivial, skip it. 13886 Sema::SpecialMemberOverloadResult SMOR = 13887 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 13888 /*ConstArg*/false, /*VolatileArg*/false, 13889 /*RValueThis*/true, /*ConstThis*/false, 13890 /*VolatileThis*/false); 13891 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 13892 !SMOR.getMethod()->isMoveAssignmentOperator()) 13893 continue; 13894 13895 if (BaseSpec->isVirtual()) { 13896 // We're going to move-assign this virtual base, and its move 13897 // assignment operator is not trivial. If this can happen for 13898 // multiple distinct direct bases of Class, diagnose it. (If it 13899 // only happens in one base, we'll diagnose it when synthesizing 13900 // that base class's move assignment operator.) 13901 CXXBaseSpecifier *&Existing = 13902 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 13903 .first->second; 13904 if (Existing && Existing != &BI) { 13905 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 13906 << Class << Base; 13907 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 13908 << (Base->getCanonicalDecl() == 13909 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 13910 << Base << Existing->getType() << Existing->getSourceRange(); 13911 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 13912 << (Base->getCanonicalDecl() == 13913 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 13914 << Base << BI.getType() << BaseSpec->getSourceRange(); 13915 13916 // Only diagnose each vbase once. 13917 Existing = nullptr; 13918 } 13919 } else { 13920 // Only walk over bases that have defaulted move assignment operators. 13921 // We assume that any user-provided move assignment operator handles 13922 // the multiple-moves-of-vbase case itself somehow. 13923 if (!SMOR.getMethod()->isDefaulted()) 13924 continue; 13925 13926 // We're going to move the base classes of Base. Add them to the list. 13927 for (auto &BI : Base->bases()) 13928 Worklist.push_back(&BI); 13929 } 13930 } 13931 } 13932 } 13933 13934 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 13935 CXXMethodDecl *MoveAssignOperator) { 13936 assert((MoveAssignOperator->isDefaulted() && 13937 MoveAssignOperator->isOverloadedOperator() && 13938 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 13939 !MoveAssignOperator->doesThisDeclarationHaveABody() && 13940 !MoveAssignOperator->isDeleted()) && 13941 "DefineImplicitMoveAssignment called for wrong function"); 13942 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 13943 return; 13944 13945 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 13946 if (ClassDecl->isInvalidDecl()) { 13947 MoveAssignOperator->setInvalidDecl(); 13948 return; 13949 } 13950 13951 // C++0x [class.copy]p28: 13952 // The implicitly-defined or move assignment operator for a non-union class 13953 // X performs memberwise move assignment of its subobjects. The direct base 13954 // classes of X are assigned first, in the order of their declaration in the 13955 // base-specifier-list, and then the immediate non-static data members of X 13956 // are assigned, in the order in which they were declared in the class 13957 // definition. 13958 13959 // Issue a warning if our implicit move assignment operator will move 13960 // from a virtual base more than once. 13961 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 13962 13963 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 13964 13965 // The exception specification is needed because we are defining the 13966 // function. 13967 ResolveExceptionSpec(CurrentLocation, 13968 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 13969 13970 // Add a context note for diagnostics produced after this point. 13971 Scope.addContextNote(CurrentLocation); 13972 13973 // The statements that form the synthesized function body. 13974 SmallVector<Stmt*, 8> Statements; 13975 13976 // The parameter for the "other" object, which we are move from. 13977 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 13978 QualType OtherRefType = Other->getType()-> 13979 getAs<RValueReferenceType>()->getPointeeType(); 13980 13981 // Our location for everything implicitly-generated. 13982 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 13983 ? MoveAssignOperator->getEndLoc() 13984 : MoveAssignOperator->getLocation(); 13985 13986 // Builds a reference to the "other" object. 13987 RefBuilder OtherRef(Other, OtherRefType); 13988 // Cast to rvalue. 13989 MoveCastBuilder MoveOther(OtherRef); 13990 13991 // Builds the "this" pointer. 13992 ThisBuilder This; 13993 13994 // Assign base classes. 13995 bool Invalid = false; 13996 for (auto &Base : ClassDecl->bases()) { 13997 // C++11 [class.copy]p28: 13998 // It is unspecified whether subobjects representing virtual base classes 13999 // are assigned more than once by the implicitly-defined copy assignment 14000 // operator. 14001 // FIXME: Do not assign to a vbase that will be assigned by some other base 14002 // class. For a move-assignment, this can result in the vbase being moved 14003 // multiple times. 14004 14005 // Form the assignment: 14006 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14007 QualType BaseType = Base.getType().getUnqualifiedType(); 14008 if (!BaseType->isRecordType()) { 14009 Invalid = true; 14010 continue; 14011 } 14012 14013 CXXCastPath BasePath; 14014 BasePath.push_back(&Base); 14015 14016 // Construct the "from" expression, which is an implicit cast to the 14017 // appropriately-qualified base type. 14018 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14019 14020 // Dereference "this". 14021 DerefBuilder DerefThis(This); 14022 14023 // Implicitly cast "this" to the appropriately-qualified base type. 14024 CastBuilder To(DerefThis, 14025 Context.getQualifiedType( 14026 BaseType, MoveAssignOperator->getMethodQualifiers()), 14027 VK_LValue, BasePath); 14028 14029 // Build the move. 14030 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14031 To, From, 14032 /*CopyingBaseSubobject=*/true, 14033 /*Copying=*/false); 14034 if (Move.isInvalid()) { 14035 MoveAssignOperator->setInvalidDecl(); 14036 return; 14037 } 14038 14039 // Success! Record the move. 14040 Statements.push_back(Move.getAs<Expr>()); 14041 } 14042 14043 // Assign non-static members. 14044 for (auto *Field : ClassDecl->fields()) { 14045 // FIXME: We should form some kind of AST representation for the implied 14046 // memcpy in a union copy operation. 14047 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14048 continue; 14049 14050 if (Field->isInvalidDecl()) { 14051 Invalid = true; 14052 continue; 14053 } 14054 14055 // Check for members of reference type; we can't move those. 14056 if (Field->getType()->isReferenceType()) { 14057 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14058 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14059 Diag(Field->getLocation(), diag::note_declared_at); 14060 Invalid = true; 14061 continue; 14062 } 14063 14064 // Check for members of const-qualified, non-class type. 14065 QualType BaseType = Context.getBaseElementType(Field->getType()); 14066 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14067 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14068 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14069 Diag(Field->getLocation(), diag::note_declared_at); 14070 Invalid = true; 14071 continue; 14072 } 14073 14074 // Suppress assigning zero-width bitfields. 14075 if (Field->isZeroLengthBitField(Context)) 14076 continue; 14077 14078 QualType FieldType = Field->getType().getNonReferenceType(); 14079 if (FieldType->isIncompleteArrayType()) { 14080 assert(ClassDecl->hasFlexibleArrayMember() && 14081 "Incomplete array type is not valid"); 14082 continue; 14083 } 14084 14085 // Build references to the field in the object we're copying from and to. 14086 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14087 LookupMemberName); 14088 MemberLookup.addDecl(Field); 14089 MemberLookup.resolveKind(); 14090 MemberBuilder From(MoveOther, OtherRefType, 14091 /*IsArrow=*/false, MemberLookup); 14092 MemberBuilder To(This, getCurrentThisType(), 14093 /*IsArrow=*/true, MemberLookup); 14094 14095 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14096 "Member reference with rvalue base must be rvalue except for reference " 14097 "members, which aren't allowed for move assignment."); 14098 14099 // Build the move of this field. 14100 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14101 To, From, 14102 /*CopyingBaseSubobject=*/false, 14103 /*Copying=*/false); 14104 if (Move.isInvalid()) { 14105 MoveAssignOperator->setInvalidDecl(); 14106 return; 14107 } 14108 14109 // Success! Record the copy. 14110 Statements.push_back(Move.getAs<Stmt>()); 14111 } 14112 14113 if (!Invalid) { 14114 // Add a "return *this;" 14115 ExprResult ThisObj = 14116 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14117 14118 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14119 if (Return.isInvalid()) 14120 Invalid = true; 14121 else 14122 Statements.push_back(Return.getAs<Stmt>()); 14123 } 14124 14125 if (Invalid) { 14126 MoveAssignOperator->setInvalidDecl(); 14127 return; 14128 } 14129 14130 StmtResult Body; 14131 { 14132 CompoundScopeRAII CompoundScope(*this); 14133 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14134 /*isStmtExpr=*/false); 14135 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14136 } 14137 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14138 MoveAssignOperator->markUsed(Context); 14139 14140 if (ASTMutationListener *L = getASTMutationListener()) { 14141 L->CompletedImplicitDefinition(MoveAssignOperator); 14142 } 14143 } 14144 14145 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14146 CXXRecordDecl *ClassDecl) { 14147 // C++ [class.copy]p4: 14148 // If the class definition does not explicitly declare a copy 14149 // constructor, one is declared implicitly. 14150 assert(ClassDecl->needsImplicitCopyConstructor()); 14151 14152 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14153 if (DSM.isAlreadyBeingDeclared()) 14154 return nullptr; 14155 14156 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14157 QualType ArgType = ClassType; 14158 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14159 if (Const) 14160 ArgType = ArgType.withConst(); 14161 14162 LangAS AS = getDefaultCXXMethodAddrSpace(); 14163 if (AS != LangAS::Default) 14164 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14165 14166 ArgType = Context.getLValueReferenceType(ArgType); 14167 14168 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14169 CXXCopyConstructor, 14170 Const); 14171 14172 DeclarationName Name 14173 = Context.DeclarationNames.getCXXConstructorName( 14174 Context.getCanonicalType(ClassType)); 14175 SourceLocation ClassLoc = ClassDecl->getLocation(); 14176 DeclarationNameInfo NameInfo(Name, ClassLoc); 14177 14178 // An implicitly-declared copy constructor is an inline public 14179 // member of its class. 14180 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14181 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14182 ExplicitSpecifier(), 14183 /*isInline=*/true, 14184 /*isImplicitlyDeclared=*/true, 14185 Constexpr ? CSK_constexpr : CSK_unspecified); 14186 CopyConstructor->setAccess(AS_public); 14187 CopyConstructor->setDefaulted(); 14188 14189 if (getLangOpts().CUDA) { 14190 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14191 CopyConstructor, 14192 /* ConstRHS */ Const, 14193 /* Diagnose */ false); 14194 } 14195 14196 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14197 14198 // Add the parameter to the constructor. 14199 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14200 ClassLoc, ClassLoc, 14201 /*IdentifierInfo=*/nullptr, 14202 ArgType, /*TInfo=*/nullptr, 14203 SC_None, nullptr); 14204 CopyConstructor->setParams(FromParam); 14205 14206 CopyConstructor->setTrivial( 14207 ClassDecl->needsOverloadResolutionForCopyConstructor() 14208 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14209 : ClassDecl->hasTrivialCopyConstructor()); 14210 14211 CopyConstructor->setTrivialForCall( 14212 ClassDecl->hasAttr<TrivialABIAttr>() || 14213 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14214 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14215 TAH_ConsiderTrivialABI) 14216 : ClassDecl->hasTrivialCopyConstructorForCall())); 14217 14218 // Note that we have declared this constructor. 14219 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14220 14221 Scope *S = getScopeForContext(ClassDecl); 14222 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14223 14224 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14225 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14226 SetDeclDeleted(CopyConstructor, ClassLoc); 14227 } 14228 14229 if (S) 14230 PushOnScopeChains(CopyConstructor, S, false); 14231 ClassDecl->addDecl(CopyConstructor); 14232 14233 return CopyConstructor; 14234 } 14235 14236 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14237 CXXConstructorDecl *CopyConstructor) { 14238 assert((CopyConstructor->isDefaulted() && 14239 CopyConstructor->isCopyConstructor() && 14240 !CopyConstructor->doesThisDeclarationHaveABody() && 14241 !CopyConstructor->isDeleted()) && 14242 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14243 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14244 return; 14245 14246 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14247 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14248 14249 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14250 14251 // The exception specification is needed because we are defining the 14252 // function. 14253 ResolveExceptionSpec(CurrentLocation, 14254 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14255 MarkVTableUsed(CurrentLocation, ClassDecl); 14256 14257 // Add a context note for diagnostics produced after this point. 14258 Scope.addContextNote(CurrentLocation); 14259 14260 // C++11 [class.copy]p7: 14261 // The [definition of an implicitly declared copy constructor] is 14262 // deprecated if the class has a user-declared copy assignment operator 14263 // or a user-declared destructor. 14264 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14265 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14266 14267 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14268 CopyConstructor->setInvalidDecl(); 14269 } else { 14270 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14271 ? CopyConstructor->getEndLoc() 14272 : CopyConstructor->getLocation(); 14273 Sema::CompoundScopeRAII CompoundScope(*this); 14274 CopyConstructor->setBody( 14275 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14276 CopyConstructor->markUsed(Context); 14277 } 14278 14279 if (ASTMutationListener *L = getASTMutationListener()) { 14280 L->CompletedImplicitDefinition(CopyConstructor); 14281 } 14282 } 14283 14284 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14285 CXXRecordDecl *ClassDecl) { 14286 assert(ClassDecl->needsImplicitMoveConstructor()); 14287 14288 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14289 if (DSM.isAlreadyBeingDeclared()) 14290 return nullptr; 14291 14292 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14293 14294 QualType ArgType = ClassType; 14295 LangAS AS = getDefaultCXXMethodAddrSpace(); 14296 if (AS != LangAS::Default) 14297 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14298 ArgType = Context.getRValueReferenceType(ArgType); 14299 14300 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14301 CXXMoveConstructor, 14302 false); 14303 14304 DeclarationName Name 14305 = Context.DeclarationNames.getCXXConstructorName( 14306 Context.getCanonicalType(ClassType)); 14307 SourceLocation ClassLoc = ClassDecl->getLocation(); 14308 DeclarationNameInfo NameInfo(Name, ClassLoc); 14309 14310 // C++11 [class.copy]p11: 14311 // An implicitly-declared copy/move constructor is an inline public 14312 // member of its class. 14313 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14314 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14315 ExplicitSpecifier(), 14316 /*isInline=*/true, 14317 /*isImplicitlyDeclared=*/true, 14318 Constexpr ? CSK_constexpr : CSK_unspecified); 14319 MoveConstructor->setAccess(AS_public); 14320 MoveConstructor->setDefaulted(); 14321 14322 if (getLangOpts().CUDA) { 14323 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14324 MoveConstructor, 14325 /* ConstRHS */ false, 14326 /* Diagnose */ false); 14327 } 14328 14329 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14330 14331 // Add the parameter to the constructor. 14332 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14333 ClassLoc, ClassLoc, 14334 /*IdentifierInfo=*/nullptr, 14335 ArgType, /*TInfo=*/nullptr, 14336 SC_None, nullptr); 14337 MoveConstructor->setParams(FromParam); 14338 14339 MoveConstructor->setTrivial( 14340 ClassDecl->needsOverloadResolutionForMoveConstructor() 14341 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14342 : ClassDecl->hasTrivialMoveConstructor()); 14343 14344 MoveConstructor->setTrivialForCall( 14345 ClassDecl->hasAttr<TrivialABIAttr>() || 14346 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14347 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14348 TAH_ConsiderTrivialABI) 14349 : ClassDecl->hasTrivialMoveConstructorForCall())); 14350 14351 // Note that we have declared this constructor. 14352 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14353 14354 Scope *S = getScopeForContext(ClassDecl); 14355 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14356 14357 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14358 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14359 SetDeclDeleted(MoveConstructor, ClassLoc); 14360 } 14361 14362 if (S) 14363 PushOnScopeChains(MoveConstructor, S, false); 14364 ClassDecl->addDecl(MoveConstructor); 14365 14366 return MoveConstructor; 14367 } 14368 14369 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14370 CXXConstructorDecl *MoveConstructor) { 14371 assert((MoveConstructor->isDefaulted() && 14372 MoveConstructor->isMoveConstructor() && 14373 !MoveConstructor->doesThisDeclarationHaveABody() && 14374 !MoveConstructor->isDeleted()) && 14375 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14376 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14377 return; 14378 14379 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14380 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14381 14382 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14383 14384 // The exception specification is needed because we are defining the 14385 // function. 14386 ResolveExceptionSpec(CurrentLocation, 14387 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14388 MarkVTableUsed(CurrentLocation, ClassDecl); 14389 14390 // Add a context note for diagnostics produced after this point. 14391 Scope.addContextNote(CurrentLocation); 14392 14393 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14394 MoveConstructor->setInvalidDecl(); 14395 } else { 14396 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14397 ? MoveConstructor->getEndLoc() 14398 : MoveConstructor->getLocation(); 14399 Sema::CompoundScopeRAII CompoundScope(*this); 14400 MoveConstructor->setBody(ActOnCompoundStmt( 14401 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14402 MoveConstructor->markUsed(Context); 14403 } 14404 14405 if (ASTMutationListener *L = getASTMutationListener()) { 14406 L->CompletedImplicitDefinition(MoveConstructor); 14407 } 14408 } 14409 14410 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14411 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14412 } 14413 14414 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14415 SourceLocation CurrentLocation, 14416 CXXConversionDecl *Conv) { 14417 SynthesizedFunctionScope Scope(*this, Conv); 14418 assert(!Conv->getReturnType()->isUndeducedType()); 14419 14420 CXXRecordDecl *Lambda = Conv->getParent(); 14421 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14422 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 14423 14424 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14425 CallOp = InstantiateFunctionDeclaration( 14426 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14427 if (!CallOp) 14428 return; 14429 14430 Invoker = InstantiateFunctionDeclaration( 14431 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14432 if (!Invoker) 14433 return; 14434 } 14435 14436 if (CallOp->isInvalidDecl()) 14437 return; 14438 14439 // Mark the call operator referenced (and add to pending instantiations 14440 // if necessary). 14441 // For both the conversion and static-invoker template specializations 14442 // we construct their body's in this function, so no need to add them 14443 // to the PendingInstantiations. 14444 MarkFunctionReferenced(CurrentLocation, CallOp); 14445 14446 // Fill in the __invoke function with a dummy implementation. IR generation 14447 // will fill in the actual details. Update its type in case it contained 14448 // an 'auto'. 14449 Invoker->markUsed(Context); 14450 Invoker->setReferenced(); 14451 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14452 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14453 14454 // Construct the body of the conversion function { return __invoke; }. 14455 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14456 VK_LValue, Conv->getLocation()); 14457 assert(FunctionRef && "Can't refer to __invoke function?"); 14458 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14459 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14460 Conv->getLocation())); 14461 Conv->markUsed(Context); 14462 Conv->setReferenced(); 14463 14464 if (ASTMutationListener *L = getASTMutationListener()) { 14465 L->CompletedImplicitDefinition(Conv); 14466 L->CompletedImplicitDefinition(Invoker); 14467 } 14468 } 14469 14470 14471 14472 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14473 SourceLocation CurrentLocation, 14474 CXXConversionDecl *Conv) 14475 { 14476 assert(!Conv->getParent()->isGenericLambda()); 14477 14478 SynthesizedFunctionScope Scope(*this, Conv); 14479 14480 // Copy-initialize the lambda object as needed to capture it. 14481 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14482 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14483 14484 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14485 Conv->getLocation(), 14486 Conv, DerefThis); 14487 14488 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14489 // behavior. Note that only the general conversion function does this 14490 // (since it's unusable otherwise); in the case where we inline the 14491 // block literal, it has block literal lifetime semantics. 14492 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14493 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 14494 CK_CopyAndAutoreleaseBlockObject, 14495 BuildBlock.get(), nullptr, VK_RValue); 14496 14497 if (BuildBlock.isInvalid()) { 14498 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14499 Conv->setInvalidDecl(); 14500 return; 14501 } 14502 14503 // Create the return statement that returns the block from the conversion 14504 // function. 14505 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14506 if (Return.isInvalid()) { 14507 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14508 Conv->setInvalidDecl(); 14509 return; 14510 } 14511 14512 // Set the body of the conversion function. 14513 Stmt *ReturnS = Return.get(); 14514 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14515 Conv->getLocation())); 14516 Conv->markUsed(Context); 14517 14518 // We're done; notify the mutation listener, if any. 14519 if (ASTMutationListener *L = getASTMutationListener()) { 14520 L->CompletedImplicitDefinition(Conv); 14521 } 14522 } 14523 14524 /// Determine whether the given list arguments contains exactly one 14525 /// "real" (non-default) argument. 14526 static bool hasOneRealArgument(MultiExprArg Args) { 14527 switch (Args.size()) { 14528 case 0: 14529 return false; 14530 14531 default: 14532 if (!Args[1]->isDefaultArgument()) 14533 return false; 14534 14535 LLVM_FALLTHROUGH; 14536 case 1: 14537 return !Args[0]->isDefaultArgument(); 14538 } 14539 14540 return false; 14541 } 14542 14543 ExprResult 14544 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14545 NamedDecl *FoundDecl, 14546 CXXConstructorDecl *Constructor, 14547 MultiExprArg ExprArgs, 14548 bool HadMultipleCandidates, 14549 bool IsListInitialization, 14550 bool IsStdInitListInitialization, 14551 bool RequiresZeroInit, 14552 unsigned ConstructKind, 14553 SourceRange ParenRange) { 14554 bool Elidable = false; 14555 14556 // C++0x [class.copy]p34: 14557 // When certain criteria are met, an implementation is allowed to 14558 // omit the copy/move construction of a class object, even if the 14559 // copy/move constructor and/or destructor for the object have 14560 // side effects. [...] 14561 // - when a temporary class object that has not been bound to a 14562 // reference (12.2) would be copied/moved to a class object 14563 // with the same cv-unqualified type, the copy/move operation 14564 // can be omitted by constructing the temporary object 14565 // directly into the target of the omitted copy/move 14566 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 14567 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 14568 Expr *SubExpr = ExprArgs[0]; 14569 Elidable = SubExpr->isTemporaryObject( 14570 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 14571 } 14572 14573 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 14574 FoundDecl, Constructor, 14575 Elidable, ExprArgs, HadMultipleCandidates, 14576 IsListInitialization, 14577 IsStdInitListInitialization, RequiresZeroInit, 14578 ConstructKind, ParenRange); 14579 } 14580 14581 ExprResult 14582 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14583 NamedDecl *FoundDecl, 14584 CXXConstructorDecl *Constructor, 14585 bool Elidable, 14586 MultiExprArg ExprArgs, 14587 bool HadMultipleCandidates, 14588 bool IsListInitialization, 14589 bool IsStdInitListInitialization, 14590 bool RequiresZeroInit, 14591 unsigned ConstructKind, 14592 SourceRange ParenRange) { 14593 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 14594 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 14595 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 14596 return ExprError(); 14597 } 14598 14599 return BuildCXXConstructExpr( 14600 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 14601 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 14602 RequiresZeroInit, ConstructKind, ParenRange); 14603 } 14604 14605 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 14606 /// including handling of its default argument expressions. 14607 ExprResult 14608 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14609 CXXConstructorDecl *Constructor, 14610 bool Elidable, 14611 MultiExprArg ExprArgs, 14612 bool HadMultipleCandidates, 14613 bool IsListInitialization, 14614 bool IsStdInitListInitialization, 14615 bool RequiresZeroInit, 14616 unsigned ConstructKind, 14617 SourceRange ParenRange) { 14618 assert(declaresSameEntity( 14619 Constructor->getParent(), 14620 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 14621 "given constructor for wrong type"); 14622 MarkFunctionReferenced(ConstructLoc, Constructor); 14623 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 14624 return ExprError(); 14625 14626 return CXXConstructExpr::Create( 14627 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 14628 ExprArgs, HadMultipleCandidates, IsListInitialization, 14629 IsStdInitListInitialization, RequiresZeroInit, 14630 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 14631 ParenRange); 14632 } 14633 14634 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 14635 assert(Field->hasInClassInitializer()); 14636 14637 // If we already have the in-class initializer nothing needs to be done. 14638 if (Field->getInClassInitializer()) 14639 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 14640 14641 // If we might have already tried and failed to instantiate, don't try again. 14642 if (Field->isInvalidDecl()) 14643 return ExprError(); 14644 14645 // Maybe we haven't instantiated the in-class initializer. Go check the 14646 // pattern FieldDecl to see if it has one. 14647 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 14648 14649 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 14650 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 14651 DeclContext::lookup_result Lookup = 14652 ClassPattern->lookup(Field->getDeclName()); 14653 14654 // Lookup can return at most two results: the pattern for the field, or the 14655 // injected class name of the parent record. No other member can have the 14656 // same name as the field. 14657 // In modules mode, lookup can return multiple results (coming from 14658 // different modules). 14659 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 14660 "more than two lookup results for field name"); 14661 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 14662 if (!Pattern) { 14663 assert(isa<CXXRecordDecl>(Lookup[0]) && 14664 "cannot have other non-field member with same name"); 14665 for (auto L : Lookup) 14666 if (isa<FieldDecl>(L)) { 14667 Pattern = cast<FieldDecl>(L); 14668 break; 14669 } 14670 assert(Pattern && "We must have set the Pattern!"); 14671 } 14672 14673 if (!Pattern->hasInClassInitializer() || 14674 InstantiateInClassInitializer(Loc, Field, Pattern, 14675 getTemplateInstantiationArgs(Field))) { 14676 // Don't diagnose this again. 14677 Field->setInvalidDecl(); 14678 return ExprError(); 14679 } 14680 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 14681 } 14682 14683 // DR1351: 14684 // If the brace-or-equal-initializer of a non-static data member 14685 // invokes a defaulted default constructor of its class or of an 14686 // enclosing class in a potentially evaluated subexpression, the 14687 // program is ill-formed. 14688 // 14689 // This resolution is unworkable: the exception specification of the 14690 // default constructor can be needed in an unevaluated context, in 14691 // particular, in the operand of a noexcept-expression, and we can be 14692 // unable to compute an exception specification for an enclosed class. 14693 // 14694 // Any attempt to resolve the exception specification of a defaulted default 14695 // constructor before the initializer is lexically complete will ultimately 14696 // come here at which point we can diagnose it. 14697 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 14698 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 14699 << OutermostClass << Field; 14700 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 14701 // Recover by marking the field invalid, unless we're in a SFINAE context. 14702 if (!isSFINAEContext()) 14703 Field->setInvalidDecl(); 14704 return ExprError(); 14705 } 14706 14707 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 14708 if (VD->isInvalidDecl()) return; 14709 14710 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 14711 if (ClassDecl->isInvalidDecl()) return; 14712 if (ClassDecl->hasIrrelevantDestructor()) return; 14713 if (ClassDecl->isDependentContext()) return; 14714 14715 if (VD->isNoDestroy(getASTContext())) 14716 return; 14717 14718 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14719 14720 // If this is an array, we'll require the destructor during initialization, so 14721 // we can skip over this. We still want to emit exit-time destructor warnings 14722 // though. 14723 if (!VD->getType()->isArrayType()) { 14724 MarkFunctionReferenced(VD->getLocation(), Destructor); 14725 CheckDestructorAccess(VD->getLocation(), Destructor, 14726 PDiag(diag::err_access_dtor_var) 14727 << VD->getDeclName() << VD->getType()); 14728 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 14729 } 14730 14731 if (Destructor->isTrivial()) return; 14732 14733 // If the destructor is constexpr, check whether the variable has constant 14734 // destruction now. 14735 if (Destructor->isConstexpr() && VD->getInit() && 14736 !VD->getInit()->isValueDependent() && VD->evaluateValue()) { 14737 SmallVector<PartialDiagnosticAt, 8> Notes; 14738 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr()) { 14739 Diag(VD->getLocation(), 14740 diag::err_constexpr_var_requires_const_destruction) << VD; 14741 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 14742 Diag(Notes[I].first, Notes[I].second); 14743 } 14744 } 14745 14746 if (!VD->hasGlobalStorage()) return; 14747 14748 // Emit warning for non-trivial dtor in global scope (a real global, 14749 // class-static, function-static). 14750 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 14751 14752 // TODO: this should be re-enabled for static locals by !CXAAtExit 14753 if (!VD->isStaticLocal()) 14754 Diag(VD->getLocation(), diag::warn_global_destructor); 14755 } 14756 14757 /// Given a constructor and the set of arguments provided for the 14758 /// constructor, convert the arguments and add any required default arguments 14759 /// to form a proper call to this constructor. 14760 /// 14761 /// \returns true if an error occurred, false otherwise. 14762 bool 14763 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 14764 MultiExprArg ArgsPtr, 14765 SourceLocation Loc, 14766 SmallVectorImpl<Expr*> &ConvertedArgs, 14767 bool AllowExplicit, 14768 bool IsListInitialization) { 14769 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 14770 unsigned NumArgs = ArgsPtr.size(); 14771 Expr **Args = ArgsPtr.data(); 14772 14773 const FunctionProtoType *Proto 14774 = Constructor->getType()->getAs<FunctionProtoType>(); 14775 assert(Proto && "Constructor without a prototype?"); 14776 unsigned NumParams = Proto->getNumParams(); 14777 14778 // If too few arguments are available, we'll fill in the rest with defaults. 14779 if (NumArgs < NumParams) 14780 ConvertedArgs.reserve(NumParams); 14781 else 14782 ConvertedArgs.reserve(NumArgs); 14783 14784 VariadicCallType CallType = 14785 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 14786 SmallVector<Expr *, 8> AllArgs; 14787 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 14788 Proto, 0, 14789 llvm::makeArrayRef(Args, NumArgs), 14790 AllArgs, 14791 CallType, AllowExplicit, 14792 IsListInitialization); 14793 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 14794 14795 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 14796 14797 CheckConstructorCall(Constructor, 14798 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 14799 Proto, Loc); 14800 14801 return Invalid; 14802 } 14803 14804 static inline bool 14805 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 14806 const FunctionDecl *FnDecl) { 14807 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 14808 if (isa<NamespaceDecl>(DC)) { 14809 return SemaRef.Diag(FnDecl->getLocation(), 14810 diag::err_operator_new_delete_declared_in_namespace) 14811 << FnDecl->getDeclName(); 14812 } 14813 14814 if (isa<TranslationUnitDecl>(DC) && 14815 FnDecl->getStorageClass() == SC_Static) { 14816 return SemaRef.Diag(FnDecl->getLocation(), 14817 diag::err_operator_new_delete_declared_static) 14818 << FnDecl->getDeclName(); 14819 } 14820 14821 return false; 14822 } 14823 14824 static QualType 14825 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 14826 QualType QTy = PtrTy->getPointeeType(); 14827 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 14828 return SemaRef.Context.getPointerType(QTy); 14829 } 14830 14831 static inline bool 14832 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 14833 CanQualType ExpectedResultType, 14834 CanQualType ExpectedFirstParamType, 14835 unsigned DependentParamTypeDiag, 14836 unsigned InvalidParamTypeDiag) { 14837 QualType ResultType = 14838 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 14839 14840 // Check that the result type is not dependent. 14841 if (ResultType->isDependentType()) 14842 return SemaRef.Diag(FnDecl->getLocation(), 14843 diag::err_operator_new_delete_dependent_result_type) 14844 << FnDecl->getDeclName() << ExpectedResultType; 14845 14846 // The operator is valid on any address space for OpenCL. 14847 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 14848 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 14849 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 14850 } 14851 } 14852 14853 // Check that the result type is what we expect. 14854 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 14855 return SemaRef.Diag(FnDecl->getLocation(), 14856 diag::err_operator_new_delete_invalid_result_type) 14857 << FnDecl->getDeclName() << ExpectedResultType; 14858 14859 // A function template must have at least 2 parameters. 14860 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 14861 return SemaRef.Diag(FnDecl->getLocation(), 14862 diag::err_operator_new_delete_template_too_few_parameters) 14863 << FnDecl->getDeclName(); 14864 14865 // The function decl must have at least 1 parameter. 14866 if (FnDecl->getNumParams() == 0) 14867 return SemaRef.Diag(FnDecl->getLocation(), 14868 diag::err_operator_new_delete_too_few_parameters) 14869 << FnDecl->getDeclName(); 14870 14871 // Check the first parameter type is not dependent. 14872 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 14873 if (FirstParamType->isDependentType()) 14874 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 14875 << FnDecl->getDeclName() << ExpectedFirstParamType; 14876 14877 // Check that the first parameter type is what we expect. 14878 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 14879 // The operator is valid on any address space for OpenCL. 14880 if (auto *PtrTy = 14881 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 14882 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 14883 } 14884 } 14885 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 14886 ExpectedFirstParamType) 14887 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 14888 << FnDecl->getDeclName() << ExpectedFirstParamType; 14889 14890 return false; 14891 } 14892 14893 static bool 14894 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 14895 // C++ [basic.stc.dynamic.allocation]p1: 14896 // A program is ill-formed if an allocation function is declared in a 14897 // namespace scope other than global scope or declared static in global 14898 // scope. 14899 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 14900 return true; 14901 14902 CanQualType SizeTy = 14903 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 14904 14905 // C++ [basic.stc.dynamic.allocation]p1: 14906 // The return type shall be void*. The first parameter shall have type 14907 // std::size_t. 14908 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 14909 SizeTy, 14910 diag::err_operator_new_dependent_param_type, 14911 diag::err_operator_new_param_type)) 14912 return true; 14913 14914 // C++ [basic.stc.dynamic.allocation]p1: 14915 // The first parameter shall not have an associated default argument. 14916 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 14917 return SemaRef.Diag(FnDecl->getLocation(), 14918 diag::err_operator_new_default_arg) 14919 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 14920 14921 return false; 14922 } 14923 14924 static bool 14925 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 14926 // C++ [basic.stc.dynamic.deallocation]p1: 14927 // A program is ill-formed if deallocation functions are declared in a 14928 // namespace scope other than global scope or declared static in global 14929 // scope. 14930 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 14931 return true; 14932 14933 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 14934 14935 // C++ P0722: 14936 // Within a class C, the first parameter of a destroying operator delete 14937 // shall be of type C *. The first parameter of any other deallocation 14938 // function shall be of type void *. 14939 CanQualType ExpectedFirstParamType = 14940 MD && MD->isDestroyingOperatorDelete() 14941 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 14942 SemaRef.Context.getRecordType(MD->getParent()))) 14943 : SemaRef.Context.VoidPtrTy; 14944 14945 // C++ [basic.stc.dynamic.deallocation]p2: 14946 // Each deallocation function shall return void 14947 if (CheckOperatorNewDeleteTypes( 14948 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 14949 diag::err_operator_delete_dependent_param_type, 14950 diag::err_operator_delete_param_type)) 14951 return true; 14952 14953 // C++ P0722: 14954 // A destroying operator delete shall be a usual deallocation function. 14955 if (MD && !MD->getParent()->isDependentContext() && 14956 MD->isDestroyingOperatorDelete() && 14957 !SemaRef.isUsualDeallocationFunction(MD)) { 14958 SemaRef.Diag(MD->getLocation(), 14959 diag::err_destroying_operator_delete_not_usual); 14960 return true; 14961 } 14962 14963 return false; 14964 } 14965 14966 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 14967 /// of this overloaded operator is well-formed. If so, returns false; 14968 /// otherwise, emits appropriate diagnostics and returns true. 14969 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 14970 assert(FnDecl && FnDecl->isOverloadedOperator() && 14971 "Expected an overloaded operator declaration"); 14972 14973 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 14974 14975 // C++ [over.oper]p5: 14976 // The allocation and deallocation functions, operator new, 14977 // operator new[], operator delete and operator delete[], are 14978 // described completely in 3.7.3. The attributes and restrictions 14979 // found in the rest of this subclause do not apply to them unless 14980 // explicitly stated in 3.7.3. 14981 if (Op == OO_Delete || Op == OO_Array_Delete) 14982 return CheckOperatorDeleteDeclaration(*this, FnDecl); 14983 14984 if (Op == OO_New || Op == OO_Array_New) 14985 return CheckOperatorNewDeclaration(*this, FnDecl); 14986 14987 // C++ [over.oper]p6: 14988 // An operator function shall either be a non-static member 14989 // function or be a non-member function and have at least one 14990 // parameter whose type is a class, a reference to a class, an 14991 // enumeration, or a reference to an enumeration. 14992 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 14993 if (MethodDecl->isStatic()) 14994 return Diag(FnDecl->getLocation(), 14995 diag::err_operator_overload_static) << FnDecl->getDeclName(); 14996 } else { 14997 bool ClassOrEnumParam = false; 14998 for (auto Param : FnDecl->parameters()) { 14999 QualType ParamType = Param->getType().getNonReferenceType(); 15000 if (ParamType->isDependentType() || ParamType->isRecordType() || 15001 ParamType->isEnumeralType()) { 15002 ClassOrEnumParam = true; 15003 break; 15004 } 15005 } 15006 15007 if (!ClassOrEnumParam) 15008 return Diag(FnDecl->getLocation(), 15009 diag::err_operator_overload_needs_class_or_enum) 15010 << FnDecl->getDeclName(); 15011 } 15012 15013 // C++ [over.oper]p8: 15014 // An operator function cannot have default arguments (8.3.6), 15015 // except where explicitly stated below. 15016 // 15017 // Only the function-call operator allows default arguments 15018 // (C++ [over.call]p1). 15019 if (Op != OO_Call) { 15020 for (auto Param : FnDecl->parameters()) { 15021 if (Param->hasDefaultArg()) 15022 return Diag(Param->getLocation(), 15023 diag::err_operator_overload_default_arg) 15024 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15025 } 15026 } 15027 15028 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15029 { false, false, false } 15030 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15031 , { Unary, Binary, MemberOnly } 15032 #include "clang/Basic/OperatorKinds.def" 15033 }; 15034 15035 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15036 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15037 bool MustBeMemberOperator = OperatorUses[Op][2]; 15038 15039 // C++ [over.oper]p8: 15040 // [...] Operator functions cannot have more or fewer parameters 15041 // than the number required for the corresponding operator, as 15042 // described in the rest of this subclause. 15043 unsigned NumParams = FnDecl->getNumParams() 15044 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15045 if (Op != OO_Call && 15046 ((NumParams == 1 && !CanBeUnaryOperator) || 15047 (NumParams == 2 && !CanBeBinaryOperator) || 15048 (NumParams < 1) || (NumParams > 2))) { 15049 // We have the wrong number of parameters. 15050 unsigned ErrorKind; 15051 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15052 ErrorKind = 2; // 2 -> unary or binary. 15053 } else if (CanBeUnaryOperator) { 15054 ErrorKind = 0; // 0 -> unary 15055 } else { 15056 assert(CanBeBinaryOperator && 15057 "All non-call overloaded operators are unary or binary!"); 15058 ErrorKind = 1; // 1 -> binary 15059 } 15060 15061 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15062 << FnDecl->getDeclName() << NumParams << ErrorKind; 15063 } 15064 15065 // Overloaded operators other than operator() cannot be variadic. 15066 if (Op != OO_Call && 15067 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 15068 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15069 << FnDecl->getDeclName(); 15070 } 15071 15072 // Some operators must be non-static member functions. 15073 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15074 return Diag(FnDecl->getLocation(), 15075 diag::err_operator_overload_must_be_member) 15076 << FnDecl->getDeclName(); 15077 } 15078 15079 // C++ [over.inc]p1: 15080 // The user-defined function called operator++ implements the 15081 // prefix and postfix ++ operator. If this function is a member 15082 // function with no parameters, or a non-member function with one 15083 // parameter of class or enumeration type, it defines the prefix 15084 // increment operator ++ for objects of that type. If the function 15085 // is a member function with one parameter (which shall be of type 15086 // int) or a non-member function with two parameters (the second 15087 // of which shall be of type int), it defines the postfix 15088 // increment operator ++ for objects of that type. 15089 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15090 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15091 QualType ParamType = LastParam->getType(); 15092 15093 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15094 !ParamType->isDependentType()) 15095 return Diag(LastParam->getLocation(), 15096 diag::err_operator_overload_post_incdec_must_be_int) 15097 << LastParam->getType() << (Op == OO_MinusMinus); 15098 } 15099 15100 return false; 15101 } 15102 15103 static bool 15104 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15105 FunctionTemplateDecl *TpDecl) { 15106 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15107 15108 // Must have one or two template parameters. 15109 if (TemplateParams->size() == 1) { 15110 NonTypeTemplateParmDecl *PmDecl = 15111 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15112 15113 // The template parameter must be a char parameter pack. 15114 if (PmDecl && PmDecl->isTemplateParameterPack() && 15115 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15116 return false; 15117 15118 } else if (TemplateParams->size() == 2) { 15119 TemplateTypeParmDecl *PmType = 15120 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15121 NonTypeTemplateParmDecl *PmArgs = 15122 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15123 15124 // The second template parameter must be a parameter pack with the 15125 // first template parameter as its type. 15126 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15127 PmArgs->isTemplateParameterPack()) { 15128 const TemplateTypeParmType *TArgs = 15129 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15130 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15131 TArgs->getIndex() == PmType->getIndex()) { 15132 if (!SemaRef.inTemplateInstantiation()) 15133 SemaRef.Diag(TpDecl->getLocation(), 15134 diag::ext_string_literal_operator_template); 15135 return false; 15136 } 15137 } 15138 } 15139 15140 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15141 diag::err_literal_operator_template) 15142 << TpDecl->getTemplateParameters()->getSourceRange(); 15143 return true; 15144 } 15145 15146 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15147 /// of this literal operator function is well-formed. If so, returns 15148 /// false; otherwise, emits appropriate diagnostics and returns true. 15149 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15150 if (isa<CXXMethodDecl>(FnDecl)) { 15151 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15152 << FnDecl->getDeclName(); 15153 return true; 15154 } 15155 15156 if (FnDecl->isExternC()) { 15157 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15158 if (const LinkageSpecDecl *LSD = 15159 FnDecl->getDeclContext()->getExternCContext()) 15160 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15161 return true; 15162 } 15163 15164 // This might be the definition of a literal operator template. 15165 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15166 15167 // This might be a specialization of a literal operator template. 15168 if (!TpDecl) 15169 TpDecl = FnDecl->getPrimaryTemplate(); 15170 15171 // template <char...> type operator "" name() and 15172 // template <class T, T...> type operator "" name() are the only valid 15173 // template signatures, and the only valid signatures with no parameters. 15174 if (TpDecl) { 15175 if (FnDecl->param_size() != 0) { 15176 Diag(FnDecl->getLocation(), 15177 diag::err_literal_operator_template_with_params); 15178 return true; 15179 } 15180 15181 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15182 return true; 15183 15184 } else if (FnDecl->param_size() == 1) { 15185 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15186 15187 QualType ParamType = Param->getType().getUnqualifiedType(); 15188 15189 // Only unsigned long long int, long double, any character type, and const 15190 // char * are allowed as the only parameters. 15191 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15192 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15193 Context.hasSameType(ParamType, Context.CharTy) || 15194 Context.hasSameType(ParamType, Context.WideCharTy) || 15195 Context.hasSameType(ParamType, Context.Char8Ty) || 15196 Context.hasSameType(ParamType, Context.Char16Ty) || 15197 Context.hasSameType(ParamType, Context.Char32Ty)) { 15198 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15199 QualType InnerType = Ptr->getPointeeType(); 15200 15201 // Pointer parameter must be a const char *. 15202 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15203 Context.CharTy) && 15204 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15205 Diag(Param->getSourceRange().getBegin(), 15206 diag::err_literal_operator_param) 15207 << ParamType << "'const char *'" << Param->getSourceRange(); 15208 return true; 15209 } 15210 15211 } else if (ParamType->isRealFloatingType()) { 15212 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15213 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15214 return true; 15215 15216 } else if (ParamType->isIntegerType()) { 15217 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15218 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15219 return true; 15220 15221 } else { 15222 Diag(Param->getSourceRange().getBegin(), 15223 diag::err_literal_operator_invalid_param) 15224 << ParamType << Param->getSourceRange(); 15225 return true; 15226 } 15227 15228 } else if (FnDecl->param_size() == 2) { 15229 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15230 15231 // First, verify that the first parameter is correct. 15232 15233 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15234 15235 // Two parameter function must have a pointer to const as a 15236 // first parameter; let's strip those qualifiers. 15237 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15238 15239 if (!PT) { 15240 Diag((*Param)->getSourceRange().getBegin(), 15241 diag::err_literal_operator_param) 15242 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15243 return true; 15244 } 15245 15246 QualType PointeeType = PT->getPointeeType(); 15247 // First parameter must be const 15248 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15249 Diag((*Param)->getSourceRange().getBegin(), 15250 diag::err_literal_operator_param) 15251 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15252 return true; 15253 } 15254 15255 QualType InnerType = PointeeType.getUnqualifiedType(); 15256 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15257 // const char32_t* are allowed as the first parameter to a two-parameter 15258 // function 15259 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15260 Context.hasSameType(InnerType, Context.WideCharTy) || 15261 Context.hasSameType(InnerType, Context.Char8Ty) || 15262 Context.hasSameType(InnerType, Context.Char16Ty) || 15263 Context.hasSameType(InnerType, Context.Char32Ty))) { 15264 Diag((*Param)->getSourceRange().getBegin(), 15265 diag::err_literal_operator_param) 15266 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15267 return true; 15268 } 15269 15270 // Move on to the second and final parameter. 15271 ++Param; 15272 15273 // The second parameter must be a std::size_t. 15274 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15275 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15276 Diag((*Param)->getSourceRange().getBegin(), 15277 diag::err_literal_operator_param) 15278 << SecondParamType << Context.getSizeType() 15279 << (*Param)->getSourceRange(); 15280 return true; 15281 } 15282 } else { 15283 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15284 return true; 15285 } 15286 15287 // Parameters are good. 15288 15289 // A parameter-declaration-clause containing a default argument is not 15290 // equivalent to any of the permitted forms. 15291 for (auto Param : FnDecl->parameters()) { 15292 if (Param->hasDefaultArg()) { 15293 Diag(Param->getDefaultArgRange().getBegin(), 15294 diag::err_literal_operator_default_argument) 15295 << Param->getDefaultArgRange(); 15296 break; 15297 } 15298 } 15299 15300 StringRef LiteralName 15301 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15302 if (LiteralName[0] != '_' && 15303 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15304 // C++11 [usrlit.suffix]p1: 15305 // Literal suffix identifiers that do not start with an underscore 15306 // are reserved for future standardization. 15307 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15308 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15309 } 15310 15311 return false; 15312 } 15313 15314 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15315 /// linkage specification, including the language and (if present) 15316 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15317 /// language string literal. LBraceLoc, if valid, provides the location of 15318 /// the '{' brace. Otherwise, this linkage specification does not 15319 /// have any braces. 15320 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15321 Expr *LangStr, 15322 SourceLocation LBraceLoc) { 15323 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15324 if (!Lit->isAscii()) { 15325 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15326 << LangStr->getSourceRange(); 15327 return nullptr; 15328 } 15329 15330 StringRef Lang = Lit->getString(); 15331 LinkageSpecDecl::LanguageIDs Language; 15332 if (Lang == "C") 15333 Language = LinkageSpecDecl::lang_c; 15334 else if (Lang == "C++") 15335 Language = LinkageSpecDecl::lang_cxx; 15336 else { 15337 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15338 << LangStr->getSourceRange(); 15339 return nullptr; 15340 } 15341 15342 // FIXME: Add all the various semantics of linkage specifications 15343 15344 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15345 LangStr->getExprLoc(), Language, 15346 LBraceLoc.isValid()); 15347 CurContext->addDecl(D); 15348 PushDeclContext(S, D); 15349 return D; 15350 } 15351 15352 /// ActOnFinishLinkageSpecification - Complete the definition of 15353 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15354 /// valid, it's the position of the closing '}' brace in a linkage 15355 /// specification that uses braces. 15356 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15357 Decl *LinkageSpec, 15358 SourceLocation RBraceLoc) { 15359 if (RBraceLoc.isValid()) { 15360 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15361 LSDecl->setRBraceLoc(RBraceLoc); 15362 } 15363 PopDeclContext(); 15364 return LinkageSpec; 15365 } 15366 15367 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15368 const ParsedAttributesView &AttrList, 15369 SourceLocation SemiLoc) { 15370 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15371 // Attribute declarations appertain to empty declaration so we handle 15372 // them here. 15373 ProcessDeclAttributeList(S, ED, AttrList); 15374 15375 CurContext->addDecl(ED); 15376 return ED; 15377 } 15378 15379 /// Perform semantic analysis for the variable declaration that 15380 /// occurs within a C++ catch clause, returning the newly-created 15381 /// variable. 15382 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15383 TypeSourceInfo *TInfo, 15384 SourceLocation StartLoc, 15385 SourceLocation Loc, 15386 IdentifierInfo *Name) { 15387 bool Invalid = false; 15388 QualType ExDeclType = TInfo->getType(); 15389 15390 // Arrays and functions decay. 15391 if (ExDeclType->isArrayType()) 15392 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15393 else if (ExDeclType->isFunctionType()) 15394 ExDeclType = Context.getPointerType(ExDeclType); 15395 15396 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15397 // The exception-declaration shall not denote a pointer or reference to an 15398 // incomplete type, other than [cv] void*. 15399 // N2844 forbids rvalue references. 15400 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15401 Diag(Loc, diag::err_catch_rvalue_ref); 15402 Invalid = true; 15403 } 15404 15405 if (ExDeclType->isVariablyModifiedType()) { 15406 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15407 Invalid = true; 15408 } 15409 15410 QualType BaseType = ExDeclType; 15411 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15412 unsigned DK = diag::err_catch_incomplete; 15413 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15414 BaseType = Ptr->getPointeeType(); 15415 Mode = 1; 15416 DK = diag::err_catch_incomplete_ptr; 15417 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15418 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15419 BaseType = Ref->getPointeeType(); 15420 Mode = 2; 15421 DK = diag::err_catch_incomplete_ref; 15422 } 15423 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15424 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15425 Invalid = true; 15426 15427 if (!Invalid && !ExDeclType->isDependentType() && 15428 RequireNonAbstractType(Loc, ExDeclType, 15429 diag::err_abstract_type_in_decl, 15430 AbstractVariableType)) 15431 Invalid = true; 15432 15433 // Only the non-fragile NeXT runtime currently supports C++ catches 15434 // of ObjC types, and no runtime supports catching ObjC types by value. 15435 if (!Invalid && getLangOpts().ObjC) { 15436 QualType T = ExDeclType; 15437 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15438 T = RT->getPointeeType(); 15439 15440 if (T->isObjCObjectType()) { 15441 Diag(Loc, diag::err_objc_object_catch); 15442 Invalid = true; 15443 } else if (T->isObjCObjectPointerType()) { 15444 // FIXME: should this be a test for macosx-fragile specifically? 15445 if (getLangOpts().ObjCRuntime.isFragile()) 15446 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15447 } 15448 } 15449 15450 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15451 ExDeclType, TInfo, SC_None); 15452 ExDecl->setExceptionVariable(true); 15453 15454 // In ARC, infer 'retaining' for variables of retainable type. 15455 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15456 Invalid = true; 15457 15458 if (!Invalid && !ExDeclType->isDependentType()) { 15459 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15460 // Insulate this from anything else we might currently be parsing. 15461 EnterExpressionEvaluationContext scope( 15462 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15463 15464 // C++ [except.handle]p16: 15465 // The object declared in an exception-declaration or, if the 15466 // exception-declaration does not specify a name, a temporary (12.2) is 15467 // copy-initialized (8.5) from the exception object. [...] 15468 // The object is destroyed when the handler exits, after the destruction 15469 // of any automatic objects initialized within the handler. 15470 // 15471 // We just pretend to initialize the object with itself, then make sure 15472 // it can be destroyed later. 15473 QualType initType = Context.getExceptionObjectType(ExDeclType); 15474 15475 InitializedEntity entity = 15476 InitializedEntity::InitializeVariable(ExDecl); 15477 InitializationKind initKind = 15478 InitializationKind::CreateCopy(Loc, SourceLocation()); 15479 15480 Expr *opaqueValue = 15481 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15482 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15483 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15484 if (result.isInvalid()) 15485 Invalid = true; 15486 else { 15487 // If the constructor used was non-trivial, set this as the 15488 // "initializer". 15489 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15490 if (!construct->getConstructor()->isTrivial()) { 15491 Expr *init = MaybeCreateExprWithCleanups(construct); 15492 ExDecl->setInit(init); 15493 } 15494 15495 // And make sure it's destructable. 15496 FinalizeVarWithDestructor(ExDecl, recordType); 15497 } 15498 } 15499 } 15500 15501 if (Invalid) 15502 ExDecl->setInvalidDecl(); 15503 15504 return ExDecl; 15505 } 15506 15507 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15508 /// handler. 15509 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15510 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15511 bool Invalid = D.isInvalidType(); 15512 15513 // Check for unexpanded parameter packs. 15514 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15515 UPPC_ExceptionType)) { 15516 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15517 D.getIdentifierLoc()); 15518 Invalid = true; 15519 } 15520 15521 IdentifierInfo *II = D.getIdentifier(); 15522 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15523 LookupOrdinaryName, 15524 ForVisibleRedeclaration)) { 15525 // The scope should be freshly made just for us. There is just no way 15526 // it contains any previous declaration, except for function parameters in 15527 // a function-try-block's catch statement. 15528 assert(!S->isDeclScope(PrevDecl)); 15529 if (isDeclInScope(PrevDecl, CurContext, S)) { 15530 Diag(D.getIdentifierLoc(), diag::err_redefinition) 15531 << D.getIdentifier(); 15532 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15533 Invalid = true; 15534 } else if (PrevDecl->isTemplateParameter()) 15535 // Maybe we will complain about the shadowed template parameter. 15536 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15537 } 15538 15539 if (D.getCXXScopeSpec().isSet() && !Invalid) { 15540 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 15541 << D.getCXXScopeSpec().getRange(); 15542 Invalid = true; 15543 } 15544 15545 VarDecl *ExDecl = BuildExceptionDeclaration( 15546 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 15547 if (Invalid) 15548 ExDecl->setInvalidDecl(); 15549 15550 // Add the exception declaration into this scope. 15551 if (II) 15552 PushOnScopeChains(ExDecl, S); 15553 else 15554 CurContext->addDecl(ExDecl); 15555 15556 ProcessDeclAttributes(S, ExDecl, D); 15557 return ExDecl; 15558 } 15559 15560 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15561 Expr *AssertExpr, 15562 Expr *AssertMessageExpr, 15563 SourceLocation RParenLoc) { 15564 StringLiteral *AssertMessage = 15565 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 15566 15567 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 15568 return nullptr; 15569 15570 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 15571 AssertMessage, RParenLoc, false); 15572 } 15573 15574 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15575 Expr *AssertExpr, 15576 StringLiteral *AssertMessage, 15577 SourceLocation RParenLoc, 15578 bool Failed) { 15579 assert(AssertExpr != nullptr && "Expected non-null condition"); 15580 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 15581 !Failed) { 15582 // In a static_assert-declaration, the constant-expression shall be a 15583 // constant expression that can be contextually converted to bool. 15584 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 15585 if (Converted.isInvalid()) 15586 Failed = true; 15587 15588 ExprResult FullAssertExpr = 15589 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 15590 /*DiscardedValue*/ false, 15591 /*IsConstexpr*/ true); 15592 if (FullAssertExpr.isInvalid()) 15593 Failed = true; 15594 else 15595 AssertExpr = FullAssertExpr.get(); 15596 15597 llvm::APSInt Cond; 15598 if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond, 15599 diag::err_static_assert_expression_is_not_constant, 15600 /*AllowFold=*/false).isInvalid()) 15601 Failed = true; 15602 15603 if (!Failed && !Cond) { 15604 SmallString<256> MsgBuffer; 15605 llvm::raw_svector_ostream Msg(MsgBuffer); 15606 if (AssertMessage) 15607 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 15608 15609 Expr *InnerCond = nullptr; 15610 std::string InnerCondDescription; 15611 std::tie(InnerCond, InnerCondDescription) = 15612 findFailedBooleanCondition(Converted.get()); 15613 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 15614 // Drill down into concept specialization expressions to see why they 15615 // weren't satisfied. 15616 Diag(StaticAssertLoc, diag::err_static_assert_failed) 15617 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 15618 ConstraintSatisfaction Satisfaction; 15619 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 15620 DiagnoseUnsatisfiedConstraint(Satisfaction); 15621 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 15622 && !isa<IntegerLiteral>(InnerCond)) { 15623 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 15624 << InnerCondDescription << !AssertMessage 15625 << Msg.str() << InnerCond->getSourceRange(); 15626 } else { 15627 Diag(StaticAssertLoc, diag::err_static_assert_failed) 15628 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 15629 } 15630 Failed = true; 15631 } 15632 } else { 15633 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 15634 /*DiscardedValue*/false, 15635 /*IsConstexpr*/true); 15636 if (FullAssertExpr.isInvalid()) 15637 Failed = true; 15638 else 15639 AssertExpr = FullAssertExpr.get(); 15640 } 15641 15642 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 15643 AssertExpr, AssertMessage, RParenLoc, 15644 Failed); 15645 15646 CurContext->addDecl(Decl); 15647 return Decl; 15648 } 15649 15650 /// Perform semantic analysis of the given friend type declaration. 15651 /// 15652 /// \returns A friend declaration that. 15653 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 15654 SourceLocation FriendLoc, 15655 TypeSourceInfo *TSInfo) { 15656 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 15657 15658 QualType T = TSInfo->getType(); 15659 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 15660 15661 // C++03 [class.friend]p2: 15662 // An elaborated-type-specifier shall be used in a friend declaration 15663 // for a class.* 15664 // 15665 // * The class-key of the elaborated-type-specifier is required. 15666 if (!CodeSynthesisContexts.empty()) { 15667 // Do not complain about the form of friend template types during any kind 15668 // of code synthesis. For template instantiation, we will have complained 15669 // when the template was defined. 15670 } else { 15671 if (!T->isElaboratedTypeSpecifier()) { 15672 // If we evaluated the type to a record type, suggest putting 15673 // a tag in front. 15674 if (const RecordType *RT = T->getAs<RecordType>()) { 15675 RecordDecl *RD = RT->getDecl(); 15676 15677 SmallString<16> InsertionText(" "); 15678 InsertionText += RD->getKindName(); 15679 15680 Diag(TypeRange.getBegin(), 15681 getLangOpts().CPlusPlus11 ? 15682 diag::warn_cxx98_compat_unelaborated_friend_type : 15683 diag::ext_unelaborated_friend_type) 15684 << (unsigned) RD->getTagKind() 15685 << T 15686 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 15687 InsertionText); 15688 } else { 15689 Diag(FriendLoc, 15690 getLangOpts().CPlusPlus11 ? 15691 diag::warn_cxx98_compat_nonclass_type_friend : 15692 diag::ext_nonclass_type_friend) 15693 << T 15694 << TypeRange; 15695 } 15696 } else if (T->getAs<EnumType>()) { 15697 Diag(FriendLoc, 15698 getLangOpts().CPlusPlus11 ? 15699 diag::warn_cxx98_compat_enum_friend : 15700 diag::ext_enum_friend) 15701 << T 15702 << TypeRange; 15703 } 15704 15705 // C++11 [class.friend]p3: 15706 // A friend declaration that does not declare a function shall have one 15707 // of the following forms: 15708 // friend elaborated-type-specifier ; 15709 // friend simple-type-specifier ; 15710 // friend typename-specifier ; 15711 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 15712 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 15713 } 15714 15715 // If the type specifier in a friend declaration designates a (possibly 15716 // cv-qualified) class type, that class is declared as a friend; otherwise, 15717 // the friend declaration is ignored. 15718 return FriendDecl::Create(Context, CurContext, 15719 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 15720 FriendLoc); 15721 } 15722 15723 /// Handle a friend tag declaration where the scope specifier was 15724 /// templated. 15725 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 15726 unsigned TagSpec, SourceLocation TagLoc, 15727 CXXScopeSpec &SS, IdentifierInfo *Name, 15728 SourceLocation NameLoc, 15729 const ParsedAttributesView &Attr, 15730 MultiTemplateParamsArg TempParamLists) { 15731 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15732 15733 bool IsMemberSpecialization = false; 15734 bool Invalid = false; 15735 15736 if (TemplateParameterList *TemplateParams = 15737 MatchTemplateParametersToScopeSpecifier( 15738 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 15739 IsMemberSpecialization, Invalid)) { 15740 if (TemplateParams->size() > 0) { 15741 // This is a declaration of a class template. 15742 if (Invalid) 15743 return nullptr; 15744 15745 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 15746 NameLoc, Attr, TemplateParams, AS_public, 15747 /*ModulePrivateLoc=*/SourceLocation(), 15748 FriendLoc, TempParamLists.size() - 1, 15749 TempParamLists.data()).get(); 15750 } else { 15751 // The "template<>" header is extraneous. 15752 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15753 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15754 IsMemberSpecialization = true; 15755 } 15756 } 15757 15758 if (Invalid) return nullptr; 15759 15760 bool isAllExplicitSpecializations = true; 15761 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 15762 if (TempParamLists[I]->size()) { 15763 isAllExplicitSpecializations = false; 15764 break; 15765 } 15766 } 15767 15768 // FIXME: don't ignore attributes. 15769 15770 // If it's explicit specializations all the way down, just forget 15771 // about the template header and build an appropriate non-templated 15772 // friend. TODO: for source fidelity, remember the headers. 15773 if (isAllExplicitSpecializations) { 15774 if (SS.isEmpty()) { 15775 bool Owned = false; 15776 bool IsDependent = false; 15777 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 15778 Attr, AS_public, 15779 /*ModulePrivateLoc=*/SourceLocation(), 15780 MultiTemplateParamsArg(), Owned, IsDependent, 15781 /*ScopedEnumKWLoc=*/SourceLocation(), 15782 /*ScopedEnumUsesClassTag=*/false, 15783 /*UnderlyingType=*/TypeResult(), 15784 /*IsTypeSpecifier=*/false, 15785 /*IsTemplateParamOrArg=*/false); 15786 } 15787 15788 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 15789 ElaboratedTypeKeyword Keyword 15790 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 15791 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 15792 *Name, NameLoc); 15793 if (T.isNull()) 15794 return nullptr; 15795 15796 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 15797 if (isa<DependentNameType>(T)) { 15798 DependentNameTypeLoc TL = 15799 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 15800 TL.setElaboratedKeywordLoc(TagLoc); 15801 TL.setQualifierLoc(QualifierLoc); 15802 TL.setNameLoc(NameLoc); 15803 } else { 15804 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 15805 TL.setElaboratedKeywordLoc(TagLoc); 15806 TL.setQualifierLoc(QualifierLoc); 15807 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 15808 } 15809 15810 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 15811 TSI, FriendLoc, TempParamLists); 15812 Friend->setAccess(AS_public); 15813 CurContext->addDecl(Friend); 15814 return Friend; 15815 } 15816 15817 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 15818 15819 15820 15821 // Handle the case of a templated-scope friend class. e.g. 15822 // template <class T> class A<T>::B; 15823 // FIXME: we don't support these right now. 15824 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 15825 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 15826 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 15827 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 15828 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 15829 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 15830 TL.setElaboratedKeywordLoc(TagLoc); 15831 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 15832 TL.setNameLoc(NameLoc); 15833 15834 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 15835 TSI, FriendLoc, TempParamLists); 15836 Friend->setAccess(AS_public); 15837 Friend->setUnsupportedFriend(true); 15838 CurContext->addDecl(Friend); 15839 return Friend; 15840 } 15841 15842 /// Handle a friend type declaration. This works in tandem with 15843 /// ActOnTag. 15844 /// 15845 /// Notes on friend class templates: 15846 /// 15847 /// We generally treat friend class declarations as if they were 15848 /// declaring a class. So, for example, the elaborated type specifier 15849 /// in a friend declaration is required to obey the restrictions of a 15850 /// class-head (i.e. no typedefs in the scope chain), template 15851 /// parameters are required to match up with simple template-ids, &c. 15852 /// However, unlike when declaring a template specialization, it's 15853 /// okay to refer to a template specialization without an empty 15854 /// template parameter declaration, e.g. 15855 /// friend class A<T>::B<unsigned>; 15856 /// We permit this as a special case; if there are any template 15857 /// parameters present at all, require proper matching, i.e. 15858 /// template <> template \<class T> friend class A<int>::B; 15859 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 15860 MultiTemplateParamsArg TempParams) { 15861 SourceLocation Loc = DS.getBeginLoc(); 15862 15863 assert(DS.isFriendSpecified()); 15864 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 15865 15866 // C++ [class.friend]p3: 15867 // A friend declaration that does not declare a function shall have one of 15868 // the following forms: 15869 // friend elaborated-type-specifier ; 15870 // friend simple-type-specifier ; 15871 // friend typename-specifier ; 15872 // 15873 // Any declaration with a type qualifier does not have that form. (It's 15874 // legal to specify a qualified type as a friend, you just can't write the 15875 // keywords.) 15876 if (DS.getTypeQualifiers()) { 15877 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 15878 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 15879 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 15880 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 15881 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 15882 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 15883 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 15884 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 15885 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 15886 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 15887 } 15888 15889 // Try to convert the decl specifier to a type. This works for 15890 // friend templates because ActOnTag never produces a ClassTemplateDecl 15891 // for a TUK_Friend. 15892 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 15893 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 15894 QualType T = TSI->getType(); 15895 if (TheDeclarator.isInvalidType()) 15896 return nullptr; 15897 15898 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 15899 return nullptr; 15900 15901 // This is definitely an error in C++98. It's probably meant to 15902 // be forbidden in C++0x, too, but the specification is just 15903 // poorly written. 15904 // 15905 // The problem is with declarations like the following: 15906 // template <T> friend A<T>::foo; 15907 // where deciding whether a class C is a friend or not now hinges 15908 // on whether there exists an instantiation of A that causes 15909 // 'foo' to equal C. There are restrictions on class-heads 15910 // (which we declare (by fiat) elaborated friend declarations to 15911 // be) that makes this tractable. 15912 // 15913 // FIXME: handle "template <> friend class A<T>;", which 15914 // is possibly well-formed? Who even knows? 15915 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 15916 Diag(Loc, diag::err_tagless_friend_type_template) 15917 << DS.getSourceRange(); 15918 return nullptr; 15919 } 15920 15921 // C++98 [class.friend]p1: A friend of a class is a function 15922 // or class that is not a member of the class . . . 15923 // This is fixed in DR77, which just barely didn't make the C++03 15924 // deadline. It's also a very silly restriction that seriously 15925 // affects inner classes and which nobody else seems to implement; 15926 // thus we never diagnose it, not even in -pedantic. 15927 // 15928 // But note that we could warn about it: it's always useless to 15929 // friend one of your own members (it's not, however, worthless to 15930 // friend a member of an arbitrary specialization of your template). 15931 15932 Decl *D; 15933 if (!TempParams.empty()) 15934 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 15935 TempParams, 15936 TSI, 15937 DS.getFriendSpecLoc()); 15938 else 15939 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 15940 15941 if (!D) 15942 return nullptr; 15943 15944 D->setAccess(AS_public); 15945 CurContext->addDecl(D); 15946 15947 return D; 15948 } 15949 15950 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 15951 MultiTemplateParamsArg TemplateParams) { 15952 const DeclSpec &DS = D.getDeclSpec(); 15953 15954 assert(DS.isFriendSpecified()); 15955 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 15956 15957 SourceLocation Loc = D.getIdentifierLoc(); 15958 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15959 15960 // C++ [class.friend]p1 15961 // A friend of a class is a function or class.... 15962 // Note that this sees through typedefs, which is intended. 15963 // It *doesn't* see through dependent types, which is correct 15964 // according to [temp.arg.type]p3: 15965 // If a declaration acquires a function type through a 15966 // type dependent on a template-parameter and this causes 15967 // a declaration that does not use the syntactic form of a 15968 // function declarator to have a function type, the program 15969 // is ill-formed. 15970 if (!TInfo->getType()->isFunctionType()) { 15971 Diag(Loc, diag::err_unexpected_friend); 15972 15973 // It might be worthwhile to try to recover by creating an 15974 // appropriate declaration. 15975 return nullptr; 15976 } 15977 15978 // C++ [namespace.memdef]p3 15979 // - If a friend declaration in a non-local class first declares a 15980 // class or function, the friend class or function is a member 15981 // of the innermost enclosing namespace. 15982 // - The name of the friend is not found by simple name lookup 15983 // until a matching declaration is provided in that namespace 15984 // scope (either before or after the class declaration granting 15985 // friendship). 15986 // - If a friend function is called, its name may be found by the 15987 // name lookup that considers functions from namespaces and 15988 // classes associated with the types of the function arguments. 15989 // - When looking for a prior declaration of a class or a function 15990 // declared as a friend, scopes outside the innermost enclosing 15991 // namespace scope are not considered. 15992 15993 CXXScopeSpec &SS = D.getCXXScopeSpec(); 15994 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 15995 assert(NameInfo.getName()); 15996 15997 // Check for unexpanded parameter packs. 15998 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 15999 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16000 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16001 return nullptr; 16002 16003 // The context we found the declaration in, or in which we should 16004 // create the declaration. 16005 DeclContext *DC; 16006 Scope *DCScope = S; 16007 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16008 ForExternalRedeclaration); 16009 16010 // There are five cases here. 16011 // - There's no scope specifier and we're in a local class. Only look 16012 // for functions declared in the immediately-enclosing block scope. 16013 // We recover from invalid scope qualifiers as if they just weren't there. 16014 FunctionDecl *FunctionContainingLocalClass = nullptr; 16015 if ((SS.isInvalid() || !SS.isSet()) && 16016 (FunctionContainingLocalClass = 16017 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16018 // C++11 [class.friend]p11: 16019 // If a friend declaration appears in a local class and the name 16020 // specified is an unqualified name, a prior declaration is 16021 // looked up without considering scopes that are outside the 16022 // innermost enclosing non-class scope. For a friend function 16023 // declaration, if there is no prior declaration, the program is 16024 // ill-formed. 16025 16026 // Find the innermost enclosing non-class scope. This is the block 16027 // scope containing the local class definition (or for a nested class, 16028 // the outer local class). 16029 DCScope = S->getFnParent(); 16030 16031 // Look up the function name in the scope. 16032 Previous.clear(LookupLocalFriendName); 16033 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16034 16035 if (!Previous.empty()) { 16036 // All possible previous declarations must have the same context: 16037 // either they were declared at block scope or they are members of 16038 // one of the enclosing local classes. 16039 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16040 } else { 16041 // This is ill-formed, but provide the context that we would have 16042 // declared the function in, if we were permitted to, for error recovery. 16043 DC = FunctionContainingLocalClass; 16044 } 16045 adjustContextForLocalExternDecl(DC); 16046 16047 // C++ [class.friend]p6: 16048 // A function can be defined in a friend declaration of a class if and 16049 // only if the class is a non-local class (9.8), the function name is 16050 // unqualified, and the function has namespace scope. 16051 if (D.isFunctionDefinition()) { 16052 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16053 } 16054 16055 // - There's no scope specifier, in which case we just go to the 16056 // appropriate scope and look for a function or function template 16057 // there as appropriate. 16058 } else if (SS.isInvalid() || !SS.isSet()) { 16059 // C++11 [namespace.memdef]p3: 16060 // If the name in a friend declaration is neither qualified nor 16061 // a template-id and the declaration is a function or an 16062 // elaborated-type-specifier, the lookup to determine whether 16063 // the entity has been previously declared shall not consider 16064 // any scopes outside the innermost enclosing namespace. 16065 bool isTemplateId = 16066 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16067 16068 // Find the appropriate context according to the above. 16069 DC = CurContext; 16070 16071 // Skip class contexts. If someone can cite chapter and verse 16072 // for this behavior, that would be nice --- it's what GCC and 16073 // EDG do, and it seems like a reasonable intent, but the spec 16074 // really only says that checks for unqualified existing 16075 // declarations should stop at the nearest enclosing namespace, 16076 // not that they should only consider the nearest enclosing 16077 // namespace. 16078 while (DC->isRecord()) 16079 DC = DC->getParent(); 16080 16081 DeclContext *LookupDC = DC; 16082 while (LookupDC->isTransparentContext()) 16083 LookupDC = LookupDC->getParent(); 16084 16085 while (true) { 16086 LookupQualifiedName(Previous, LookupDC); 16087 16088 if (!Previous.empty()) { 16089 DC = LookupDC; 16090 break; 16091 } 16092 16093 if (isTemplateId) { 16094 if (isa<TranslationUnitDecl>(LookupDC)) break; 16095 } else { 16096 if (LookupDC->isFileContext()) break; 16097 } 16098 LookupDC = LookupDC->getParent(); 16099 } 16100 16101 DCScope = getScopeForDeclContext(S, DC); 16102 16103 // - There's a non-dependent scope specifier, in which case we 16104 // compute it and do a previous lookup there for a function 16105 // or function template. 16106 } else if (!SS.getScopeRep()->isDependent()) { 16107 DC = computeDeclContext(SS); 16108 if (!DC) return nullptr; 16109 16110 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16111 16112 LookupQualifiedName(Previous, DC); 16113 16114 // C++ [class.friend]p1: A friend of a class is a function or 16115 // class that is not a member of the class . . . 16116 if (DC->Equals(CurContext)) 16117 Diag(DS.getFriendSpecLoc(), 16118 getLangOpts().CPlusPlus11 ? 16119 diag::warn_cxx98_compat_friend_is_member : 16120 diag::err_friend_is_member); 16121 16122 if (D.isFunctionDefinition()) { 16123 // C++ [class.friend]p6: 16124 // A function can be defined in a friend declaration of a class if and 16125 // only if the class is a non-local class (9.8), the function name is 16126 // unqualified, and the function has namespace scope. 16127 // 16128 // FIXME: We should only do this if the scope specifier names the 16129 // innermost enclosing namespace; otherwise the fixit changes the 16130 // meaning of the code. 16131 SemaDiagnosticBuilder DB 16132 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16133 16134 DB << SS.getScopeRep(); 16135 if (DC->isFileContext()) 16136 DB << FixItHint::CreateRemoval(SS.getRange()); 16137 SS.clear(); 16138 } 16139 16140 // - There's a scope specifier that does not match any template 16141 // parameter lists, in which case we use some arbitrary context, 16142 // create a method or method template, and wait for instantiation. 16143 // - There's a scope specifier that does match some template 16144 // parameter lists, which we don't handle right now. 16145 } else { 16146 if (D.isFunctionDefinition()) { 16147 // C++ [class.friend]p6: 16148 // A function can be defined in a friend declaration of a class if and 16149 // only if the class is a non-local class (9.8), the function name is 16150 // unqualified, and the function has namespace scope. 16151 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16152 << SS.getScopeRep(); 16153 } 16154 16155 DC = CurContext; 16156 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16157 } 16158 16159 if (!DC->isRecord()) { 16160 int DiagArg = -1; 16161 switch (D.getName().getKind()) { 16162 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16163 case UnqualifiedIdKind::IK_ConstructorName: 16164 DiagArg = 0; 16165 break; 16166 case UnqualifiedIdKind::IK_DestructorName: 16167 DiagArg = 1; 16168 break; 16169 case UnqualifiedIdKind::IK_ConversionFunctionId: 16170 DiagArg = 2; 16171 break; 16172 case UnqualifiedIdKind::IK_DeductionGuideName: 16173 DiagArg = 3; 16174 break; 16175 case UnqualifiedIdKind::IK_Identifier: 16176 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16177 case UnqualifiedIdKind::IK_LiteralOperatorId: 16178 case UnqualifiedIdKind::IK_OperatorFunctionId: 16179 case UnqualifiedIdKind::IK_TemplateId: 16180 break; 16181 } 16182 // This implies that it has to be an operator or function. 16183 if (DiagArg >= 0) { 16184 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16185 return nullptr; 16186 } 16187 } 16188 16189 // FIXME: This is an egregious hack to cope with cases where the scope stack 16190 // does not contain the declaration context, i.e., in an out-of-line 16191 // definition of a class. 16192 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16193 if (!DCScope) { 16194 FakeDCScope.setEntity(DC); 16195 DCScope = &FakeDCScope; 16196 } 16197 16198 bool AddToScope = true; 16199 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16200 TemplateParams, AddToScope); 16201 if (!ND) return nullptr; 16202 16203 assert(ND->getLexicalDeclContext() == CurContext); 16204 16205 // If we performed typo correction, we might have added a scope specifier 16206 // and changed the decl context. 16207 DC = ND->getDeclContext(); 16208 16209 // Add the function declaration to the appropriate lookup tables, 16210 // adjusting the redeclarations list as necessary. We don't 16211 // want to do this yet if the friending class is dependent. 16212 // 16213 // Also update the scope-based lookup if the target context's 16214 // lookup context is in lexical scope. 16215 if (!CurContext->isDependentContext()) { 16216 DC = DC->getRedeclContext(); 16217 DC->makeDeclVisibleInContext(ND); 16218 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16219 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16220 } 16221 16222 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16223 D.getIdentifierLoc(), ND, 16224 DS.getFriendSpecLoc()); 16225 FrD->setAccess(AS_public); 16226 CurContext->addDecl(FrD); 16227 16228 if (ND->isInvalidDecl()) { 16229 FrD->setInvalidDecl(); 16230 } else { 16231 if (DC->isRecord()) CheckFriendAccess(ND); 16232 16233 FunctionDecl *FD; 16234 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16235 FD = FTD->getTemplatedDecl(); 16236 else 16237 FD = cast<FunctionDecl>(ND); 16238 16239 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16240 // default argument expression, that declaration shall be a definition 16241 // and shall be the only declaration of the function or function 16242 // template in the translation unit. 16243 if (functionDeclHasDefaultArgument(FD)) { 16244 // We can't look at FD->getPreviousDecl() because it may not have been set 16245 // if we're in a dependent context. If the function is known to be a 16246 // redeclaration, we will have narrowed Previous down to the right decl. 16247 if (D.isRedeclaration()) { 16248 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16249 Diag(Previous.getRepresentativeDecl()->getLocation(), 16250 diag::note_previous_declaration); 16251 } else if (!D.isFunctionDefinition()) 16252 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16253 } 16254 16255 // Mark templated-scope function declarations as unsupported. 16256 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16257 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16258 << SS.getScopeRep() << SS.getRange() 16259 << cast<CXXRecordDecl>(CurContext); 16260 FrD->setUnsupportedFriend(true); 16261 } 16262 } 16263 16264 return ND; 16265 } 16266 16267 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16268 AdjustDeclIfTemplate(Dcl); 16269 16270 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16271 if (!Fn) { 16272 Diag(DelLoc, diag::err_deleted_non_function); 16273 return; 16274 } 16275 16276 // Deleted function does not have a body. 16277 Fn->setWillHaveBody(false); 16278 16279 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16280 // Don't consider the implicit declaration we generate for explicit 16281 // specializations. FIXME: Do not generate these implicit declarations. 16282 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16283 Prev->getPreviousDecl()) && 16284 !Prev->isDefined()) { 16285 Diag(DelLoc, diag::err_deleted_decl_not_first); 16286 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16287 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16288 : diag::note_previous_declaration); 16289 } 16290 // If the declaration wasn't the first, we delete the function anyway for 16291 // recovery. 16292 Fn = Fn->getCanonicalDecl(); 16293 } 16294 16295 // dllimport/dllexport cannot be deleted. 16296 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16297 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16298 Fn->setInvalidDecl(); 16299 } 16300 16301 if (Fn->isDeleted()) 16302 return; 16303 16304 // C++11 [basic.start.main]p3: 16305 // A program that defines main as deleted [...] is ill-formed. 16306 if (Fn->isMain()) 16307 Diag(DelLoc, diag::err_deleted_main); 16308 16309 // C++11 [dcl.fct.def.delete]p4: 16310 // A deleted function is implicitly inline. 16311 Fn->setImplicitlyInline(); 16312 Fn->setDeletedAsWritten(); 16313 16314 // See if we're deleting a function which is already known to override a 16315 // non-deleted virtual function. 16316 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 16317 bool IssuedDiagnostic = false; 16318 for (const CXXMethodDecl *O : MD->overridden_methods()) { 16319 if (!(*MD->begin_overridden_methods())->isDeleted()) { 16320 if (!IssuedDiagnostic) { 16321 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 16322 IssuedDiagnostic = true; 16323 } 16324 Diag(O->getLocation(), diag::note_overridden_virtual_function); 16325 } 16326 } 16327 // If this function was implicitly deleted because it was defaulted, 16328 // explain why it was deleted. 16329 if (IssuedDiagnostic && MD->isDefaulted()) 16330 DiagnoseDeletedDefaultedFunction(MD); 16331 } 16332 } 16333 16334 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16335 if (!Dcl || Dcl->isInvalidDecl()) 16336 return; 16337 16338 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16339 if (!FD) { 16340 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16341 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16342 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16343 return; 16344 } 16345 } 16346 16347 Diag(DefaultLoc, diag::err_default_special_members) 16348 << getLangOpts().CPlusPlus2a; 16349 return; 16350 } 16351 16352 // Reject if this can't possibly be a defaultable function. 16353 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16354 if (!DefKind && 16355 // A dependent function that doesn't locally look defaultable can 16356 // still instantiate to a defaultable function if it's a constructor 16357 // or assignment operator. 16358 (!FD->isDependentContext() || 16359 (!isa<CXXConstructorDecl>(FD) && 16360 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16361 Diag(DefaultLoc, diag::err_default_special_members) 16362 << getLangOpts().CPlusPlus2a; 16363 return; 16364 } 16365 16366 if (DefKind.isComparison() && 16367 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16368 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16369 << (int)DefKind.asComparison(); 16370 return; 16371 } 16372 16373 // Issue compatibility warning. We already warned if the operator is 16374 // 'operator<=>' when parsing the '<=>' token. 16375 if (DefKind.isComparison() && 16376 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16377 Diag(DefaultLoc, getLangOpts().CPlusPlus2a 16378 ? diag::warn_cxx17_compat_defaulted_comparison 16379 : diag::ext_defaulted_comparison); 16380 } 16381 16382 FD->setDefaulted(); 16383 FD->setExplicitlyDefaulted(); 16384 16385 // Defer checking functions that are defaulted in a dependent context. 16386 if (FD->isDependentContext()) 16387 return; 16388 16389 // Unset that we will have a body for this function. We might not, 16390 // if it turns out to be trivial, and we don't need this marking now 16391 // that we've marked it as defaulted. 16392 FD->setWillHaveBody(false); 16393 16394 // If this definition appears within the record, do the checking when 16395 // the record is complete. This is always the case for a defaulted 16396 // comparison. 16397 if (DefKind.isComparison()) 16398 return; 16399 auto *MD = cast<CXXMethodDecl>(FD); 16400 16401 const FunctionDecl *Primary = FD; 16402 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16403 // Ask the template instantiation pattern that actually had the 16404 // '= default' on it. 16405 Primary = Pattern; 16406 16407 // If the method was defaulted on its first declaration, we will have 16408 // already performed the checking in CheckCompletedCXXClass. Such a 16409 // declaration doesn't trigger an implicit definition. 16410 if (Primary->getCanonicalDecl()->isDefaulted()) 16411 return; 16412 16413 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16414 MD->setInvalidDecl(); 16415 else 16416 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 16417 } 16418 16419 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16420 for (Stmt *SubStmt : S->children()) { 16421 if (!SubStmt) 16422 continue; 16423 if (isa<ReturnStmt>(SubStmt)) 16424 Self.Diag(SubStmt->getBeginLoc(), 16425 diag::err_return_in_constructor_handler); 16426 if (!isa<Expr>(SubStmt)) 16427 SearchForReturnInStmt(Self, SubStmt); 16428 } 16429 } 16430 16431 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16432 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16433 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16434 SearchForReturnInStmt(*this, Handler); 16435 } 16436 } 16437 16438 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16439 const CXXMethodDecl *Old) { 16440 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 16441 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 16442 16443 if (OldFT->hasExtParameterInfos()) { 16444 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16445 // A parameter of the overriding method should be annotated with noescape 16446 // if the corresponding parameter of the overridden method is annotated. 16447 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16448 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16449 Diag(New->getParamDecl(I)->getLocation(), 16450 diag::warn_overriding_method_missing_noescape); 16451 Diag(Old->getParamDecl(I)->getLocation(), 16452 diag::note_overridden_marked_noescape); 16453 } 16454 } 16455 16456 // Virtual overrides must have the same code_seg. 16457 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16458 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16459 if ((NewCSA || OldCSA) && 16460 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16461 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16462 Diag(Old->getLocation(), diag::note_previous_declaration); 16463 return true; 16464 } 16465 16466 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16467 16468 // If the calling conventions match, everything is fine 16469 if (NewCC == OldCC) 16470 return false; 16471 16472 // If the calling conventions mismatch because the new function is static, 16473 // suppress the calling convention mismatch error; the error about static 16474 // function override (err_static_overrides_virtual from 16475 // Sema::CheckFunctionDeclaration) is more clear. 16476 if (New->getStorageClass() == SC_Static) 16477 return false; 16478 16479 Diag(New->getLocation(), 16480 diag::err_conflicting_overriding_cc_attributes) 16481 << New->getDeclName() << New->getType() << Old->getType(); 16482 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16483 return true; 16484 } 16485 16486 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16487 const CXXMethodDecl *Old) { 16488 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 16489 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 16490 16491 if (Context.hasSameType(NewTy, OldTy) || 16492 NewTy->isDependentType() || OldTy->isDependentType()) 16493 return false; 16494 16495 // Check if the return types are covariant 16496 QualType NewClassTy, OldClassTy; 16497 16498 /// Both types must be pointers or references to classes. 16499 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16500 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16501 NewClassTy = NewPT->getPointeeType(); 16502 OldClassTy = OldPT->getPointeeType(); 16503 } 16504 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16505 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16506 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16507 NewClassTy = NewRT->getPointeeType(); 16508 OldClassTy = OldRT->getPointeeType(); 16509 } 16510 } 16511 } 16512 16513 // The return types aren't either both pointers or references to a class type. 16514 if (NewClassTy.isNull()) { 16515 Diag(New->getLocation(), 16516 diag::err_different_return_type_for_overriding_virtual_function) 16517 << New->getDeclName() << NewTy << OldTy 16518 << New->getReturnTypeSourceRange(); 16519 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16520 << Old->getReturnTypeSourceRange(); 16521 16522 return true; 16523 } 16524 16525 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16526 // C++14 [class.virtual]p8: 16527 // If the class type in the covariant return type of D::f differs from 16528 // that of B::f, the class type in the return type of D::f shall be 16529 // complete at the point of declaration of D::f or shall be the class 16530 // type D. 16531 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16532 if (!RT->isBeingDefined() && 16533 RequireCompleteType(New->getLocation(), NewClassTy, 16534 diag::err_covariant_return_incomplete, 16535 New->getDeclName())) 16536 return true; 16537 } 16538 16539 // Check if the new class derives from the old class. 16540 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 16541 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 16542 << New->getDeclName() << NewTy << OldTy 16543 << New->getReturnTypeSourceRange(); 16544 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16545 << Old->getReturnTypeSourceRange(); 16546 return true; 16547 } 16548 16549 // Check if we the conversion from derived to base is valid. 16550 if (CheckDerivedToBaseConversion( 16551 NewClassTy, OldClassTy, 16552 diag::err_covariant_return_inaccessible_base, 16553 diag::err_covariant_return_ambiguous_derived_to_base_conv, 16554 New->getLocation(), New->getReturnTypeSourceRange(), 16555 New->getDeclName(), nullptr)) { 16556 // FIXME: this note won't trigger for delayed access control 16557 // diagnostics, and it's impossible to get an undelayed error 16558 // here from access control during the original parse because 16559 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 16560 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16561 << Old->getReturnTypeSourceRange(); 16562 return true; 16563 } 16564 } 16565 16566 // The qualifiers of the return types must be the same. 16567 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 16568 Diag(New->getLocation(), 16569 diag::err_covariant_return_type_different_qualifications) 16570 << New->getDeclName() << NewTy << OldTy 16571 << New->getReturnTypeSourceRange(); 16572 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16573 << Old->getReturnTypeSourceRange(); 16574 return true; 16575 } 16576 16577 16578 // The new class type must have the same or less qualifiers as the old type. 16579 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 16580 Diag(New->getLocation(), 16581 diag::err_covariant_return_type_class_type_more_qualified) 16582 << New->getDeclName() << NewTy << OldTy 16583 << New->getReturnTypeSourceRange(); 16584 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16585 << Old->getReturnTypeSourceRange(); 16586 return true; 16587 } 16588 16589 return false; 16590 } 16591 16592 /// Mark the given method pure. 16593 /// 16594 /// \param Method the method to be marked pure. 16595 /// 16596 /// \param InitRange the source range that covers the "0" initializer. 16597 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 16598 SourceLocation EndLoc = InitRange.getEnd(); 16599 if (EndLoc.isValid()) 16600 Method->setRangeEnd(EndLoc); 16601 16602 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 16603 Method->setPure(); 16604 return false; 16605 } 16606 16607 if (!Method->isInvalidDecl()) 16608 Diag(Method->getLocation(), diag::err_non_virtual_pure) 16609 << Method->getDeclName() << InitRange; 16610 return true; 16611 } 16612 16613 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 16614 if (D->getFriendObjectKind()) 16615 Diag(D->getLocation(), diag::err_pure_friend); 16616 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 16617 CheckPureMethod(M, ZeroLoc); 16618 else 16619 Diag(D->getLocation(), diag::err_illegal_initializer); 16620 } 16621 16622 /// Determine whether the given declaration is a global variable or 16623 /// static data member. 16624 static bool isNonlocalVariable(const Decl *D) { 16625 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 16626 return Var->hasGlobalStorage(); 16627 16628 return false; 16629 } 16630 16631 /// Invoked when we are about to parse an initializer for the declaration 16632 /// 'Dcl'. 16633 /// 16634 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 16635 /// static data member of class X, names should be looked up in the scope of 16636 /// class X. If the declaration had a scope specifier, a scope will have 16637 /// been created and passed in for this purpose. Otherwise, S will be null. 16638 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 16639 // If there is no declaration, there was an error parsing it. 16640 if (!D || D->isInvalidDecl()) 16641 return; 16642 16643 // We will always have a nested name specifier here, but this declaration 16644 // might not be out of line if the specifier names the current namespace: 16645 // extern int n; 16646 // int ::n = 0; 16647 if (S && D->isOutOfLine()) 16648 EnterDeclaratorContext(S, D->getDeclContext()); 16649 16650 // If we are parsing the initializer for a static data member, push a 16651 // new expression evaluation context that is associated with this static 16652 // data member. 16653 if (isNonlocalVariable(D)) 16654 PushExpressionEvaluationContext( 16655 ExpressionEvaluationContext::PotentiallyEvaluated, D); 16656 } 16657 16658 /// Invoked after we are finished parsing an initializer for the declaration D. 16659 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 16660 // If there is no declaration, there was an error parsing it. 16661 if (!D || D->isInvalidDecl()) 16662 return; 16663 16664 if (isNonlocalVariable(D)) 16665 PopExpressionEvaluationContext(); 16666 16667 if (S && D->isOutOfLine()) 16668 ExitDeclaratorContext(S); 16669 } 16670 16671 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 16672 /// C++ if/switch/while/for statement. 16673 /// e.g: "if (int x = f()) {...}" 16674 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 16675 // C++ 6.4p2: 16676 // The declarator shall not specify a function or an array. 16677 // The type-specifier-seq shall not contain typedef and shall not declare a 16678 // new class or enumeration. 16679 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 16680 "Parser allowed 'typedef' as storage class of condition decl."); 16681 16682 Decl *Dcl = ActOnDeclarator(S, D); 16683 if (!Dcl) 16684 return true; 16685 16686 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 16687 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 16688 << D.getSourceRange(); 16689 return true; 16690 } 16691 16692 return Dcl; 16693 } 16694 16695 void Sema::LoadExternalVTableUses() { 16696 if (!ExternalSource) 16697 return; 16698 16699 SmallVector<ExternalVTableUse, 4> VTables; 16700 ExternalSource->ReadUsedVTables(VTables); 16701 SmallVector<VTableUse, 4> NewUses; 16702 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 16703 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 16704 = VTablesUsed.find(VTables[I].Record); 16705 // Even if a definition wasn't required before, it may be required now. 16706 if (Pos != VTablesUsed.end()) { 16707 if (!Pos->second && VTables[I].DefinitionRequired) 16708 Pos->second = true; 16709 continue; 16710 } 16711 16712 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 16713 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 16714 } 16715 16716 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 16717 } 16718 16719 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 16720 bool DefinitionRequired) { 16721 // Ignore any vtable uses in unevaluated operands or for classes that do 16722 // not have a vtable. 16723 if (!Class->isDynamicClass() || Class->isDependentContext() || 16724 CurContext->isDependentContext() || isUnevaluatedContext()) 16725 return; 16726 // Do not mark as used if compiling for the device outside of the target 16727 // region. 16728 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 16729 !isInOpenMPDeclareTargetContext() && 16730 !isInOpenMPTargetExecutionDirective()) { 16731 if (!DefinitionRequired) 16732 MarkVirtualMembersReferenced(Loc, Class); 16733 return; 16734 } 16735 16736 // Try to insert this class into the map. 16737 LoadExternalVTableUses(); 16738 Class = Class->getCanonicalDecl(); 16739 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 16740 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 16741 if (!Pos.second) { 16742 // If we already had an entry, check to see if we are promoting this vtable 16743 // to require a definition. If so, we need to reappend to the VTableUses 16744 // list, since we may have already processed the first entry. 16745 if (DefinitionRequired && !Pos.first->second) { 16746 Pos.first->second = true; 16747 } else { 16748 // Otherwise, we can early exit. 16749 return; 16750 } 16751 } else { 16752 // The Microsoft ABI requires that we perform the destructor body 16753 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 16754 // the deleting destructor is emitted with the vtable, not with the 16755 // destructor definition as in the Itanium ABI. 16756 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16757 CXXDestructorDecl *DD = Class->getDestructor(); 16758 if (DD && DD->isVirtual() && !DD->isDeleted()) { 16759 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 16760 // If this is an out-of-line declaration, marking it referenced will 16761 // not do anything. Manually call CheckDestructor to look up operator 16762 // delete(). 16763 ContextRAII SavedContext(*this, DD); 16764 CheckDestructor(DD); 16765 } else { 16766 MarkFunctionReferenced(Loc, Class->getDestructor()); 16767 } 16768 } 16769 } 16770 } 16771 16772 // Local classes need to have their virtual members marked 16773 // immediately. For all other classes, we mark their virtual members 16774 // at the end of the translation unit. 16775 if (Class->isLocalClass()) 16776 MarkVirtualMembersReferenced(Loc, Class); 16777 else 16778 VTableUses.push_back(std::make_pair(Class, Loc)); 16779 } 16780 16781 bool Sema::DefineUsedVTables() { 16782 LoadExternalVTableUses(); 16783 if (VTableUses.empty()) 16784 return false; 16785 16786 // Note: The VTableUses vector could grow as a result of marking 16787 // the members of a class as "used", so we check the size each 16788 // time through the loop and prefer indices (which are stable) to 16789 // iterators (which are not). 16790 bool DefinedAnything = false; 16791 for (unsigned I = 0; I != VTableUses.size(); ++I) { 16792 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 16793 if (!Class) 16794 continue; 16795 TemplateSpecializationKind ClassTSK = 16796 Class->getTemplateSpecializationKind(); 16797 16798 SourceLocation Loc = VTableUses[I].second; 16799 16800 bool DefineVTable = true; 16801 16802 // If this class has a key function, but that key function is 16803 // defined in another translation unit, we don't need to emit the 16804 // vtable even though we're using it. 16805 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 16806 if (KeyFunction && !KeyFunction->hasBody()) { 16807 // The key function is in another translation unit. 16808 DefineVTable = false; 16809 TemplateSpecializationKind TSK = 16810 KeyFunction->getTemplateSpecializationKind(); 16811 assert(TSK != TSK_ExplicitInstantiationDefinition && 16812 TSK != TSK_ImplicitInstantiation && 16813 "Instantiations don't have key functions"); 16814 (void)TSK; 16815 } else if (!KeyFunction) { 16816 // If we have a class with no key function that is the subject 16817 // of an explicit instantiation declaration, suppress the 16818 // vtable; it will live with the explicit instantiation 16819 // definition. 16820 bool IsExplicitInstantiationDeclaration = 16821 ClassTSK == TSK_ExplicitInstantiationDeclaration; 16822 for (auto R : Class->redecls()) { 16823 TemplateSpecializationKind TSK 16824 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 16825 if (TSK == TSK_ExplicitInstantiationDeclaration) 16826 IsExplicitInstantiationDeclaration = true; 16827 else if (TSK == TSK_ExplicitInstantiationDefinition) { 16828 IsExplicitInstantiationDeclaration = false; 16829 break; 16830 } 16831 } 16832 16833 if (IsExplicitInstantiationDeclaration) 16834 DefineVTable = false; 16835 } 16836 16837 // The exception specifications for all virtual members may be needed even 16838 // if we are not providing an authoritative form of the vtable in this TU. 16839 // We may choose to emit it available_externally anyway. 16840 if (!DefineVTable) { 16841 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 16842 continue; 16843 } 16844 16845 // Mark all of the virtual members of this class as referenced, so 16846 // that we can build a vtable. Then, tell the AST consumer that a 16847 // vtable for this class is required. 16848 DefinedAnything = true; 16849 MarkVirtualMembersReferenced(Loc, Class); 16850 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 16851 if (VTablesUsed[Canonical]) 16852 Consumer.HandleVTable(Class); 16853 16854 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 16855 // no key function or the key function is inlined. Don't warn in C++ ABIs 16856 // that lack key functions, since the user won't be able to make one. 16857 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 16858 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 16859 const FunctionDecl *KeyFunctionDef = nullptr; 16860 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 16861 KeyFunctionDef->isInlined())) { 16862 Diag(Class->getLocation(), 16863 ClassTSK == TSK_ExplicitInstantiationDefinition 16864 ? diag::warn_weak_template_vtable 16865 : diag::warn_weak_vtable) 16866 << Class; 16867 } 16868 } 16869 } 16870 VTableUses.clear(); 16871 16872 return DefinedAnything; 16873 } 16874 16875 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 16876 const CXXRecordDecl *RD) { 16877 for (const auto *I : RD->methods()) 16878 if (I->isVirtual() && !I->isPure()) 16879 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 16880 } 16881 16882 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 16883 const CXXRecordDecl *RD, 16884 bool ConstexprOnly) { 16885 // Mark all functions which will appear in RD's vtable as used. 16886 CXXFinalOverriderMap FinalOverriders; 16887 RD->getFinalOverriders(FinalOverriders); 16888 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 16889 E = FinalOverriders.end(); 16890 I != E; ++I) { 16891 for (OverridingMethods::const_iterator OI = I->second.begin(), 16892 OE = I->second.end(); 16893 OI != OE; ++OI) { 16894 assert(OI->second.size() > 0 && "no final overrider"); 16895 CXXMethodDecl *Overrider = OI->second.front().Method; 16896 16897 // C++ [basic.def.odr]p2: 16898 // [...] A virtual member function is used if it is not pure. [...] 16899 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 16900 MarkFunctionReferenced(Loc, Overrider); 16901 } 16902 } 16903 16904 // Only classes that have virtual bases need a VTT. 16905 if (RD->getNumVBases() == 0) 16906 return; 16907 16908 for (const auto &I : RD->bases()) { 16909 const auto *Base = 16910 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 16911 if (Base->getNumVBases() == 0) 16912 continue; 16913 MarkVirtualMembersReferenced(Loc, Base); 16914 } 16915 } 16916 16917 /// SetIvarInitializers - This routine builds initialization ASTs for the 16918 /// Objective-C implementation whose ivars need be initialized. 16919 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 16920 if (!getLangOpts().CPlusPlus) 16921 return; 16922 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 16923 SmallVector<ObjCIvarDecl*, 8> ivars; 16924 CollectIvarsToConstructOrDestruct(OID, ivars); 16925 if (ivars.empty()) 16926 return; 16927 SmallVector<CXXCtorInitializer*, 32> AllToInit; 16928 for (unsigned i = 0; i < ivars.size(); i++) { 16929 FieldDecl *Field = ivars[i]; 16930 if (Field->isInvalidDecl()) 16931 continue; 16932 16933 CXXCtorInitializer *Member; 16934 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 16935 InitializationKind InitKind = 16936 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 16937 16938 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 16939 ExprResult MemberInit = 16940 InitSeq.Perform(*this, InitEntity, InitKind, None); 16941 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 16942 // Note, MemberInit could actually come back empty if no initialization 16943 // is required (e.g., because it would call a trivial default constructor) 16944 if (!MemberInit.get() || MemberInit.isInvalid()) 16945 continue; 16946 16947 Member = 16948 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 16949 SourceLocation(), 16950 MemberInit.getAs<Expr>(), 16951 SourceLocation()); 16952 AllToInit.push_back(Member); 16953 16954 // Be sure that the destructor is accessible and is marked as referenced. 16955 if (const RecordType *RecordTy = 16956 Context.getBaseElementType(Field->getType()) 16957 ->getAs<RecordType>()) { 16958 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 16959 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 16960 MarkFunctionReferenced(Field->getLocation(), Destructor); 16961 CheckDestructorAccess(Field->getLocation(), Destructor, 16962 PDiag(diag::err_access_dtor_ivar) 16963 << Context.getBaseElementType(Field->getType())); 16964 } 16965 } 16966 } 16967 ObjCImplementation->setIvarInitializers(Context, 16968 AllToInit.data(), AllToInit.size()); 16969 } 16970 } 16971 16972 static 16973 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 16974 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 16975 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 16976 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 16977 Sema &S) { 16978 if (Ctor->isInvalidDecl()) 16979 return; 16980 16981 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 16982 16983 // Target may not be determinable yet, for instance if this is a dependent 16984 // call in an uninstantiated template. 16985 if (Target) { 16986 const FunctionDecl *FNTarget = nullptr; 16987 (void)Target->hasBody(FNTarget); 16988 Target = const_cast<CXXConstructorDecl*>( 16989 cast_or_null<CXXConstructorDecl>(FNTarget)); 16990 } 16991 16992 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 16993 // Avoid dereferencing a null pointer here. 16994 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 16995 16996 if (!Current.insert(Canonical).second) 16997 return; 16998 16999 // We know that beyond here, we aren't chaining into a cycle. 17000 if (!Target || !Target->isDelegatingConstructor() || 17001 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17002 Valid.insert(Current.begin(), Current.end()); 17003 Current.clear(); 17004 // We've hit a cycle. 17005 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17006 Current.count(TCanonical)) { 17007 // If we haven't diagnosed this cycle yet, do so now. 17008 if (!Invalid.count(TCanonical)) { 17009 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17010 diag::warn_delegating_ctor_cycle) 17011 << Ctor; 17012 17013 // Don't add a note for a function delegating directly to itself. 17014 if (TCanonical != Canonical) 17015 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17016 17017 CXXConstructorDecl *C = Target; 17018 while (C->getCanonicalDecl() != Canonical) { 17019 const FunctionDecl *FNTarget = nullptr; 17020 (void)C->getTargetConstructor()->hasBody(FNTarget); 17021 assert(FNTarget && "Ctor cycle through bodiless function"); 17022 17023 C = const_cast<CXXConstructorDecl*>( 17024 cast<CXXConstructorDecl>(FNTarget)); 17025 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17026 } 17027 } 17028 17029 Invalid.insert(Current.begin(), Current.end()); 17030 Current.clear(); 17031 } else { 17032 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17033 } 17034 } 17035 17036 17037 void Sema::CheckDelegatingCtorCycles() { 17038 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17039 17040 for (DelegatingCtorDeclsType::iterator 17041 I = DelegatingCtorDecls.begin(ExternalSource), 17042 E = DelegatingCtorDecls.end(); 17043 I != E; ++I) 17044 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17045 17046 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17047 (*CI)->setInvalidDecl(); 17048 } 17049 17050 namespace { 17051 /// AST visitor that finds references to the 'this' expression. 17052 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17053 Sema &S; 17054 17055 public: 17056 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17057 17058 bool VisitCXXThisExpr(CXXThisExpr *E) { 17059 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17060 << E->isImplicit(); 17061 return false; 17062 } 17063 }; 17064 } 17065 17066 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17067 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17068 if (!TSInfo) 17069 return false; 17070 17071 TypeLoc TL = TSInfo->getTypeLoc(); 17072 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17073 if (!ProtoTL) 17074 return false; 17075 17076 // C++11 [expr.prim.general]p3: 17077 // [The expression this] shall not appear before the optional 17078 // cv-qualifier-seq and it shall not appear within the declaration of a 17079 // static member function (although its type and value category are defined 17080 // within a static member function as they are within a non-static member 17081 // function). [ Note: this is because declaration matching does not occur 17082 // until the complete declarator is known. - end note ] 17083 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17084 FindCXXThisExpr Finder(*this); 17085 17086 // If the return type came after the cv-qualifier-seq, check it now. 17087 if (Proto->hasTrailingReturn() && 17088 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17089 return true; 17090 17091 // Check the exception specification. 17092 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17093 return true; 17094 17095 return checkThisInStaticMemberFunctionAttributes(Method); 17096 } 17097 17098 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17099 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17100 if (!TSInfo) 17101 return false; 17102 17103 TypeLoc TL = TSInfo->getTypeLoc(); 17104 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17105 if (!ProtoTL) 17106 return false; 17107 17108 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17109 FindCXXThisExpr Finder(*this); 17110 17111 switch (Proto->getExceptionSpecType()) { 17112 case EST_Unparsed: 17113 case EST_Uninstantiated: 17114 case EST_Unevaluated: 17115 case EST_BasicNoexcept: 17116 case EST_NoThrow: 17117 case EST_DynamicNone: 17118 case EST_MSAny: 17119 case EST_None: 17120 break; 17121 17122 case EST_DependentNoexcept: 17123 case EST_NoexceptFalse: 17124 case EST_NoexceptTrue: 17125 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17126 return true; 17127 LLVM_FALLTHROUGH; 17128 17129 case EST_Dynamic: 17130 for (const auto &E : Proto->exceptions()) { 17131 if (!Finder.TraverseType(E)) 17132 return true; 17133 } 17134 break; 17135 } 17136 17137 return false; 17138 } 17139 17140 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17141 FindCXXThisExpr Finder(*this); 17142 17143 // Check attributes. 17144 for (const auto *A : Method->attrs()) { 17145 // FIXME: This should be emitted by tblgen. 17146 Expr *Arg = nullptr; 17147 ArrayRef<Expr *> Args; 17148 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17149 Arg = G->getArg(); 17150 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17151 Arg = G->getArg(); 17152 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17153 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17154 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17155 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17156 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17157 Arg = ETLF->getSuccessValue(); 17158 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17159 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17160 Arg = STLF->getSuccessValue(); 17161 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17162 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17163 Arg = LR->getArg(); 17164 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17165 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17166 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17167 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17168 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17169 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17170 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17171 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17172 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17173 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17174 17175 if (Arg && !Finder.TraverseStmt(Arg)) 17176 return true; 17177 17178 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17179 if (!Finder.TraverseStmt(Args[I])) 17180 return true; 17181 } 17182 } 17183 17184 return false; 17185 } 17186 17187 void Sema::checkExceptionSpecification( 17188 bool IsTopLevel, ExceptionSpecificationType EST, 17189 ArrayRef<ParsedType> DynamicExceptions, 17190 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17191 SmallVectorImpl<QualType> &Exceptions, 17192 FunctionProtoType::ExceptionSpecInfo &ESI) { 17193 Exceptions.clear(); 17194 ESI.Type = EST; 17195 if (EST == EST_Dynamic) { 17196 Exceptions.reserve(DynamicExceptions.size()); 17197 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17198 // FIXME: Preserve type source info. 17199 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17200 17201 if (IsTopLevel) { 17202 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17203 collectUnexpandedParameterPacks(ET, Unexpanded); 17204 if (!Unexpanded.empty()) { 17205 DiagnoseUnexpandedParameterPacks( 17206 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17207 Unexpanded); 17208 continue; 17209 } 17210 } 17211 17212 // Check that the type is valid for an exception spec, and 17213 // drop it if not. 17214 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17215 Exceptions.push_back(ET); 17216 } 17217 ESI.Exceptions = Exceptions; 17218 return; 17219 } 17220 17221 if (isComputedNoexcept(EST)) { 17222 assert((NoexceptExpr->isTypeDependent() || 17223 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17224 Context.BoolTy) && 17225 "Parser should have made sure that the expression is boolean"); 17226 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17227 ESI.Type = EST_BasicNoexcept; 17228 return; 17229 } 17230 17231 ESI.NoexceptExpr = NoexceptExpr; 17232 return; 17233 } 17234 } 17235 17236 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17237 ExceptionSpecificationType EST, 17238 SourceRange SpecificationRange, 17239 ArrayRef<ParsedType> DynamicExceptions, 17240 ArrayRef<SourceRange> DynamicExceptionRanges, 17241 Expr *NoexceptExpr) { 17242 if (!MethodD) 17243 return; 17244 17245 // Dig out the method we're referring to. 17246 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17247 MethodD = FunTmpl->getTemplatedDecl(); 17248 17249 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17250 if (!Method) 17251 return; 17252 17253 // Check the exception specification. 17254 llvm::SmallVector<QualType, 4> Exceptions; 17255 FunctionProtoType::ExceptionSpecInfo ESI; 17256 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17257 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17258 ESI); 17259 17260 // Update the exception specification on the function type. 17261 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17262 17263 if (Method->isStatic()) 17264 checkThisInStaticMemberFunctionExceptionSpec(Method); 17265 17266 if (Method->isVirtual()) { 17267 // Check overrides, which we previously had to delay. 17268 for (const CXXMethodDecl *O : Method->overridden_methods()) 17269 CheckOverridingFunctionExceptionSpec(Method, O); 17270 } 17271 } 17272 17273 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17274 /// 17275 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17276 SourceLocation DeclStart, Declarator &D, 17277 Expr *BitWidth, 17278 InClassInitStyle InitStyle, 17279 AccessSpecifier AS, 17280 const ParsedAttr &MSPropertyAttr) { 17281 IdentifierInfo *II = D.getIdentifier(); 17282 if (!II) { 17283 Diag(DeclStart, diag::err_anonymous_property); 17284 return nullptr; 17285 } 17286 SourceLocation Loc = D.getIdentifierLoc(); 17287 17288 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17289 QualType T = TInfo->getType(); 17290 if (getLangOpts().CPlusPlus) { 17291 CheckExtraCXXDefaultArguments(D); 17292 17293 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17294 UPPC_DataMemberType)) { 17295 D.setInvalidType(); 17296 T = Context.IntTy; 17297 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17298 } 17299 } 17300 17301 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17302 17303 if (D.getDeclSpec().isInlineSpecified()) 17304 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17305 << getLangOpts().CPlusPlus17; 17306 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17307 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17308 diag::err_invalid_thread) 17309 << DeclSpec::getSpecifierName(TSCS); 17310 17311 // Check to see if this name was declared as a member previously 17312 NamedDecl *PrevDecl = nullptr; 17313 LookupResult Previous(*this, II, Loc, LookupMemberName, 17314 ForVisibleRedeclaration); 17315 LookupName(Previous, S); 17316 switch (Previous.getResultKind()) { 17317 case LookupResult::Found: 17318 case LookupResult::FoundUnresolvedValue: 17319 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17320 break; 17321 17322 case LookupResult::FoundOverloaded: 17323 PrevDecl = Previous.getRepresentativeDecl(); 17324 break; 17325 17326 case LookupResult::NotFound: 17327 case LookupResult::NotFoundInCurrentInstantiation: 17328 case LookupResult::Ambiguous: 17329 break; 17330 } 17331 17332 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17333 // Maybe we will complain about the shadowed template parameter. 17334 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17335 // Just pretend that we didn't see the previous declaration. 17336 PrevDecl = nullptr; 17337 } 17338 17339 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17340 PrevDecl = nullptr; 17341 17342 SourceLocation TSSL = D.getBeginLoc(); 17343 MSPropertyDecl *NewPD = 17344 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17345 MSPropertyAttr.getPropertyDataGetter(), 17346 MSPropertyAttr.getPropertyDataSetter()); 17347 ProcessDeclAttributes(TUScope, NewPD, D); 17348 NewPD->setAccess(AS); 17349 17350 if (NewPD->isInvalidDecl()) 17351 Record->setInvalidDecl(); 17352 17353 if (D.getDeclSpec().isModulePrivateSpecified()) 17354 NewPD->setModulePrivate(); 17355 17356 if (NewPD->isInvalidDecl() && PrevDecl) { 17357 // Don't introduce NewFD into scope; there's already something 17358 // with the same name in the same scope. 17359 } else if (II) { 17360 PushOnScopeChains(NewPD, S); 17361 } else 17362 Record->addDecl(NewPD); 17363 17364 return NewPD; 17365 } 17366