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/PartialDiagnostic.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Lex/LiteralSupport.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/CXXFieldCollector.h" 32 #include "clang/Sema/DeclSpec.h" 33 #include "clang/Sema/Initialization.h" 34 #include "clang/Sema/Lookup.h" 35 #include "clang/Sema/ParsedTemplate.h" 36 #include "clang/Sema/Scope.h" 37 #include "clang/Sema/ScopeInfo.h" 38 #include "clang/Sema/SemaInternal.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include "llvm/ADT/StringExtras.h" 43 #include <map> 44 #include <set> 45 46 using namespace clang; 47 48 //===----------------------------------------------------------------------===// 49 // CheckDefaultArgumentVisitor 50 //===----------------------------------------------------------------------===// 51 52 namespace { 53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 54 /// the default argument of a parameter to determine whether it 55 /// contains any ill-formed subexpressions. For example, this will 56 /// diagnose the use of local variables or parameters within the 57 /// default argument expression. 58 class CheckDefaultArgumentVisitor 59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 60 Expr *DefaultArg; 61 Sema *S; 62 63 public: 64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 65 : DefaultArg(defarg), S(s) {} 66 67 bool VisitExpr(Expr *Node); 68 bool VisitDeclRefExpr(DeclRefExpr *DRE); 69 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 70 bool VisitLambdaExpr(LambdaExpr *Lambda); 71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 72 }; 73 74 /// VisitExpr - Visit all of the children of this expression. 75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 76 bool IsInvalid = false; 77 for (Stmt *SubStmt : Node->children()) 78 IsInvalid |= Visit(SubStmt); 79 return IsInvalid; 80 } 81 82 /// VisitDeclRefExpr - Visit a reference to a declaration, to 83 /// determine whether this declaration can be used in the default 84 /// argument expression. 85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 86 NamedDecl *Decl = DRE->getDecl(); 87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 88 // C++ [dcl.fct.default]p9 89 // Default arguments are evaluated each time the function is 90 // called. The order of evaluation of function arguments is 91 // unspecified. Consequently, parameters of a function shall not 92 // be used in default argument expressions, even if they are not 93 // evaluated. Parameters of a function declared before a default 94 // argument expression are in scope and can hide namespace and 95 // class member names. 96 return S->Diag(DRE->getBeginLoc(), 97 diag::err_param_default_argument_references_param) 98 << Param->getDeclName() << DefaultArg->getSourceRange(); 99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 100 // C++ [dcl.fct.default]p7 101 // Local variables shall not be used in default argument 102 // expressions. 103 if (VDecl->isLocalVarDecl()) 104 return S->Diag(DRE->getBeginLoc(), 105 diag::err_param_default_argument_references_local) 106 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 107 } 108 109 return false; 110 } 111 112 /// VisitCXXThisExpr - Visit a C++ "this" expression. 113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 114 // C++ [dcl.fct.default]p8: 115 // The keyword this shall not be used in a default argument of a 116 // member function. 117 return S->Diag(ThisE->getBeginLoc(), 118 diag::err_param_default_argument_references_this) 119 << ThisE->getSourceRange(); 120 } 121 122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 123 bool Invalid = false; 124 for (PseudoObjectExpr::semantics_iterator 125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 126 Expr *E = *i; 127 128 // Look through bindings. 129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 130 E = OVE->getSourceExpr(); 131 assert(E && "pseudo-object binding without source expression?"); 132 } 133 134 Invalid |= Visit(E); 135 } 136 return Invalid; 137 } 138 139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 140 // C++11 [expr.lambda.prim]p13: 141 // A lambda-expression appearing in a default argument shall not 142 // implicitly or explicitly capture any entity. 143 if (Lambda->capture_begin() == Lambda->capture_end()) 144 return false; 145 146 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If we have a throw-all spec at this point, ignore the function. 166 if (ComputedEST == EST_None) 167 return; 168 169 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 170 EST = EST_BasicNoexcept; 171 172 switch (EST) { 173 case EST_Unparsed: 174 case EST_Uninstantiated: 175 case EST_Unevaluated: 176 llvm_unreachable("should not see unresolved exception specs here"); 177 178 // If this function can throw any exceptions, make a note of that. 179 case EST_MSAny: 180 case EST_None: 181 // FIXME: Whichever we see last of MSAny and None determines our result. 182 // We should make a consistent, order-independent choice here. 183 ClearExceptions(); 184 ComputedEST = EST; 185 return; 186 case EST_NoexceptFalse: 187 ClearExceptions(); 188 ComputedEST = EST_None; 189 return; 190 // FIXME: If the call to this decl is using any of its default arguments, we 191 // need to search them for potentially-throwing calls. 192 // If this function has a basic noexcept, it doesn't affect the outcome. 193 case EST_BasicNoexcept: 194 case EST_NoexceptTrue: 195 case EST_NoThrow: 196 return; 197 // If we're still at noexcept(true) and there's a throw() callee, 198 // change to that specification. 199 case EST_DynamicNone: 200 if (ComputedEST == EST_BasicNoexcept) 201 ComputedEST = EST_DynamicNone; 202 return; 203 case EST_DependentNoexcept: 204 llvm_unreachable( 205 "should not generate implicit declarations for dependent cases"); 206 case EST_Dynamic: 207 break; 208 } 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // C++11 [dcl.fct.default]p3 321 // A default argument expression [...] shall not be specified for a 322 // parameter pack. 323 if (Param->isParameterPack()) { 324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 325 << DefaultArg->getSourceRange(); 326 return; 327 } 328 329 // Check that the default argument is well-formed 330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 331 if (DefaultArgChecker.Visit(DefaultArg)) { 332 Param->setInvalidDecl(); 333 return; 334 } 335 336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 337 } 338 339 /// ActOnParamUnparsedDefaultArgument - We've seen a default 340 /// argument for a function parameter, but we can't parse it yet 341 /// because we're inside a class definition. Note that this default 342 /// argument will be parsed later. 343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 344 SourceLocation EqualLoc, 345 SourceLocation ArgLoc) { 346 if (!param) 347 return; 348 349 ParmVarDecl *Param = cast<ParmVarDecl>(param); 350 Param->setUnparsedDefaultArg(); 351 UnparsedDefaultArgLocs[Param] = ArgLoc; 352 } 353 354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 355 /// the default argument for the parameter param failed. 356 void Sema::ActOnParamDefaultArgumentError(Decl *param, 357 SourceLocation EqualLoc) { 358 if (!param) 359 return; 360 361 ParmVarDecl *Param = cast<ParmVarDecl>(param); 362 Param->setInvalidDecl(); 363 UnparsedDefaultArgLocs.erase(Param); 364 Param->setDefaultArg(new(Context) 365 OpaqueValueExpr(EqualLoc, 366 Param->getType().getNonReferenceType(), 367 VK_RValue)); 368 } 369 370 /// CheckExtraCXXDefaultArguments - Check for any extra default 371 /// arguments in the declarator, which is not a function declaration 372 /// or definition and therefore is not permitted to have default 373 /// arguments. This routine should be invoked for every declarator 374 /// that is not a function declaration or definition. 375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 376 // C++ [dcl.fct.default]p3 377 // A default argument expression shall be specified only in the 378 // parameter-declaration-clause of a function declaration or in a 379 // template-parameter (14.1). It shall not be specified for a 380 // parameter pack. If it is specified in a 381 // parameter-declaration-clause, it shall not occur within a 382 // declarator or abstract-declarator of a parameter-declaration. 383 bool MightBeFunction = D.isFunctionDeclarationContext(); 384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 385 DeclaratorChunk &chunk = D.getTypeObject(i); 386 if (chunk.Kind == DeclaratorChunk::Function) { 387 if (MightBeFunction) { 388 // This is a function declaration. It can have default arguments, but 389 // keep looking in case its return type is a function type with default 390 // arguments. 391 MightBeFunction = false; 392 continue; 393 } 394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 395 ++argIdx) { 396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 397 if (Param->hasUnparsedDefaultArg()) { 398 std::unique_ptr<CachedTokens> Toks = 399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 400 SourceRange SR; 401 if (Toks->size() > 1) 402 SR = SourceRange((*Toks)[1].getLocation(), 403 Toks->back().getLocation()); 404 else 405 SR = UnparsedDefaultArgLocs[Param]; 406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 407 << SR; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficient, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found the right previous declaration. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter unless the new 551 // function is a friend declaration in a template class. In the latter 552 // case the default arguments will be inherited when the friend 553 // declaration will be instantiated. 554 if (New->getFriendObjectKind() == Decl::FOK_None || 555 !New->getLexicalDeclContext()->isDependentContext()) { 556 // It's important to use getInit() here; getDefaultArg() 557 // strips off any top-level ExprWithCleanups. 558 NewParam->setHasInheritedDefaultArg(); 559 if (OldParam->hasUnparsedDefaultArg()) 560 NewParam->setUnparsedDefaultArg(); 561 else if (OldParam->hasUninstantiatedDefaultArg()) 562 NewParam->setUninstantiatedDefaultArg( 563 OldParam->getUninstantiatedDefaultArg()); 564 else 565 NewParam->setDefaultArg(OldParam->getInit()); 566 } 567 } else if (NewParamHasDfl) { 568 if (New->getDescribedFunctionTemplate()) { 569 // Paragraph 4, quoted above, only applies to non-template functions. 570 Diag(NewParam->getLocation(), 571 diag::err_param_default_argument_template_redecl) 572 << NewParam->getDefaultArgRange(); 573 Diag(PrevForDefaultArgs->getLocation(), 574 diag::note_template_prev_declaration) 575 << false; 576 } else if (New->getTemplateSpecializationKind() 577 != TSK_ImplicitInstantiation && 578 New->getTemplateSpecializationKind() != TSK_Undeclared) { 579 // C++ [temp.expr.spec]p21: 580 // Default function arguments shall not be specified in a declaration 581 // or a definition for one of the following explicit specializations: 582 // - the explicit specialization of a function template; 583 // - the explicit specialization of a member function template; 584 // - the explicit specialization of a member function of a class 585 // template where the class template specialization to which the 586 // member function specialization belongs is implicitly 587 // instantiated. 588 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 589 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 590 << New->getDeclName() 591 << NewParam->getDefaultArgRange(); 592 } else if (New->getDeclContext()->isDependentContext()) { 593 // C++ [dcl.fct.default]p6 (DR217): 594 // Default arguments for a member function of a class template shall 595 // be specified on the initial declaration of the member function 596 // within the class template. 597 // 598 // Reading the tea leaves a bit in DR217 and its reference to DR205 599 // leads me to the conclusion that one cannot add default function 600 // arguments for an out-of-line definition of a member function of a 601 // dependent type. 602 int WhichKind = 2; 603 if (CXXRecordDecl *Record 604 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 605 if (Record->getDescribedClassTemplate()) 606 WhichKind = 0; 607 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 608 WhichKind = 1; 609 else 610 WhichKind = 2; 611 } 612 613 Diag(NewParam->getLocation(), 614 diag::err_param_default_argument_member_template_redecl) 615 << WhichKind 616 << NewParam->getDefaultArgRange(); 617 } 618 } 619 } 620 621 // DR1344: If a default argument is added outside a class definition and that 622 // default argument makes the function a special member function, the program 623 // is ill-formed. This can only happen for constructors. 624 if (isa<CXXConstructorDecl>(New) && 625 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 626 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 627 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 628 if (NewSM != OldSM) { 629 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 630 assert(NewParam->hasDefaultArg()); 631 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 632 << NewParam->getDefaultArgRange() << NewSM; 633 Diag(Old->getLocation(), diag::note_previous_declaration); 634 } 635 } 636 637 const FunctionDecl *Def; 638 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 639 // template has a constexpr specifier then all its declarations shall 640 // contain the constexpr specifier. 641 if (New->getConstexprKind() != Old->getConstexprKind()) { 642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 643 << New << New->getConstexprKind() << Old->getConstexprKind(); 644 Diag(Old->getLocation(), diag::note_previous_declaration); 645 Invalid = true; 646 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 647 Old->isDefined(Def) && 648 // If a friend function is inlined but does not have 'inline' 649 // specifier, it is a definition. Do not report attribute conflict 650 // in this case, redefinition will be diagnosed later. 651 (New->isInlineSpecified() || 652 New->getFriendObjectKind() == Decl::FOK_None)) { 653 // C++11 [dcl.fcn.spec]p4: 654 // If the definition of a function appears in a translation unit before its 655 // first declaration as inline, the program is ill-formed. 656 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 657 Diag(Def->getLocation(), diag::note_previous_definition); 658 Invalid = true; 659 } 660 661 // C++17 [temp.deduct.guide]p3: 662 // Two deduction guide declarations in the same translation unit 663 // for the same class template shall not have equivalent 664 // parameter-declaration-clauses. 665 if (isa<CXXDeductionGuideDecl>(New) && 666 !New->isFunctionTemplateSpecialization()) { 667 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 668 Diag(Old->getLocation(), diag::note_previous_declaration); 669 } 670 671 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 672 // argument expression, that declaration shall be a definition and shall be 673 // the only declaration of the function or function template in the 674 // translation unit. 675 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 676 functionDeclHasDefaultArgument(Old)) { 677 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 678 Diag(Old->getLocation(), diag::note_previous_declaration); 679 Invalid = true; 680 } 681 682 return Invalid; 683 } 684 685 NamedDecl * 686 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 687 MultiTemplateParamsArg TemplateParamLists) { 688 assert(D.isDecompositionDeclarator()); 689 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 690 691 // The syntax only allows a decomposition declarator as a simple-declaration, 692 // a for-range-declaration, or a condition in Clang, but we parse it in more 693 // cases than that. 694 if (!D.mayHaveDecompositionDeclarator()) { 695 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 696 << Decomp.getSourceRange(); 697 return nullptr; 698 } 699 700 if (!TemplateParamLists.empty()) { 701 // FIXME: There's no rule against this, but there are also no rules that 702 // would actually make it usable, so we reject it for now. 703 Diag(TemplateParamLists.front()->getTemplateLoc(), 704 diag::err_decomp_decl_template); 705 return nullptr; 706 } 707 708 Diag(Decomp.getLSquareLoc(), 709 !getLangOpts().CPlusPlus17 710 ? diag::ext_decomp_decl 711 : D.getContext() == DeclaratorContext::ConditionContext 712 ? diag::ext_decomp_decl_cond 713 : diag::warn_cxx14_compat_decomp_decl) 714 << Decomp.getSourceRange(); 715 716 // The semantic context is always just the current context. 717 DeclContext *const DC = CurContext; 718 719 // C++17 [dcl.dcl]/8: 720 // The decl-specifier-seq shall contain only the type-specifier auto 721 // and cv-qualifiers. 722 // C++2a [dcl.dcl]/8: 723 // If decl-specifier-seq contains any decl-specifier other than static, 724 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 725 auto &DS = D.getDeclSpec(); 726 { 727 SmallVector<StringRef, 8> BadSpecifiers; 728 SmallVector<SourceLocation, 8> BadSpecifierLocs; 729 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 730 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 731 if (auto SCS = DS.getStorageClassSpec()) { 732 if (SCS == DeclSpec::SCS_static) { 733 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 734 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 735 } else { 736 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 737 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 738 } 739 } 740 if (auto TSCS = DS.getThreadStorageClassSpec()) { 741 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 742 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 743 } 744 if (DS.hasConstexprSpecifier()) { 745 BadSpecifiers.push_back( 746 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 747 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 748 } 749 if (DS.isInlineSpecified()) { 750 BadSpecifiers.push_back("inline"); 751 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 752 } 753 if (!BadSpecifiers.empty()) { 754 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 755 Err << (int)BadSpecifiers.size() 756 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 757 // Don't add FixItHints to remove the specifiers; we do still respect 758 // them when building the underlying variable. 759 for (auto Loc : BadSpecifierLocs) 760 Err << SourceRange(Loc, Loc); 761 } else if (!CPlusPlus20Specifiers.empty()) { 762 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 763 getLangOpts().CPlusPlus2a 764 ? diag::warn_cxx17_compat_decomp_decl_spec 765 : diag::ext_decomp_decl_spec); 766 Warn << (int)CPlusPlus20Specifiers.size() 767 << llvm::join(CPlusPlus20Specifiers.begin(), 768 CPlusPlus20Specifiers.end(), " "); 769 for (auto Loc : CPlusPlus20SpecifierLocs) 770 Warn << SourceRange(Loc, Loc); 771 } 772 // We can't recover from it being declared as a typedef. 773 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 774 return nullptr; 775 } 776 777 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 778 QualType R = TInfo->getType(); 779 780 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 781 UPPC_DeclarationType)) 782 D.setInvalidType(); 783 784 // The syntax only allows a single ref-qualifier prior to the decomposition 785 // declarator. No other declarator chunks are permitted. Also check the type 786 // specifier here. 787 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 788 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 789 (D.getNumTypeObjects() == 1 && 790 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 791 Diag(Decomp.getLSquareLoc(), 792 (D.hasGroupingParens() || 793 (D.getNumTypeObjects() && 794 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 795 ? diag::err_decomp_decl_parens 796 : diag::err_decomp_decl_type) 797 << R; 798 799 // In most cases, there's no actual problem with an explicitly-specified 800 // type, but a function type won't work here, and ActOnVariableDeclarator 801 // shouldn't be called for such a type. 802 if (R->isFunctionType()) 803 D.setInvalidType(); 804 } 805 806 // Build the BindingDecls. 807 SmallVector<BindingDecl*, 8> Bindings; 808 809 // Build the BindingDecls. 810 for (auto &B : D.getDecompositionDeclarator().bindings()) { 811 // Check for name conflicts. 812 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 813 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 814 ForVisibleRedeclaration); 815 LookupName(Previous, S, 816 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 817 818 // It's not permitted to shadow a template parameter name. 819 if (Previous.isSingleResult() && 820 Previous.getFoundDecl()->isTemplateParameter()) { 821 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 822 Previous.getFoundDecl()); 823 Previous.clear(); 824 } 825 826 bool ConsiderLinkage = DC->isFunctionOrMethod() && 827 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 828 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 829 /*AllowInlineNamespace*/false); 830 if (!Previous.empty()) { 831 auto *Old = Previous.getRepresentativeDecl(); 832 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 833 Diag(Old->getLocation(), diag::note_previous_definition); 834 } 835 836 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 837 PushOnScopeChains(BD, S, true); 838 Bindings.push_back(BD); 839 ParsingInitForAutoVars.insert(BD); 840 } 841 842 // There are no prior lookup results for the variable itself, because it 843 // is unnamed. 844 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 845 Decomp.getLSquareLoc()); 846 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 847 ForVisibleRedeclaration); 848 849 // Build the variable that holds the non-decomposed object. 850 bool AddToScope = true; 851 NamedDecl *New = 852 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 853 MultiTemplateParamsArg(), AddToScope, Bindings); 854 if (AddToScope) { 855 S->AddDecl(New); 856 CurContext->addHiddenDecl(New); 857 } 858 859 if (isInOpenMPDeclareTargetContext()) 860 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 861 862 return New; 863 } 864 865 static bool checkSimpleDecomposition( 866 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 867 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 868 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 869 if ((int64_t)Bindings.size() != NumElems) { 870 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 871 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 872 << (NumElems < Bindings.size()); 873 return true; 874 } 875 876 unsigned I = 0; 877 for (auto *B : Bindings) { 878 SourceLocation Loc = B->getLocation(); 879 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 880 if (E.isInvalid()) 881 return true; 882 E = GetInit(Loc, E.get(), I++); 883 if (E.isInvalid()) 884 return true; 885 B->setBinding(ElemType, E.get()); 886 } 887 888 return false; 889 } 890 891 static bool checkArrayLikeDecomposition(Sema &S, 892 ArrayRef<BindingDecl *> Bindings, 893 ValueDecl *Src, QualType DecompType, 894 const llvm::APSInt &NumElems, 895 QualType ElemType) { 896 return checkSimpleDecomposition( 897 S, Bindings, Src, DecompType, NumElems, ElemType, 898 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 899 ExprResult E = S.ActOnIntegerConstant(Loc, I); 900 if (E.isInvalid()) 901 return ExprError(); 902 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 903 }); 904 } 905 906 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 907 ValueDecl *Src, QualType DecompType, 908 const ConstantArrayType *CAT) { 909 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 910 llvm::APSInt(CAT->getSize()), 911 CAT->getElementType()); 912 } 913 914 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 915 ValueDecl *Src, QualType DecompType, 916 const VectorType *VT) { 917 return checkArrayLikeDecomposition( 918 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 919 S.Context.getQualifiedType(VT->getElementType(), 920 DecompType.getQualifiers())); 921 } 922 923 static bool checkComplexDecomposition(Sema &S, 924 ArrayRef<BindingDecl *> Bindings, 925 ValueDecl *Src, QualType DecompType, 926 const ComplexType *CT) { 927 return checkSimpleDecomposition( 928 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 929 S.Context.getQualifiedType(CT->getElementType(), 930 DecompType.getQualifiers()), 931 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 932 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 933 }); 934 } 935 936 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 937 TemplateArgumentListInfo &Args) { 938 SmallString<128> SS; 939 llvm::raw_svector_ostream OS(SS); 940 bool First = true; 941 for (auto &Arg : Args.arguments()) { 942 if (!First) 943 OS << ", "; 944 Arg.getArgument().print(PrintingPolicy, OS); 945 First = false; 946 } 947 return OS.str(); 948 } 949 950 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 951 SourceLocation Loc, StringRef Trait, 952 TemplateArgumentListInfo &Args, 953 unsigned DiagID) { 954 auto DiagnoseMissing = [&] { 955 if (DiagID) 956 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 957 Args); 958 return true; 959 }; 960 961 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 962 NamespaceDecl *Std = S.getStdNamespace(); 963 if (!Std) 964 return DiagnoseMissing(); 965 966 // Look up the trait itself, within namespace std. We can diagnose various 967 // problems with this lookup even if we've been asked to not diagnose a 968 // missing specialization, because this can only fail if the user has been 969 // declaring their own names in namespace std or we don't support the 970 // standard library implementation in use. 971 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 972 Loc, Sema::LookupOrdinaryName); 973 if (!S.LookupQualifiedName(Result, Std)) 974 return DiagnoseMissing(); 975 if (Result.isAmbiguous()) 976 return true; 977 978 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 979 if (!TraitTD) { 980 Result.suppressDiagnostics(); 981 NamedDecl *Found = *Result.begin(); 982 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 983 S.Diag(Found->getLocation(), diag::note_declared_at); 984 return true; 985 } 986 987 // Build the template-id. 988 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 989 if (TraitTy.isNull()) 990 return true; 991 if (!S.isCompleteType(Loc, TraitTy)) { 992 if (DiagID) 993 S.RequireCompleteType( 994 Loc, TraitTy, DiagID, 995 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 996 return true; 997 } 998 999 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1000 assert(RD && "specialization of class template is not a class?"); 1001 1002 // Look up the member of the trait type. 1003 S.LookupQualifiedName(TraitMemberLookup, RD); 1004 return TraitMemberLookup.isAmbiguous(); 1005 } 1006 1007 static TemplateArgumentLoc 1008 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1009 uint64_t I) { 1010 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1011 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1012 } 1013 1014 static TemplateArgumentLoc 1015 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1016 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1017 } 1018 1019 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1020 1021 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1022 llvm::APSInt &Size) { 1023 EnterExpressionEvaluationContext ContextRAII( 1024 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1025 1026 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1027 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1028 1029 // Form template argument list for tuple_size<T>. 1030 TemplateArgumentListInfo Args(Loc, Loc); 1031 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1032 1033 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1034 // it's not tuple-like. 1035 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1036 R.empty()) 1037 return IsTupleLike::NotTupleLike; 1038 1039 // If we get this far, we've committed to the tuple interpretation, but 1040 // we can still fail if there actually isn't a usable ::value. 1041 1042 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1043 LookupResult &R; 1044 TemplateArgumentListInfo &Args; 1045 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1046 : R(R), Args(Args) {} 1047 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1048 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1049 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1050 } 1051 } Diagnoser(R, Args); 1052 1053 ExprResult E = 1054 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1055 if (E.isInvalid()) 1056 return IsTupleLike::Error; 1057 1058 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1059 if (E.isInvalid()) 1060 return IsTupleLike::Error; 1061 1062 return IsTupleLike::TupleLike; 1063 } 1064 1065 /// \return std::tuple_element<I, T>::type. 1066 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1067 unsigned I, QualType T) { 1068 // Form template argument list for tuple_element<I, T>. 1069 TemplateArgumentListInfo Args(Loc, Loc); 1070 Args.addArgument( 1071 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1072 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1073 1074 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1075 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1076 if (lookupStdTypeTraitMember( 1077 S, R, Loc, "tuple_element", Args, 1078 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1079 return QualType(); 1080 1081 auto *TD = R.getAsSingle<TypeDecl>(); 1082 if (!TD) { 1083 R.suppressDiagnostics(); 1084 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1085 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1086 if (!R.empty()) 1087 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1088 return QualType(); 1089 } 1090 1091 return S.Context.getTypeDeclType(TD); 1092 } 1093 1094 namespace { 1095 struct BindingDiagnosticTrap { 1096 Sema &S; 1097 DiagnosticErrorTrap Trap; 1098 BindingDecl *BD; 1099 1100 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1101 : S(S), Trap(S.Diags), BD(BD) {} 1102 ~BindingDiagnosticTrap() { 1103 if (Trap.hasErrorOccurred()) 1104 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1105 } 1106 }; 1107 } 1108 1109 static bool checkTupleLikeDecomposition(Sema &S, 1110 ArrayRef<BindingDecl *> Bindings, 1111 VarDecl *Src, QualType DecompType, 1112 const llvm::APSInt &TupleSize) { 1113 if ((int64_t)Bindings.size() != TupleSize) { 1114 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1115 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1116 << (TupleSize < Bindings.size()); 1117 return true; 1118 } 1119 1120 if (Bindings.empty()) 1121 return false; 1122 1123 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1124 1125 // [dcl.decomp]p3: 1126 // The unqualified-id get is looked up in the scope of E by class member 1127 // access lookup ... 1128 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1129 bool UseMemberGet = false; 1130 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1131 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1132 S.LookupQualifiedName(MemberGet, RD); 1133 if (MemberGet.isAmbiguous()) 1134 return true; 1135 // ... and if that finds at least one declaration that is a function 1136 // template whose first template parameter is a non-type parameter ... 1137 for (NamedDecl *D : MemberGet) { 1138 if (FunctionTemplateDecl *FTD = 1139 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1140 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1141 if (TPL->size() != 0 && 1142 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1143 // ... the initializer is e.get<i>(). 1144 UseMemberGet = true; 1145 break; 1146 } 1147 } 1148 } 1149 } 1150 1151 unsigned I = 0; 1152 for (auto *B : Bindings) { 1153 BindingDiagnosticTrap Trap(S, B); 1154 SourceLocation Loc = B->getLocation(); 1155 1156 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1157 if (E.isInvalid()) 1158 return true; 1159 1160 // e is an lvalue if the type of the entity is an lvalue reference and 1161 // an xvalue otherwise 1162 if (!Src->getType()->isLValueReferenceType()) 1163 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1164 E.get(), nullptr, VK_XValue); 1165 1166 TemplateArgumentListInfo Args(Loc, Loc); 1167 Args.addArgument( 1168 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1169 1170 if (UseMemberGet) { 1171 // if [lookup of member get] finds at least one declaration, the 1172 // initializer is e.get<i-1>(). 1173 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1174 CXXScopeSpec(), SourceLocation(), nullptr, 1175 MemberGet, &Args, nullptr); 1176 if (E.isInvalid()) 1177 return true; 1178 1179 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1180 } else { 1181 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1182 // in the associated namespaces. 1183 Expr *Get = UnresolvedLookupExpr::Create( 1184 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1185 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1186 UnresolvedSetIterator(), UnresolvedSetIterator()); 1187 1188 Expr *Arg = E.get(); 1189 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1190 } 1191 if (E.isInvalid()) 1192 return true; 1193 Expr *Init = E.get(); 1194 1195 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1196 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1197 if (T.isNull()) 1198 return true; 1199 1200 // each vi is a variable of type "reference to T" initialized with the 1201 // initializer, where the reference is an lvalue reference if the 1202 // initializer is an lvalue and an rvalue reference otherwise 1203 QualType RefType = 1204 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1205 if (RefType.isNull()) 1206 return true; 1207 auto *RefVD = VarDecl::Create( 1208 S.Context, Src->getDeclContext(), Loc, Loc, 1209 B->getDeclName().getAsIdentifierInfo(), RefType, 1210 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1211 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1212 RefVD->setTSCSpec(Src->getTSCSpec()); 1213 RefVD->setImplicit(); 1214 if (Src->isInlineSpecified()) 1215 RefVD->setInlineSpecified(); 1216 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1217 1218 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1219 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1220 InitializationSequence Seq(S, Entity, Kind, Init); 1221 E = Seq.Perform(S, Entity, Kind, Init); 1222 if (E.isInvalid()) 1223 return true; 1224 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1225 if (E.isInvalid()) 1226 return true; 1227 RefVD->setInit(E.get()); 1228 RefVD->checkInitIsICE(); 1229 1230 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1231 DeclarationNameInfo(B->getDeclName(), Loc), 1232 RefVD); 1233 if (E.isInvalid()) 1234 return true; 1235 1236 B->setBinding(T, E.get()); 1237 I++; 1238 } 1239 1240 return false; 1241 } 1242 1243 /// Find the base class to decompose in a built-in decomposition of a class type. 1244 /// This base class search is, unfortunately, not quite like any other that we 1245 /// perform anywhere else in C++. 1246 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1247 const CXXRecordDecl *RD, 1248 CXXCastPath &BasePath) { 1249 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1250 CXXBasePath &Path) { 1251 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1252 }; 1253 1254 const CXXRecordDecl *ClassWithFields = nullptr; 1255 AccessSpecifier AS = AS_public; 1256 if (RD->hasDirectFields()) 1257 // [dcl.decomp]p4: 1258 // Otherwise, all of E's non-static data members shall be public direct 1259 // members of E ... 1260 ClassWithFields = RD; 1261 else { 1262 // ... or of ... 1263 CXXBasePaths Paths; 1264 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1265 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1266 // If no classes have fields, just decompose RD itself. (This will work 1267 // if and only if zero bindings were provided.) 1268 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1269 } 1270 1271 CXXBasePath *BestPath = nullptr; 1272 for (auto &P : Paths) { 1273 if (!BestPath) 1274 BestPath = &P; 1275 else if (!S.Context.hasSameType(P.back().Base->getType(), 1276 BestPath->back().Base->getType())) { 1277 // ... the same ... 1278 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1279 << false << RD << BestPath->back().Base->getType() 1280 << P.back().Base->getType(); 1281 return DeclAccessPair(); 1282 } else if (P.Access < BestPath->Access) { 1283 BestPath = &P; 1284 } 1285 } 1286 1287 // ... unambiguous ... 1288 QualType BaseType = BestPath->back().Base->getType(); 1289 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1290 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1291 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1292 return DeclAccessPair(); 1293 } 1294 1295 // ... [accessible, implied by other rules] base class of E. 1296 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1297 *BestPath, diag::err_decomp_decl_inaccessible_base); 1298 AS = BestPath->Access; 1299 1300 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1301 S.BuildBasePathArray(Paths, BasePath); 1302 } 1303 1304 // The above search did not check whether the selected class itself has base 1305 // classes with fields, so check that now. 1306 CXXBasePaths Paths; 1307 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1308 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1309 << (ClassWithFields == RD) << RD << ClassWithFields 1310 << Paths.front().back().Base->getType(); 1311 return DeclAccessPair(); 1312 } 1313 1314 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1315 } 1316 1317 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1318 ValueDecl *Src, QualType DecompType, 1319 const CXXRecordDecl *OrigRD) { 1320 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1321 diag::err_incomplete_type)) 1322 return true; 1323 1324 CXXCastPath BasePath; 1325 DeclAccessPair BasePair = 1326 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1327 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1328 if (!RD) 1329 return true; 1330 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1331 DecompType.getQualifiers()); 1332 1333 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1334 unsigned NumFields = 1335 std::count_if(RD->field_begin(), RD->field_end(), 1336 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1337 assert(Bindings.size() != NumFields); 1338 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1339 << DecompType << (unsigned)Bindings.size() << NumFields 1340 << (NumFields < Bindings.size()); 1341 return true; 1342 }; 1343 1344 // all of E's non-static data members shall be [...] well-formed 1345 // when named as e.name in the context of the structured binding, 1346 // E shall not have an anonymous union member, ... 1347 unsigned I = 0; 1348 for (auto *FD : RD->fields()) { 1349 if (FD->isUnnamedBitfield()) 1350 continue; 1351 1352 if (FD->isAnonymousStructOrUnion()) { 1353 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1354 << DecompType << FD->getType()->isUnionType(); 1355 S.Diag(FD->getLocation(), diag::note_declared_at); 1356 return true; 1357 } 1358 1359 // We have a real field to bind. 1360 if (I >= Bindings.size()) 1361 return DiagnoseBadNumberOfBindings(); 1362 auto *B = Bindings[I++]; 1363 SourceLocation Loc = B->getLocation(); 1364 1365 // The field must be accessible in the context of the structured binding. 1366 // We already checked that the base class is accessible. 1367 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1368 // const_cast here. 1369 S.CheckStructuredBindingMemberAccess( 1370 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1371 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1372 BasePair.getAccess(), FD->getAccess()))); 1373 1374 // Initialize the binding to Src.FD. 1375 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1376 if (E.isInvalid()) 1377 return true; 1378 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1379 VK_LValue, &BasePath); 1380 if (E.isInvalid()) 1381 return true; 1382 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1383 CXXScopeSpec(), FD, 1384 DeclAccessPair::make(FD, FD->getAccess()), 1385 DeclarationNameInfo(FD->getDeclName(), Loc)); 1386 if (E.isInvalid()) 1387 return true; 1388 1389 // If the type of the member is T, the referenced type is cv T, where cv is 1390 // the cv-qualification of the decomposition expression. 1391 // 1392 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1393 // 'const' to the type of the field. 1394 Qualifiers Q = DecompType.getQualifiers(); 1395 if (FD->isMutable()) 1396 Q.removeConst(); 1397 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1398 } 1399 1400 if (I != Bindings.size()) 1401 return DiagnoseBadNumberOfBindings(); 1402 1403 return false; 1404 } 1405 1406 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1407 QualType DecompType = DD->getType(); 1408 1409 // If the type of the decomposition is dependent, then so is the type of 1410 // each binding. 1411 if (DecompType->isDependentType()) { 1412 for (auto *B : DD->bindings()) 1413 B->setType(Context.DependentTy); 1414 return; 1415 } 1416 1417 DecompType = DecompType.getNonReferenceType(); 1418 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1419 1420 // C++1z [dcl.decomp]/2: 1421 // If E is an array type [...] 1422 // As an extension, we also support decomposition of built-in complex and 1423 // vector types. 1424 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1425 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1426 DD->setInvalidDecl(); 1427 return; 1428 } 1429 if (auto *VT = DecompType->getAs<VectorType>()) { 1430 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1431 DD->setInvalidDecl(); 1432 return; 1433 } 1434 if (auto *CT = DecompType->getAs<ComplexType>()) { 1435 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1436 DD->setInvalidDecl(); 1437 return; 1438 } 1439 1440 // C++1z [dcl.decomp]/3: 1441 // if the expression std::tuple_size<E>::value is a well-formed integral 1442 // constant expression, [...] 1443 llvm::APSInt TupleSize(32); 1444 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1445 case IsTupleLike::Error: 1446 DD->setInvalidDecl(); 1447 return; 1448 1449 case IsTupleLike::TupleLike: 1450 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1451 DD->setInvalidDecl(); 1452 return; 1453 1454 case IsTupleLike::NotTupleLike: 1455 break; 1456 } 1457 1458 // C++1z [dcl.dcl]/8: 1459 // [E shall be of array or non-union class type] 1460 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1461 if (!RD || RD->isUnion()) { 1462 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1463 << DD << !RD << DecompType; 1464 DD->setInvalidDecl(); 1465 return; 1466 } 1467 1468 // C++1z [dcl.decomp]/4: 1469 // all of E's non-static data members shall be [...] direct members of 1470 // E or of the same unambiguous public base class of E, ... 1471 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1472 DD->setInvalidDecl(); 1473 } 1474 1475 /// Merge the exception specifications of two variable declarations. 1476 /// 1477 /// This is called when there's a redeclaration of a VarDecl. The function 1478 /// checks if the redeclaration might have an exception specification and 1479 /// validates compatibility and merges the specs if necessary. 1480 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1481 // Shortcut if exceptions are disabled. 1482 if (!getLangOpts().CXXExceptions) 1483 return; 1484 1485 assert(Context.hasSameType(New->getType(), Old->getType()) && 1486 "Should only be called if types are otherwise the same."); 1487 1488 QualType NewType = New->getType(); 1489 QualType OldType = Old->getType(); 1490 1491 // We're only interested in pointers and references to functions, as well 1492 // as pointers to member functions. 1493 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1494 NewType = R->getPointeeType(); 1495 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1496 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1497 NewType = P->getPointeeType(); 1498 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1499 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1500 NewType = M->getPointeeType(); 1501 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1502 } 1503 1504 if (!NewType->isFunctionProtoType()) 1505 return; 1506 1507 // There's lots of special cases for functions. For function pointers, system 1508 // libraries are hopefully not as broken so that we don't need these 1509 // workarounds. 1510 if (CheckEquivalentExceptionSpec( 1511 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1512 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1513 New->setInvalidDecl(); 1514 } 1515 } 1516 1517 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1518 /// function declaration are well-formed according to C++ 1519 /// [dcl.fct.default]. 1520 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1521 unsigned NumParams = FD->getNumParams(); 1522 unsigned p; 1523 1524 // Find first parameter with a default argument 1525 for (p = 0; p < NumParams; ++p) { 1526 ParmVarDecl *Param = FD->getParamDecl(p); 1527 if (Param->hasDefaultArg()) 1528 break; 1529 } 1530 1531 // C++11 [dcl.fct.default]p4: 1532 // In a given function declaration, each parameter subsequent to a parameter 1533 // with a default argument shall have a default argument supplied in this or 1534 // a previous declaration or shall be a function parameter pack. A default 1535 // argument shall not be redefined by a later declaration (not even to the 1536 // same value). 1537 unsigned LastMissingDefaultArg = 0; 1538 for (; p < NumParams; ++p) { 1539 ParmVarDecl *Param = FD->getParamDecl(p); 1540 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1541 if (Param->isInvalidDecl()) 1542 /* We already complained about this parameter. */; 1543 else if (Param->getIdentifier()) 1544 Diag(Param->getLocation(), 1545 diag::err_param_default_argument_missing_name) 1546 << Param->getIdentifier(); 1547 else 1548 Diag(Param->getLocation(), 1549 diag::err_param_default_argument_missing); 1550 1551 LastMissingDefaultArg = p; 1552 } 1553 } 1554 1555 if (LastMissingDefaultArg > 0) { 1556 // Some default arguments were missing. Clear out all of the 1557 // default arguments up to (and including) the last missing 1558 // default argument, so that we leave the function parameters 1559 // in a semantically valid state. 1560 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1561 ParmVarDecl *Param = FD->getParamDecl(p); 1562 if (Param->hasDefaultArg()) { 1563 Param->setDefaultArg(nullptr); 1564 } 1565 } 1566 } 1567 } 1568 1569 /// Check that the given type is a literal type. Issue a diagnostic if not, 1570 /// if Kind is Diagnose. 1571 /// \return \c true if a problem has been found (and optionally diagnosed). 1572 template <typename... Ts> 1573 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1574 SourceLocation Loc, QualType T, unsigned DiagID, 1575 Ts &&...DiagArgs) { 1576 if (T->isDependentType()) 1577 return false; 1578 1579 switch (Kind) { 1580 case Sema::CheckConstexprKind::Diagnose: 1581 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1582 std::forward<Ts>(DiagArgs)...); 1583 1584 case Sema::CheckConstexprKind::CheckValid: 1585 return !T->isLiteralType(SemaRef.Context); 1586 } 1587 1588 llvm_unreachable("unknown CheckConstexprKind"); 1589 } 1590 1591 // CheckConstexprParameterTypes - Check whether a function's parameter types 1592 // are all literal types. If so, return true. If not, produce a suitable 1593 // diagnostic and return false. 1594 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1595 const FunctionDecl *FD, 1596 Sema::CheckConstexprKind Kind) { 1597 unsigned ArgIndex = 0; 1598 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1599 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1600 e = FT->param_type_end(); 1601 i != e; ++i, ++ArgIndex) { 1602 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1603 SourceLocation ParamLoc = PD->getLocation(); 1604 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1605 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1606 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1607 FD->isConsteval())) 1608 return false; 1609 } 1610 return true; 1611 } 1612 1613 /// Get diagnostic %select index for tag kind for 1614 /// record diagnostic message. 1615 /// WARNING: Indexes apply to particular diagnostics only! 1616 /// 1617 /// \returns diagnostic %select index. 1618 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1619 switch (Tag) { 1620 case TTK_Struct: return 0; 1621 case TTK_Interface: return 1; 1622 case TTK_Class: return 2; 1623 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1624 } 1625 } 1626 1627 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1628 Stmt *Body, 1629 Sema::CheckConstexprKind Kind); 1630 1631 // Check whether a function declaration satisfies the requirements of a 1632 // constexpr function definition or a constexpr constructor definition. If so, 1633 // return true. If not, produce appropriate diagnostics (unless asked not to by 1634 // Kind) and return false. 1635 // 1636 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1637 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1638 CheckConstexprKind Kind) { 1639 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1640 if (MD && MD->isInstance()) { 1641 // C++11 [dcl.constexpr]p4: 1642 // The definition of a constexpr constructor shall satisfy the following 1643 // constraints: 1644 // - the class shall not have any virtual base classes; 1645 // 1646 // FIXME: This only applies to constructors, not arbitrary member 1647 // functions. 1648 const CXXRecordDecl *RD = MD->getParent(); 1649 if (RD->getNumVBases()) { 1650 if (Kind == CheckConstexprKind::CheckValid) 1651 return false; 1652 1653 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1654 << isa<CXXConstructorDecl>(NewFD) 1655 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1656 for (const auto &I : RD->vbases()) 1657 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1658 << I.getSourceRange(); 1659 return false; 1660 } 1661 } 1662 1663 if (!isa<CXXConstructorDecl>(NewFD)) { 1664 // C++11 [dcl.constexpr]p3: 1665 // The definition of a constexpr function shall satisfy the following 1666 // constraints: 1667 // - it shall not be virtual; (removed in C++20) 1668 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1669 if (Method && Method->isVirtual()) { 1670 if (getLangOpts().CPlusPlus2a) { 1671 if (Kind == CheckConstexprKind::Diagnose) 1672 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1673 } else { 1674 if (Kind == CheckConstexprKind::CheckValid) 1675 return false; 1676 1677 Method = Method->getCanonicalDecl(); 1678 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1679 1680 // If it's not obvious why this function is virtual, find an overridden 1681 // function which uses the 'virtual' keyword. 1682 const CXXMethodDecl *WrittenVirtual = Method; 1683 while (!WrittenVirtual->isVirtualAsWritten()) 1684 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1685 if (WrittenVirtual != Method) 1686 Diag(WrittenVirtual->getLocation(), 1687 diag::note_overridden_virtual_function); 1688 return false; 1689 } 1690 } 1691 1692 // - its return type shall be a literal type; 1693 QualType RT = NewFD->getReturnType(); 1694 if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT, 1695 diag::err_constexpr_non_literal_return, 1696 NewFD->isConsteval())) 1697 return false; 1698 } 1699 1700 // - each of its parameter types shall be a literal type; 1701 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1702 return false; 1703 1704 Stmt *Body = NewFD->getBody(); 1705 assert(Body && 1706 "CheckConstexprFunctionDefinition called on function with no body"); 1707 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1708 } 1709 1710 /// Check the given declaration statement is legal within a constexpr function 1711 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1712 /// 1713 /// \return true if the body is OK (maybe only as an extension), false if we 1714 /// have diagnosed a problem. 1715 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1716 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1717 Sema::CheckConstexprKind Kind) { 1718 // C++11 [dcl.constexpr]p3 and p4: 1719 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1720 // contain only 1721 for (const auto *DclIt : DS->decls()) { 1722 switch (DclIt->getKind()) { 1723 case Decl::StaticAssert: 1724 case Decl::Using: 1725 case Decl::UsingShadow: 1726 case Decl::UsingDirective: 1727 case Decl::UnresolvedUsingTypename: 1728 case Decl::UnresolvedUsingValue: 1729 // - static_assert-declarations 1730 // - using-declarations, 1731 // - using-directives, 1732 continue; 1733 1734 case Decl::Typedef: 1735 case Decl::TypeAlias: { 1736 // - typedef declarations and alias-declarations that do not define 1737 // classes or enumerations, 1738 const auto *TN = cast<TypedefNameDecl>(DclIt); 1739 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1740 // Don't allow variably-modified types in constexpr functions. 1741 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1742 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1743 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1744 << TL.getSourceRange() << TL.getType() 1745 << isa<CXXConstructorDecl>(Dcl); 1746 } 1747 return false; 1748 } 1749 continue; 1750 } 1751 1752 case Decl::Enum: 1753 case Decl::CXXRecord: 1754 // C++1y allows types to be defined, not just declared. 1755 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1756 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1757 SemaRef.Diag(DS->getBeginLoc(), 1758 SemaRef.getLangOpts().CPlusPlus14 1759 ? diag::warn_cxx11_compat_constexpr_type_definition 1760 : diag::ext_constexpr_type_definition) 1761 << isa<CXXConstructorDecl>(Dcl); 1762 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1763 return false; 1764 } 1765 } 1766 continue; 1767 1768 case Decl::EnumConstant: 1769 case Decl::IndirectField: 1770 case Decl::ParmVar: 1771 // These can only appear with other declarations which are banned in 1772 // C++11 and permitted in C++1y, so ignore them. 1773 continue; 1774 1775 case Decl::Var: 1776 case Decl::Decomposition: { 1777 // C++1y [dcl.constexpr]p3 allows anything except: 1778 // a definition of a variable of non-literal type or of static or 1779 // thread storage duration or for which no initialization is performed. 1780 const auto *VD = cast<VarDecl>(DclIt); 1781 if (VD->isThisDeclarationADefinition()) { 1782 if (VD->isStaticLocal()) { 1783 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1784 SemaRef.Diag(VD->getLocation(), 1785 diag::err_constexpr_local_var_static) 1786 << isa<CXXConstructorDecl>(Dcl) 1787 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1788 } 1789 return false; 1790 } 1791 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1792 diag::err_constexpr_local_var_non_literal_type, 1793 isa<CXXConstructorDecl>(Dcl))) 1794 return false; 1795 if (!VD->getType()->isDependentType() && 1796 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1797 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1798 SemaRef.Diag(VD->getLocation(), 1799 diag::err_constexpr_local_var_no_init) 1800 << isa<CXXConstructorDecl>(Dcl); 1801 } 1802 return false; 1803 } 1804 } 1805 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1806 SemaRef.Diag(VD->getLocation(), 1807 SemaRef.getLangOpts().CPlusPlus14 1808 ? diag::warn_cxx11_compat_constexpr_local_var 1809 : diag::ext_constexpr_local_var) 1810 << isa<CXXConstructorDecl>(Dcl); 1811 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1812 return false; 1813 } 1814 continue; 1815 } 1816 1817 case Decl::NamespaceAlias: 1818 case Decl::Function: 1819 // These are disallowed in C++11 and permitted in C++1y. Allow them 1820 // everywhere as an extension. 1821 if (!Cxx1yLoc.isValid()) 1822 Cxx1yLoc = DS->getBeginLoc(); 1823 continue; 1824 1825 default: 1826 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1827 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1828 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1829 } 1830 return false; 1831 } 1832 } 1833 1834 return true; 1835 } 1836 1837 /// Check that the given field is initialized within a constexpr constructor. 1838 /// 1839 /// \param Dcl The constexpr constructor being checked. 1840 /// \param Field The field being checked. This may be a member of an anonymous 1841 /// struct or union nested within the class being checked. 1842 /// \param Inits All declarations, including anonymous struct/union members and 1843 /// indirect members, for which any initialization was provided. 1844 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1845 /// multiple notes for different members to the same error. 1846 /// \param Kind Whether we're diagnosing a constructor as written or determining 1847 /// whether the formal requirements are satisfied. 1848 /// \return \c false if we're checking for validity and the constructor does 1849 /// not satisfy the requirements on a constexpr constructor. 1850 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1851 const FunctionDecl *Dcl, 1852 FieldDecl *Field, 1853 llvm::SmallSet<Decl*, 16> &Inits, 1854 bool &Diagnosed, 1855 Sema::CheckConstexprKind Kind) { 1856 if (Field->isInvalidDecl()) 1857 return true; 1858 1859 if (Field->isUnnamedBitfield()) 1860 return true; 1861 1862 // Anonymous unions with no variant members and empty anonymous structs do not 1863 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1864 // indirect fields don't need initializing. 1865 if (Field->isAnonymousStructOrUnion() && 1866 (Field->getType()->isUnionType() 1867 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1868 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1869 return true; 1870 1871 if (!Inits.count(Field)) { 1872 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1873 if (!Diagnosed) { 1874 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1875 Diagnosed = true; 1876 } 1877 SemaRef.Diag(Field->getLocation(), 1878 diag::note_constexpr_ctor_missing_init); 1879 } else { 1880 return false; 1881 } 1882 } else if (Field->isAnonymousStructOrUnion()) { 1883 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1884 for (auto *I : RD->fields()) 1885 // If an anonymous union contains an anonymous struct of which any member 1886 // is initialized, all members must be initialized. 1887 if (!RD->isUnion() || Inits.count(I)) 1888 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1889 Kind)) 1890 return false; 1891 } 1892 return true; 1893 } 1894 1895 /// Check the provided statement is allowed in a constexpr function 1896 /// definition. 1897 static bool 1898 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1899 SmallVectorImpl<SourceLocation> &ReturnStmts, 1900 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1901 Sema::CheckConstexprKind Kind) { 1902 // - its function-body shall be [...] a compound-statement that contains only 1903 switch (S->getStmtClass()) { 1904 case Stmt::NullStmtClass: 1905 // - null statements, 1906 return true; 1907 1908 case Stmt::DeclStmtClass: 1909 // - static_assert-declarations 1910 // - using-declarations, 1911 // - using-directives, 1912 // - typedef declarations and alias-declarations that do not define 1913 // classes or enumerations, 1914 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1915 return false; 1916 return true; 1917 1918 case Stmt::ReturnStmtClass: 1919 // - and exactly one return statement; 1920 if (isa<CXXConstructorDecl>(Dcl)) { 1921 // C++1y allows return statements in constexpr constructors. 1922 if (!Cxx1yLoc.isValid()) 1923 Cxx1yLoc = S->getBeginLoc(); 1924 return true; 1925 } 1926 1927 ReturnStmts.push_back(S->getBeginLoc()); 1928 return true; 1929 1930 case Stmt::CompoundStmtClass: { 1931 // C++1y allows compound-statements. 1932 if (!Cxx1yLoc.isValid()) 1933 Cxx1yLoc = S->getBeginLoc(); 1934 1935 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1936 for (auto *BodyIt : CompStmt->body()) { 1937 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1938 Cxx1yLoc, Cxx2aLoc, Kind)) 1939 return false; 1940 } 1941 return true; 1942 } 1943 1944 case Stmt::AttributedStmtClass: 1945 if (!Cxx1yLoc.isValid()) 1946 Cxx1yLoc = S->getBeginLoc(); 1947 return true; 1948 1949 case Stmt::IfStmtClass: { 1950 // C++1y allows if-statements. 1951 if (!Cxx1yLoc.isValid()) 1952 Cxx1yLoc = S->getBeginLoc(); 1953 1954 IfStmt *If = cast<IfStmt>(S); 1955 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1956 Cxx1yLoc, Cxx2aLoc, Kind)) 1957 return false; 1958 if (If->getElse() && 1959 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1960 Cxx1yLoc, Cxx2aLoc, Kind)) 1961 return false; 1962 return true; 1963 } 1964 1965 case Stmt::WhileStmtClass: 1966 case Stmt::DoStmtClass: 1967 case Stmt::ForStmtClass: 1968 case Stmt::CXXForRangeStmtClass: 1969 case Stmt::ContinueStmtClass: 1970 // C++1y allows all of these. We don't allow them as extensions in C++11, 1971 // because they don't make sense without variable mutation. 1972 if (!SemaRef.getLangOpts().CPlusPlus14) 1973 break; 1974 if (!Cxx1yLoc.isValid()) 1975 Cxx1yLoc = S->getBeginLoc(); 1976 for (Stmt *SubStmt : S->children()) 1977 if (SubStmt && 1978 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1979 Cxx1yLoc, Cxx2aLoc, Kind)) 1980 return false; 1981 return true; 1982 1983 case Stmt::SwitchStmtClass: 1984 case Stmt::CaseStmtClass: 1985 case Stmt::DefaultStmtClass: 1986 case Stmt::BreakStmtClass: 1987 // C++1y allows switch-statements, and since they don't need variable 1988 // mutation, we can reasonably allow them in C++11 as an extension. 1989 if (!Cxx1yLoc.isValid()) 1990 Cxx1yLoc = S->getBeginLoc(); 1991 for (Stmt *SubStmt : S->children()) 1992 if (SubStmt && 1993 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1994 Cxx1yLoc, Cxx2aLoc, Kind)) 1995 return false; 1996 return true; 1997 1998 case Stmt::GCCAsmStmtClass: 1999 case Stmt::MSAsmStmtClass: 2000 // C++2a allows inline assembly statements. 2001 case Stmt::CXXTryStmtClass: 2002 if (Cxx2aLoc.isInvalid()) 2003 Cxx2aLoc = S->getBeginLoc(); 2004 for (Stmt *SubStmt : S->children()) { 2005 if (SubStmt && 2006 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2007 Cxx1yLoc, Cxx2aLoc, Kind)) 2008 return false; 2009 } 2010 return true; 2011 2012 case Stmt::CXXCatchStmtClass: 2013 // Do not bother checking the language mode (already covered by the 2014 // try block check). 2015 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2016 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2017 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2018 return false; 2019 return true; 2020 2021 default: 2022 if (!isa<Expr>(S)) 2023 break; 2024 2025 // C++1y allows expression-statements. 2026 if (!Cxx1yLoc.isValid()) 2027 Cxx1yLoc = S->getBeginLoc(); 2028 return true; 2029 } 2030 2031 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2032 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2033 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2034 } 2035 return false; 2036 } 2037 2038 /// Check the body for the given constexpr function declaration only contains 2039 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2040 /// 2041 /// \return true if the body is OK, false if we have found or diagnosed a 2042 /// problem. 2043 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2044 Stmt *Body, 2045 Sema::CheckConstexprKind Kind) { 2046 SmallVector<SourceLocation, 4> ReturnStmts; 2047 2048 if (isa<CXXTryStmt>(Body)) { 2049 // C++11 [dcl.constexpr]p3: 2050 // The definition of a constexpr function shall satisfy the following 2051 // constraints: [...] 2052 // - its function-body shall be = delete, = default, or a 2053 // compound-statement 2054 // 2055 // C++11 [dcl.constexpr]p4: 2056 // In the definition of a constexpr constructor, [...] 2057 // - its function-body shall not be a function-try-block; 2058 // 2059 // This restriction is lifted in C++2a, as long as inner statements also 2060 // apply the general constexpr rules. 2061 switch (Kind) { 2062 case Sema::CheckConstexprKind::CheckValid: 2063 if (!SemaRef.getLangOpts().CPlusPlus2a) 2064 return false; 2065 break; 2066 2067 case Sema::CheckConstexprKind::Diagnose: 2068 SemaRef.Diag(Body->getBeginLoc(), 2069 !SemaRef.getLangOpts().CPlusPlus2a 2070 ? diag::ext_constexpr_function_try_block_cxx2a 2071 : diag::warn_cxx17_compat_constexpr_function_try_block) 2072 << isa<CXXConstructorDecl>(Dcl); 2073 break; 2074 } 2075 } 2076 2077 // - its function-body shall be [...] a compound-statement that contains only 2078 // [... list of cases ...] 2079 // 2080 // Note that walking the children here is enough to properly check for 2081 // CompoundStmt and CXXTryStmt body. 2082 SourceLocation Cxx1yLoc, Cxx2aLoc; 2083 for (Stmt *SubStmt : Body->children()) { 2084 if (SubStmt && 2085 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2086 Cxx1yLoc, Cxx2aLoc, Kind)) 2087 return false; 2088 } 2089 2090 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2091 // If this is only valid as an extension, report that we don't satisfy the 2092 // constraints of the current language. 2093 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) || 2094 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2095 return false; 2096 } else if (Cxx2aLoc.isValid()) { 2097 SemaRef.Diag(Cxx2aLoc, 2098 SemaRef.getLangOpts().CPlusPlus2a 2099 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2100 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 2101 << isa<CXXConstructorDecl>(Dcl); 2102 } else if (Cxx1yLoc.isValid()) { 2103 SemaRef.Diag(Cxx1yLoc, 2104 SemaRef.getLangOpts().CPlusPlus14 2105 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2106 : diag::ext_constexpr_body_invalid_stmt) 2107 << isa<CXXConstructorDecl>(Dcl); 2108 } 2109 2110 if (const CXXConstructorDecl *Constructor 2111 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2112 const CXXRecordDecl *RD = Constructor->getParent(); 2113 // DR1359: 2114 // - every non-variant non-static data member and base class sub-object 2115 // shall be initialized; 2116 // DR1460: 2117 // - if the class is a union having variant members, exactly one of them 2118 // shall be initialized; 2119 if (RD->isUnion()) { 2120 if (Constructor->getNumCtorInitializers() == 0 && 2121 RD->hasVariantMembers()) { 2122 if (Kind == Sema::CheckConstexprKind::Diagnose) 2123 SemaRef.Diag(Dcl->getLocation(), 2124 diag::err_constexpr_union_ctor_no_init); 2125 return false; 2126 } 2127 } else if (!Constructor->isDependentContext() && 2128 !Constructor->isDelegatingConstructor()) { 2129 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2130 2131 // Skip detailed checking if we have enough initializers, and we would 2132 // allow at most one initializer per member. 2133 bool AnyAnonStructUnionMembers = false; 2134 unsigned Fields = 0; 2135 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2136 E = RD->field_end(); I != E; ++I, ++Fields) { 2137 if (I->isAnonymousStructOrUnion()) { 2138 AnyAnonStructUnionMembers = true; 2139 break; 2140 } 2141 } 2142 // DR1460: 2143 // - if the class is a union-like class, but is not a union, for each of 2144 // its anonymous union members having variant members, exactly one of 2145 // them shall be initialized; 2146 if (AnyAnonStructUnionMembers || 2147 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2148 // Check initialization of non-static data members. Base classes are 2149 // always initialized so do not need to be checked. Dependent bases 2150 // might not have initializers in the member initializer list. 2151 llvm::SmallSet<Decl*, 16> Inits; 2152 for (const auto *I: Constructor->inits()) { 2153 if (FieldDecl *FD = I->getMember()) 2154 Inits.insert(FD); 2155 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2156 Inits.insert(ID->chain_begin(), ID->chain_end()); 2157 } 2158 2159 bool Diagnosed = false; 2160 for (auto *I : RD->fields()) 2161 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2162 Kind)) 2163 return false; 2164 } 2165 } 2166 } else { 2167 if (ReturnStmts.empty()) { 2168 // C++1y doesn't require constexpr functions to contain a 'return' 2169 // statement. We still do, unless the return type might be void, because 2170 // otherwise if there's no return statement, the function cannot 2171 // be used in a core constant expression. 2172 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2173 (Dcl->getReturnType()->isVoidType() || 2174 Dcl->getReturnType()->isDependentType()); 2175 switch (Kind) { 2176 case Sema::CheckConstexprKind::Diagnose: 2177 SemaRef.Diag(Dcl->getLocation(), 2178 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2179 : diag::err_constexpr_body_no_return) 2180 << Dcl->isConsteval(); 2181 if (!OK) 2182 return false; 2183 break; 2184 2185 case Sema::CheckConstexprKind::CheckValid: 2186 // The formal requirements don't include this rule in C++14, even 2187 // though the "must be able to produce a constant expression" rules 2188 // still imply it in some cases. 2189 if (!SemaRef.getLangOpts().CPlusPlus14) 2190 return false; 2191 break; 2192 } 2193 } else if (ReturnStmts.size() > 1) { 2194 switch (Kind) { 2195 case Sema::CheckConstexprKind::Diagnose: 2196 SemaRef.Diag( 2197 ReturnStmts.back(), 2198 SemaRef.getLangOpts().CPlusPlus14 2199 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2200 : diag::ext_constexpr_body_multiple_return); 2201 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2202 SemaRef.Diag(ReturnStmts[I], 2203 diag::note_constexpr_body_previous_return); 2204 break; 2205 2206 case Sema::CheckConstexprKind::CheckValid: 2207 if (!SemaRef.getLangOpts().CPlusPlus14) 2208 return false; 2209 break; 2210 } 2211 } 2212 } 2213 2214 // C++11 [dcl.constexpr]p5: 2215 // if no function argument values exist such that the function invocation 2216 // substitution would produce a constant expression, the program is 2217 // ill-formed; no diagnostic required. 2218 // C++11 [dcl.constexpr]p3: 2219 // - every constructor call and implicit conversion used in initializing the 2220 // return value shall be one of those allowed in a constant expression. 2221 // C++11 [dcl.constexpr]p4: 2222 // - every constructor involved in initializing non-static data members and 2223 // base class sub-objects shall be a constexpr constructor. 2224 // 2225 // Note that this rule is distinct from the "requirements for a constexpr 2226 // function", so is not checked in CheckValid mode. 2227 SmallVector<PartialDiagnosticAt, 8> Diags; 2228 if (Kind == Sema::CheckConstexprKind::Diagnose && 2229 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2230 SemaRef.Diag(Dcl->getLocation(), 2231 diag::ext_constexpr_function_never_constant_expr) 2232 << isa<CXXConstructorDecl>(Dcl); 2233 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2234 SemaRef.Diag(Diags[I].first, Diags[I].second); 2235 // Don't return false here: we allow this for compatibility in 2236 // system headers. 2237 } 2238 2239 return true; 2240 } 2241 2242 /// Get the class that is directly named by the current context. This is the 2243 /// class for which an unqualified-id in this scope could name a constructor 2244 /// or destructor. 2245 /// 2246 /// If the scope specifier denotes a class, this will be that class. 2247 /// If the scope specifier is empty, this will be the class whose 2248 /// member-specification we are currently within. Otherwise, there 2249 /// is no such class. 2250 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2251 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2252 2253 if (SS && SS->isInvalid()) 2254 return nullptr; 2255 2256 if (SS && SS->isNotEmpty()) { 2257 DeclContext *DC = computeDeclContext(*SS, true); 2258 return dyn_cast_or_null<CXXRecordDecl>(DC); 2259 } 2260 2261 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2262 } 2263 2264 /// isCurrentClassName - Determine whether the identifier II is the 2265 /// name of the class type currently being defined. In the case of 2266 /// nested classes, this will only return true if II is the name of 2267 /// the innermost class. 2268 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2269 const CXXScopeSpec *SS) { 2270 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2271 return CurDecl && &II == CurDecl->getIdentifier(); 2272 } 2273 2274 /// Determine whether the identifier II is a typo for the name of 2275 /// the class type currently being defined. If so, update it to the identifier 2276 /// that should have been used. 2277 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2278 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2279 2280 if (!getLangOpts().SpellChecking) 2281 return false; 2282 2283 CXXRecordDecl *CurDecl; 2284 if (SS && SS->isSet() && !SS->isInvalid()) { 2285 DeclContext *DC = computeDeclContext(*SS, true); 2286 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2287 } else 2288 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2289 2290 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2291 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2292 < II->getLength()) { 2293 II = CurDecl->getIdentifier(); 2294 return true; 2295 } 2296 2297 return false; 2298 } 2299 2300 /// Determine whether the given class is a base class of the given 2301 /// class, including looking at dependent bases. 2302 static bool findCircularInheritance(const CXXRecordDecl *Class, 2303 const CXXRecordDecl *Current) { 2304 SmallVector<const CXXRecordDecl*, 8> Queue; 2305 2306 Class = Class->getCanonicalDecl(); 2307 while (true) { 2308 for (const auto &I : Current->bases()) { 2309 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2310 if (!Base) 2311 continue; 2312 2313 Base = Base->getDefinition(); 2314 if (!Base) 2315 continue; 2316 2317 if (Base->getCanonicalDecl() == Class) 2318 return true; 2319 2320 Queue.push_back(Base); 2321 } 2322 2323 if (Queue.empty()) 2324 return false; 2325 2326 Current = Queue.pop_back_val(); 2327 } 2328 2329 return false; 2330 } 2331 2332 /// Check the validity of a C++ base class specifier. 2333 /// 2334 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2335 /// and returns NULL otherwise. 2336 CXXBaseSpecifier * 2337 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2338 SourceRange SpecifierRange, 2339 bool Virtual, AccessSpecifier Access, 2340 TypeSourceInfo *TInfo, 2341 SourceLocation EllipsisLoc) { 2342 QualType BaseType = TInfo->getType(); 2343 2344 // C++ [class.union]p1: 2345 // A union shall not have base classes. 2346 if (Class->isUnion()) { 2347 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2348 << SpecifierRange; 2349 return nullptr; 2350 } 2351 2352 if (EllipsisLoc.isValid() && 2353 !TInfo->getType()->containsUnexpandedParameterPack()) { 2354 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2355 << TInfo->getTypeLoc().getSourceRange(); 2356 EllipsisLoc = SourceLocation(); 2357 } 2358 2359 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2360 2361 if (BaseType->isDependentType()) { 2362 // Make sure that we don't have circular inheritance among our dependent 2363 // bases. For non-dependent bases, the check for completeness below handles 2364 // this. 2365 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2366 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2367 ((BaseDecl = BaseDecl->getDefinition()) && 2368 findCircularInheritance(Class, BaseDecl))) { 2369 Diag(BaseLoc, diag::err_circular_inheritance) 2370 << BaseType << Context.getTypeDeclType(Class); 2371 2372 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2373 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2374 << BaseType; 2375 2376 return nullptr; 2377 } 2378 } 2379 2380 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2381 Class->getTagKind() == TTK_Class, 2382 Access, TInfo, EllipsisLoc); 2383 } 2384 2385 // Base specifiers must be record types. 2386 if (!BaseType->isRecordType()) { 2387 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2388 return nullptr; 2389 } 2390 2391 // C++ [class.union]p1: 2392 // A union shall not be used as a base class. 2393 if (BaseType->isUnionType()) { 2394 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2395 return nullptr; 2396 } 2397 2398 // For the MS ABI, propagate DLL attributes to base class templates. 2399 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2400 if (Attr *ClassAttr = getDLLAttr(Class)) { 2401 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2402 BaseType->getAsCXXRecordDecl())) { 2403 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2404 BaseLoc); 2405 } 2406 } 2407 } 2408 2409 // C++ [class.derived]p2: 2410 // The class-name in a base-specifier shall not be an incompletely 2411 // defined class. 2412 if (RequireCompleteType(BaseLoc, BaseType, 2413 diag::err_incomplete_base_class, SpecifierRange)) { 2414 Class->setInvalidDecl(); 2415 return nullptr; 2416 } 2417 2418 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2419 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2420 assert(BaseDecl && "Record type has no declaration"); 2421 BaseDecl = BaseDecl->getDefinition(); 2422 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2423 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2424 assert(CXXBaseDecl && "Base type is not a C++ type"); 2425 2426 // Microsoft docs say: 2427 // "If a base-class has a code_seg attribute, derived classes must have the 2428 // same attribute." 2429 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2430 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2431 if ((DerivedCSA || BaseCSA) && 2432 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2433 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2434 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2435 << CXXBaseDecl; 2436 return nullptr; 2437 } 2438 2439 // A class which contains a flexible array member is not suitable for use as a 2440 // base class: 2441 // - If the layout determines that a base comes before another base, 2442 // the flexible array member would index into the subsequent base. 2443 // - If the layout determines that base comes before the derived class, 2444 // the flexible array member would index into the derived class. 2445 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2446 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2447 << CXXBaseDecl->getDeclName(); 2448 return nullptr; 2449 } 2450 2451 // C++ [class]p3: 2452 // If a class is marked final and it appears as a base-type-specifier in 2453 // base-clause, the program is ill-formed. 2454 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2455 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2456 << CXXBaseDecl->getDeclName() 2457 << FA->isSpelledAsSealed(); 2458 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2459 << CXXBaseDecl->getDeclName() << FA->getRange(); 2460 return nullptr; 2461 } 2462 2463 if (BaseDecl->isInvalidDecl()) 2464 Class->setInvalidDecl(); 2465 2466 // Create the base specifier. 2467 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2468 Class->getTagKind() == TTK_Class, 2469 Access, TInfo, EllipsisLoc); 2470 } 2471 2472 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2473 /// one entry in the base class list of a class specifier, for 2474 /// example: 2475 /// class foo : public bar, virtual private baz { 2476 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2477 BaseResult 2478 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2479 ParsedAttributes &Attributes, 2480 bool Virtual, AccessSpecifier Access, 2481 ParsedType basetype, SourceLocation BaseLoc, 2482 SourceLocation EllipsisLoc) { 2483 if (!classdecl) 2484 return true; 2485 2486 AdjustDeclIfTemplate(classdecl); 2487 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2488 if (!Class) 2489 return true; 2490 2491 // We haven't yet attached the base specifiers. 2492 Class->setIsParsingBaseSpecifiers(); 2493 2494 // We do not support any C++11 attributes on base-specifiers yet. 2495 // Diagnose any attributes we see. 2496 for (const ParsedAttr &AL : Attributes) { 2497 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2498 continue; 2499 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2500 ? (unsigned)diag::warn_unknown_attribute_ignored 2501 : (unsigned)diag::err_base_specifier_attribute) 2502 << AL.getName(); 2503 } 2504 2505 TypeSourceInfo *TInfo = nullptr; 2506 GetTypeFromParser(basetype, &TInfo); 2507 2508 if (EllipsisLoc.isInvalid() && 2509 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2510 UPPC_BaseType)) 2511 return true; 2512 2513 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2514 Virtual, Access, TInfo, 2515 EllipsisLoc)) 2516 return BaseSpec; 2517 else 2518 Class->setInvalidDecl(); 2519 2520 return true; 2521 } 2522 2523 /// Use small set to collect indirect bases. As this is only used 2524 /// locally, there's no need to abstract the small size parameter. 2525 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2526 2527 /// Recursively add the bases of Type. Don't add Type itself. 2528 static void 2529 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2530 const QualType &Type) 2531 { 2532 // Even though the incoming type is a base, it might not be 2533 // a class -- it could be a template parm, for instance. 2534 if (auto Rec = Type->getAs<RecordType>()) { 2535 auto Decl = Rec->getAsCXXRecordDecl(); 2536 2537 // Iterate over its bases. 2538 for (const auto &BaseSpec : Decl->bases()) { 2539 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2540 .getUnqualifiedType(); 2541 if (Set.insert(Base).second) 2542 // If we've not already seen it, recurse. 2543 NoteIndirectBases(Context, Set, Base); 2544 } 2545 } 2546 } 2547 2548 /// Performs the actual work of attaching the given base class 2549 /// specifiers to a C++ class. 2550 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2551 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2552 if (Bases.empty()) 2553 return false; 2554 2555 // Used to keep track of which base types we have already seen, so 2556 // that we can properly diagnose redundant direct base types. Note 2557 // that the key is always the unqualified canonical type of the base 2558 // class. 2559 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2560 2561 // Used to track indirect bases so we can see if a direct base is 2562 // ambiguous. 2563 IndirectBaseSet IndirectBaseTypes; 2564 2565 // Copy non-redundant base specifiers into permanent storage. 2566 unsigned NumGoodBases = 0; 2567 bool Invalid = false; 2568 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2569 QualType NewBaseType 2570 = Context.getCanonicalType(Bases[idx]->getType()); 2571 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2572 2573 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2574 if (KnownBase) { 2575 // C++ [class.mi]p3: 2576 // A class shall not be specified as a direct base class of a 2577 // derived class more than once. 2578 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2579 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2580 2581 // Delete the duplicate base class specifier; we're going to 2582 // overwrite its pointer later. 2583 Context.Deallocate(Bases[idx]); 2584 2585 Invalid = true; 2586 } else { 2587 // Okay, add this new base class. 2588 KnownBase = Bases[idx]; 2589 Bases[NumGoodBases++] = Bases[idx]; 2590 2591 // Note this base's direct & indirect bases, if there could be ambiguity. 2592 if (Bases.size() > 1) 2593 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2594 2595 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2596 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2597 if (Class->isInterface() && 2598 (!RD->isInterfaceLike() || 2599 KnownBase->getAccessSpecifier() != AS_public)) { 2600 // The Microsoft extension __interface does not permit bases that 2601 // are not themselves public interfaces. 2602 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2603 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2604 << RD->getSourceRange(); 2605 Invalid = true; 2606 } 2607 if (RD->hasAttr<WeakAttr>()) 2608 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2609 } 2610 } 2611 } 2612 2613 // Attach the remaining base class specifiers to the derived class. 2614 Class->setBases(Bases.data(), NumGoodBases); 2615 2616 // Check that the only base classes that are duplicate are virtual. 2617 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2618 // Check whether this direct base is inaccessible due to ambiguity. 2619 QualType BaseType = Bases[idx]->getType(); 2620 2621 // Skip all dependent types in templates being used as base specifiers. 2622 // Checks below assume that the base specifier is a CXXRecord. 2623 if (BaseType->isDependentType()) 2624 continue; 2625 2626 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2627 .getUnqualifiedType(); 2628 2629 if (IndirectBaseTypes.count(CanonicalBase)) { 2630 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2631 /*DetectVirtual=*/true); 2632 bool found 2633 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2634 assert(found); 2635 (void)found; 2636 2637 if (Paths.isAmbiguous(CanonicalBase)) 2638 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2639 << BaseType << getAmbiguousPathsDisplayString(Paths) 2640 << Bases[idx]->getSourceRange(); 2641 else 2642 assert(Bases[idx]->isVirtual()); 2643 } 2644 2645 // Delete the base class specifier, since its data has been copied 2646 // into the CXXRecordDecl. 2647 Context.Deallocate(Bases[idx]); 2648 } 2649 2650 return Invalid; 2651 } 2652 2653 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2654 /// class, after checking whether there are any duplicate base 2655 /// classes. 2656 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2657 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2658 if (!ClassDecl || Bases.empty()) 2659 return; 2660 2661 AdjustDeclIfTemplate(ClassDecl); 2662 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2663 } 2664 2665 /// Determine whether the type \p Derived is a C++ class that is 2666 /// derived from the type \p Base. 2667 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2668 if (!getLangOpts().CPlusPlus) 2669 return false; 2670 2671 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2672 if (!DerivedRD) 2673 return false; 2674 2675 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2676 if (!BaseRD) 2677 return false; 2678 2679 // If either the base or the derived type is invalid, don't try to 2680 // check whether one is derived from the other. 2681 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2682 return false; 2683 2684 // FIXME: In a modules build, do we need the entire path to be visible for us 2685 // to be able to use the inheritance relationship? 2686 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2687 return false; 2688 2689 return DerivedRD->isDerivedFrom(BaseRD); 2690 } 2691 2692 /// Determine whether the type \p Derived is a C++ class that is 2693 /// derived from the type \p Base. 2694 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2695 CXXBasePaths &Paths) { 2696 if (!getLangOpts().CPlusPlus) 2697 return false; 2698 2699 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2700 if (!DerivedRD) 2701 return false; 2702 2703 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2704 if (!BaseRD) 2705 return false; 2706 2707 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2708 return false; 2709 2710 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2711 } 2712 2713 static void BuildBasePathArray(const CXXBasePath &Path, 2714 CXXCastPath &BasePathArray) { 2715 // We first go backward and check if we have a virtual base. 2716 // FIXME: It would be better if CXXBasePath had the base specifier for 2717 // the nearest virtual base. 2718 unsigned Start = 0; 2719 for (unsigned I = Path.size(); I != 0; --I) { 2720 if (Path[I - 1].Base->isVirtual()) { 2721 Start = I - 1; 2722 break; 2723 } 2724 } 2725 2726 // Now add all bases. 2727 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2728 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2729 } 2730 2731 2732 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2733 CXXCastPath &BasePathArray) { 2734 assert(BasePathArray.empty() && "Base path array must be empty!"); 2735 assert(Paths.isRecordingPaths() && "Must record paths!"); 2736 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2737 } 2738 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2739 /// conversion (where Derived and Base are class types) is 2740 /// well-formed, meaning that the conversion is unambiguous (and 2741 /// that all of the base classes are accessible). Returns true 2742 /// and emits a diagnostic if the code is ill-formed, returns false 2743 /// otherwise. Loc is the location where this routine should point to 2744 /// if there is an error, and Range is the source range to highlight 2745 /// if there is an error. 2746 /// 2747 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2748 /// diagnostic for the respective type of error will be suppressed, but the 2749 /// check for ill-formed code will still be performed. 2750 bool 2751 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2752 unsigned InaccessibleBaseID, 2753 unsigned AmbigiousBaseConvID, 2754 SourceLocation Loc, SourceRange Range, 2755 DeclarationName Name, 2756 CXXCastPath *BasePath, 2757 bool IgnoreAccess) { 2758 // First, determine whether the path from Derived to Base is 2759 // ambiguous. This is slightly more expensive than checking whether 2760 // the Derived to Base conversion exists, because here we need to 2761 // explore multiple paths to determine if there is an ambiguity. 2762 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2763 /*DetectVirtual=*/false); 2764 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2765 if (!DerivationOkay) 2766 return true; 2767 2768 const CXXBasePath *Path = nullptr; 2769 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2770 Path = &Paths.front(); 2771 2772 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2773 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2774 // user to access such bases. 2775 if (!Path && getLangOpts().MSVCCompat) { 2776 for (const CXXBasePath &PossiblePath : Paths) { 2777 if (PossiblePath.size() == 1) { 2778 Path = &PossiblePath; 2779 if (AmbigiousBaseConvID) 2780 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2781 << Base << Derived << Range; 2782 break; 2783 } 2784 } 2785 } 2786 2787 if (Path) { 2788 if (!IgnoreAccess) { 2789 // Check that the base class can be accessed. 2790 switch ( 2791 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2792 case AR_inaccessible: 2793 return true; 2794 case AR_accessible: 2795 case AR_dependent: 2796 case AR_delayed: 2797 break; 2798 } 2799 } 2800 2801 // Build a base path if necessary. 2802 if (BasePath) 2803 ::BuildBasePathArray(*Path, *BasePath); 2804 return false; 2805 } 2806 2807 if (AmbigiousBaseConvID) { 2808 // We know that the derived-to-base conversion is ambiguous, and 2809 // we're going to produce a diagnostic. Perform the derived-to-base 2810 // search just one more time to compute all of the possible paths so 2811 // that we can print them out. This is more expensive than any of 2812 // the previous derived-to-base checks we've done, but at this point 2813 // performance isn't as much of an issue. 2814 Paths.clear(); 2815 Paths.setRecordingPaths(true); 2816 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2817 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2818 (void)StillOkay; 2819 2820 // Build up a textual representation of the ambiguous paths, e.g., 2821 // D -> B -> A, that will be used to illustrate the ambiguous 2822 // conversions in the diagnostic. We only print one of the paths 2823 // to each base class subobject. 2824 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2825 2826 Diag(Loc, AmbigiousBaseConvID) 2827 << Derived << Base << PathDisplayStr << Range << Name; 2828 } 2829 return true; 2830 } 2831 2832 bool 2833 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2834 SourceLocation Loc, SourceRange Range, 2835 CXXCastPath *BasePath, 2836 bool IgnoreAccess) { 2837 return CheckDerivedToBaseConversion( 2838 Derived, Base, diag::err_upcast_to_inaccessible_base, 2839 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2840 BasePath, IgnoreAccess); 2841 } 2842 2843 2844 /// Builds a string representing ambiguous paths from a 2845 /// specific derived class to different subobjects of the same base 2846 /// class. 2847 /// 2848 /// This function builds a string that can be used in error messages 2849 /// to show the different paths that one can take through the 2850 /// inheritance hierarchy to go from the derived class to different 2851 /// subobjects of a base class. The result looks something like this: 2852 /// @code 2853 /// struct D -> struct B -> struct A 2854 /// struct D -> struct C -> struct A 2855 /// @endcode 2856 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2857 std::string PathDisplayStr; 2858 std::set<unsigned> DisplayedPaths; 2859 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2860 Path != Paths.end(); ++Path) { 2861 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2862 // We haven't displayed a path to this particular base 2863 // class subobject yet. 2864 PathDisplayStr += "\n "; 2865 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2866 for (CXXBasePath::const_iterator Element = Path->begin(); 2867 Element != Path->end(); ++Element) 2868 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2869 } 2870 } 2871 2872 return PathDisplayStr; 2873 } 2874 2875 //===----------------------------------------------------------------------===// 2876 // C++ class member Handling 2877 //===----------------------------------------------------------------------===// 2878 2879 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2880 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2881 SourceLocation ColonLoc, 2882 const ParsedAttributesView &Attrs) { 2883 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2884 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2885 ASLoc, ColonLoc); 2886 CurContext->addHiddenDecl(ASDecl); 2887 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2888 } 2889 2890 /// CheckOverrideControl - Check C++11 override control semantics. 2891 void Sema::CheckOverrideControl(NamedDecl *D) { 2892 if (D->isInvalidDecl()) 2893 return; 2894 2895 // We only care about "override" and "final" declarations. 2896 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2897 return; 2898 2899 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2900 2901 // We can't check dependent instance methods. 2902 if (MD && MD->isInstance() && 2903 (MD->getParent()->hasAnyDependentBases() || 2904 MD->getType()->isDependentType())) 2905 return; 2906 2907 if (MD && !MD->isVirtual()) { 2908 // If we have a non-virtual method, check if if hides a virtual method. 2909 // (In that case, it's most likely the method has the wrong type.) 2910 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2911 FindHiddenVirtualMethods(MD, OverloadedMethods); 2912 2913 if (!OverloadedMethods.empty()) { 2914 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2915 Diag(OA->getLocation(), 2916 diag::override_keyword_hides_virtual_member_function) 2917 << "override" << (OverloadedMethods.size() > 1); 2918 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2919 Diag(FA->getLocation(), 2920 diag::override_keyword_hides_virtual_member_function) 2921 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2922 << (OverloadedMethods.size() > 1); 2923 } 2924 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2925 MD->setInvalidDecl(); 2926 return; 2927 } 2928 // Fall through into the general case diagnostic. 2929 // FIXME: We might want to attempt typo correction here. 2930 } 2931 2932 if (!MD || !MD->isVirtual()) { 2933 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2934 Diag(OA->getLocation(), 2935 diag::override_keyword_only_allowed_on_virtual_member_functions) 2936 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2937 D->dropAttr<OverrideAttr>(); 2938 } 2939 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2940 Diag(FA->getLocation(), 2941 diag::override_keyword_only_allowed_on_virtual_member_functions) 2942 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2943 << FixItHint::CreateRemoval(FA->getLocation()); 2944 D->dropAttr<FinalAttr>(); 2945 } 2946 return; 2947 } 2948 2949 // C++11 [class.virtual]p5: 2950 // If a function is marked with the virt-specifier override and 2951 // does not override a member function of a base class, the program is 2952 // ill-formed. 2953 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2954 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2955 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2956 << MD->getDeclName(); 2957 } 2958 2959 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2960 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2961 return; 2962 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2963 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2964 return; 2965 2966 SourceLocation Loc = MD->getLocation(); 2967 SourceLocation SpellingLoc = Loc; 2968 if (getSourceManager().isMacroArgExpansion(Loc)) 2969 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2970 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2971 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2972 return; 2973 2974 if (MD->size_overridden_methods() > 0) { 2975 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2976 ? diag::warn_destructor_marked_not_override_overriding 2977 : diag::warn_function_marked_not_override_overriding; 2978 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2979 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2980 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2981 } 2982 } 2983 2984 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2985 /// function overrides a virtual member function marked 'final', according to 2986 /// C++11 [class.virtual]p4. 2987 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2988 const CXXMethodDecl *Old) { 2989 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2990 if (!FA) 2991 return false; 2992 2993 Diag(New->getLocation(), diag::err_final_function_overridden) 2994 << New->getDeclName() 2995 << FA->isSpelledAsSealed(); 2996 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2997 return true; 2998 } 2999 3000 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3001 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3002 // FIXME: Destruction of ObjC lifetime types has side-effects. 3003 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3004 return !RD->isCompleteDefinition() || 3005 !RD->hasTrivialDefaultConstructor() || 3006 !RD->hasTrivialDestructor(); 3007 return false; 3008 } 3009 3010 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3011 ParsedAttributesView::const_iterator Itr = 3012 llvm::find_if(list, [](const ParsedAttr &AL) { 3013 return AL.isDeclspecPropertyAttribute(); 3014 }); 3015 if (Itr != list.end()) 3016 return &*Itr; 3017 return nullptr; 3018 } 3019 3020 // Check if there is a field shadowing. 3021 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3022 DeclarationName FieldName, 3023 const CXXRecordDecl *RD, 3024 bool DeclIsField) { 3025 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3026 return; 3027 3028 // To record a shadowed field in a base 3029 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3030 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3031 CXXBasePath &Path) { 3032 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3033 // Record an ambiguous path directly 3034 if (Bases.find(Base) != Bases.end()) 3035 return true; 3036 for (const auto Field : Base->lookup(FieldName)) { 3037 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3038 Field->getAccess() != AS_private) { 3039 assert(Field->getAccess() != AS_none); 3040 assert(Bases.find(Base) == Bases.end()); 3041 Bases[Base] = Field; 3042 return true; 3043 } 3044 } 3045 return false; 3046 }; 3047 3048 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3049 /*DetectVirtual=*/true); 3050 if (!RD->lookupInBases(FieldShadowed, Paths)) 3051 return; 3052 3053 for (const auto &P : Paths) { 3054 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3055 auto It = Bases.find(Base); 3056 // Skip duplicated bases 3057 if (It == Bases.end()) 3058 continue; 3059 auto BaseField = It->second; 3060 assert(BaseField->getAccess() != AS_private); 3061 if (AS_none != 3062 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3063 Diag(Loc, diag::warn_shadow_field) 3064 << FieldName << RD << Base << DeclIsField; 3065 Diag(BaseField->getLocation(), diag::note_shadow_field); 3066 Bases.erase(It); 3067 } 3068 } 3069 } 3070 3071 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3072 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3073 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3074 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3075 /// present (but parsing it has been deferred). 3076 NamedDecl * 3077 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3078 MultiTemplateParamsArg TemplateParameterLists, 3079 Expr *BW, const VirtSpecifiers &VS, 3080 InClassInitStyle InitStyle) { 3081 const DeclSpec &DS = D.getDeclSpec(); 3082 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3083 DeclarationName Name = NameInfo.getName(); 3084 SourceLocation Loc = NameInfo.getLoc(); 3085 3086 // For anonymous bitfields, the location should point to the type. 3087 if (Loc.isInvalid()) 3088 Loc = D.getBeginLoc(); 3089 3090 Expr *BitWidth = static_cast<Expr*>(BW); 3091 3092 assert(isa<CXXRecordDecl>(CurContext)); 3093 assert(!DS.isFriendSpecified()); 3094 3095 bool isFunc = D.isDeclarationOfFunction(); 3096 const ParsedAttr *MSPropertyAttr = 3097 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3098 3099 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3100 // The Microsoft extension __interface only permits public member functions 3101 // and prohibits constructors, destructors, operators, non-public member 3102 // functions, static methods and data members. 3103 unsigned InvalidDecl; 3104 bool ShowDeclName = true; 3105 if (!isFunc && 3106 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3107 InvalidDecl = 0; 3108 else if (!isFunc) 3109 InvalidDecl = 1; 3110 else if (AS != AS_public) 3111 InvalidDecl = 2; 3112 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3113 InvalidDecl = 3; 3114 else switch (Name.getNameKind()) { 3115 case DeclarationName::CXXConstructorName: 3116 InvalidDecl = 4; 3117 ShowDeclName = false; 3118 break; 3119 3120 case DeclarationName::CXXDestructorName: 3121 InvalidDecl = 5; 3122 ShowDeclName = false; 3123 break; 3124 3125 case DeclarationName::CXXOperatorName: 3126 case DeclarationName::CXXConversionFunctionName: 3127 InvalidDecl = 6; 3128 break; 3129 3130 default: 3131 InvalidDecl = 0; 3132 break; 3133 } 3134 3135 if (InvalidDecl) { 3136 if (ShowDeclName) 3137 Diag(Loc, diag::err_invalid_member_in_interface) 3138 << (InvalidDecl-1) << Name; 3139 else 3140 Diag(Loc, diag::err_invalid_member_in_interface) 3141 << (InvalidDecl-1) << ""; 3142 return nullptr; 3143 } 3144 } 3145 3146 // C++ 9.2p6: A member shall not be declared to have automatic storage 3147 // duration (auto, register) or with the extern storage-class-specifier. 3148 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3149 // data members and cannot be applied to names declared const or static, 3150 // and cannot be applied to reference members. 3151 switch (DS.getStorageClassSpec()) { 3152 case DeclSpec::SCS_unspecified: 3153 case DeclSpec::SCS_typedef: 3154 case DeclSpec::SCS_static: 3155 break; 3156 case DeclSpec::SCS_mutable: 3157 if (isFunc) { 3158 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3159 3160 // FIXME: It would be nicer if the keyword was ignored only for this 3161 // declarator. Otherwise we could get follow-up errors. 3162 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3163 } 3164 break; 3165 default: 3166 Diag(DS.getStorageClassSpecLoc(), 3167 diag::err_storageclass_invalid_for_member); 3168 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3169 break; 3170 } 3171 3172 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3173 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3174 !isFunc); 3175 3176 if (DS.hasConstexprSpecifier() && isInstField) { 3177 SemaDiagnosticBuilder B = 3178 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3179 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3180 if (InitStyle == ICIS_NoInit) { 3181 B << 0 << 0; 3182 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3183 B << FixItHint::CreateRemoval(ConstexprLoc); 3184 else { 3185 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3186 D.getMutableDeclSpec().ClearConstexprSpec(); 3187 const char *PrevSpec; 3188 unsigned DiagID; 3189 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3190 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3191 (void)Failed; 3192 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3193 } 3194 } else { 3195 B << 1; 3196 const char *PrevSpec; 3197 unsigned DiagID; 3198 if (D.getMutableDeclSpec().SetStorageClassSpec( 3199 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3200 Context.getPrintingPolicy())) { 3201 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3202 "This is the only DeclSpec that should fail to be applied"); 3203 B << 1; 3204 } else { 3205 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3206 isInstField = false; 3207 } 3208 } 3209 } 3210 3211 NamedDecl *Member; 3212 if (isInstField) { 3213 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3214 3215 // Data members must have identifiers for names. 3216 if (!Name.isIdentifier()) { 3217 Diag(Loc, diag::err_bad_variable_name) 3218 << Name; 3219 return nullptr; 3220 } 3221 3222 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3223 3224 // Member field could not be with "template" keyword. 3225 // So TemplateParameterLists should be empty in this case. 3226 if (TemplateParameterLists.size()) { 3227 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3228 if (TemplateParams->size()) { 3229 // There is no such thing as a member field template. 3230 Diag(D.getIdentifierLoc(), diag::err_template_member) 3231 << II 3232 << SourceRange(TemplateParams->getTemplateLoc(), 3233 TemplateParams->getRAngleLoc()); 3234 } else { 3235 // There is an extraneous 'template<>' for this member. 3236 Diag(TemplateParams->getTemplateLoc(), 3237 diag::err_template_member_noparams) 3238 << II 3239 << SourceRange(TemplateParams->getTemplateLoc(), 3240 TemplateParams->getRAngleLoc()); 3241 } 3242 return nullptr; 3243 } 3244 3245 if (SS.isSet() && !SS.isInvalid()) { 3246 // The user provided a superfluous scope specifier inside a class 3247 // definition: 3248 // 3249 // class X { 3250 // int X::member; 3251 // }; 3252 if (DeclContext *DC = computeDeclContext(SS, false)) 3253 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3254 D.getName().getKind() == 3255 UnqualifiedIdKind::IK_TemplateId); 3256 else 3257 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3258 << Name << SS.getRange(); 3259 3260 SS.clear(); 3261 } 3262 3263 if (MSPropertyAttr) { 3264 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3265 BitWidth, InitStyle, AS, *MSPropertyAttr); 3266 if (!Member) 3267 return nullptr; 3268 isInstField = false; 3269 } else { 3270 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3271 BitWidth, InitStyle, AS); 3272 if (!Member) 3273 return nullptr; 3274 } 3275 3276 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3277 } else { 3278 Member = HandleDeclarator(S, D, TemplateParameterLists); 3279 if (!Member) 3280 return nullptr; 3281 3282 // Non-instance-fields can't have a bitfield. 3283 if (BitWidth) { 3284 if (Member->isInvalidDecl()) { 3285 // don't emit another diagnostic. 3286 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3287 // C++ 9.6p3: A bit-field shall not be a static member. 3288 // "static member 'A' cannot be a bit-field" 3289 Diag(Loc, diag::err_static_not_bitfield) 3290 << Name << BitWidth->getSourceRange(); 3291 } else if (isa<TypedefDecl>(Member)) { 3292 // "typedef member 'x' cannot be a bit-field" 3293 Diag(Loc, diag::err_typedef_not_bitfield) 3294 << Name << BitWidth->getSourceRange(); 3295 } else { 3296 // A function typedef ("typedef int f(); f a;"). 3297 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3298 Diag(Loc, diag::err_not_integral_type_bitfield) 3299 << Name << cast<ValueDecl>(Member)->getType() 3300 << BitWidth->getSourceRange(); 3301 } 3302 3303 BitWidth = nullptr; 3304 Member->setInvalidDecl(); 3305 } 3306 3307 NamedDecl *NonTemplateMember = Member; 3308 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3309 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3310 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3311 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3312 3313 Member->setAccess(AS); 3314 3315 // If we have declared a member function template or static data member 3316 // template, set the access of the templated declaration as well. 3317 if (NonTemplateMember != Member) 3318 NonTemplateMember->setAccess(AS); 3319 3320 // C++ [temp.deduct.guide]p3: 3321 // A deduction guide [...] for a member class template [shall be 3322 // declared] with the same access [as the template]. 3323 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3324 auto *TD = DG->getDeducedTemplate(); 3325 // Access specifiers are only meaningful if both the template and the 3326 // deduction guide are from the same scope. 3327 if (AS != TD->getAccess() && 3328 TD->getDeclContext()->getRedeclContext()->Equals( 3329 DG->getDeclContext()->getRedeclContext())) { 3330 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3331 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3332 << TD->getAccess(); 3333 const AccessSpecDecl *LastAccessSpec = nullptr; 3334 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3335 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3336 LastAccessSpec = AccessSpec; 3337 } 3338 assert(LastAccessSpec && "differing access with no access specifier"); 3339 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3340 << AS; 3341 } 3342 } 3343 } 3344 3345 if (VS.isOverrideSpecified()) 3346 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3347 if (VS.isFinalSpecified()) 3348 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3349 VS.isFinalSpelledSealed())); 3350 3351 if (VS.getLastLocation().isValid()) { 3352 // Update the end location of a method that has a virt-specifiers. 3353 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3354 MD->setRangeEnd(VS.getLastLocation()); 3355 } 3356 3357 CheckOverrideControl(Member); 3358 3359 assert((Name || isInstField) && "No identifier for non-field ?"); 3360 3361 if (isInstField) { 3362 FieldDecl *FD = cast<FieldDecl>(Member); 3363 FieldCollector->Add(FD); 3364 3365 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3366 // Remember all explicit private FieldDecls that have a name, no side 3367 // effects and are not part of a dependent type declaration. 3368 if (!FD->isImplicit() && FD->getDeclName() && 3369 FD->getAccess() == AS_private && 3370 !FD->hasAttr<UnusedAttr>() && 3371 !FD->getParent()->isDependentContext() && 3372 !InitializationHasSideEffects(*FD)) 3373 UnusedPrivateFields.insert(FD); 3374 } 3375 } 3376 3377 return Member; 3378 } 3379 3380 namespace { 3381 class UninitializedFieldVisitor 3382 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3383 Sema &S; 3384 // List of Decls to generate a warning on. Also remove Decls that become 3385 // initialized. 3386 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3387 // List of base classes of the record. Classes are removed after their 3388 // initializers. 3389 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3390 // Vector of decls to be removed from the Decl set prior to visiting the 3391 // nodes. These Decls may have been initialized in the prior initializer. 3392 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3393 // If non-null, add a note to the warning pointing back to the constructor. 3394 const CXXConstructorDecl *Constructor; 3395 // Variables to hold state when processing an initializer list. When 3396 // InitList is true, special case initialization of FieldDecls matching 3397 // InitListFieldDecl. 3398 bool InitList; 3399 FieldDecl *InitListFieldDecl; 3400 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3401 3402 public: 3403 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3404 UninitializedFieldVisitor(Sema &S, 3405 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3406 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3407 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3408 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3409 3410 // Returns true if the use of ME is not an uninitialized use. 3411 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3412 bool CheckReferenceOnly) { 3413 llvm::SmallVector<FieldDecl*, 4> Fields; 3414 bool ReferenceField = false; 3415 while (ME) { 3416 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3417 if (!FD) 3418 return false; 3419 Fields.push_back(FD); 3420 if (FD->getType()->isReferenceType()) 3421 ReferenceField = true; 3422 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3423 } 3424 3425 // Binding a reference to an uninitialized field is not an 3426 // uninitialized use. 3427 if (CheckReferenceOnly && !ReferenceField) 3428 return true; 3429 3430 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3431 // Discard the first field since it is the field decl that is being 3432 // initialized. 3433 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3434 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3435 } 3436 3437 for (auto UsedIter = UsedFieldIndex.begin(), 3438 UsedEnd = UsedFieldIndex.end(), 3439 OrigIter = InitFieldIndex.begin(), 3440 OrigEnd = InitFieldIndex.end(); 3441 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3442 if (*UsedIter < *OrigIter) 3443 return true; 3444 if (*UsedIter > *OrigIter) 3445 break; 3446 } 3447 3448 return false; 3449 } 3450 3451 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3452 bool AddressOf) { 3453 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3454 return; 3455 3456 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3457 // or union. 3458 MemberExpr *FieldME = ME; 3459 3460 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3461 3462 Expr *Base = ME; 3463 while (MemberExpr *SubME = 3464 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3465 3466 if (isa<VarDecl>(SubME->getMemberDecl())) 3467 return; 3468 3469 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3470 if (!FD->isAnonymousStructOrUnion()) 3471 FieldME = SubME; 3472 3473 if (!FieldME->getType().isPODType(S.Context)) 3474 AllPODFields = false; 3475 3476 Base = SubME->getBase(); 3477 } 3478 3479 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3480 return; 3481 3482 if (AddressOf && AllPODFields) 3483 return; 3484 3485 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3486 3487 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3488 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3489 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3490 } 3491 3492 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3493 QualType T = BaseCast->getType(); 3494 if (T->isPointerType() && 3495 BaseClasses.count(T->getPointeeType())) { 3496 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3497 << T->getPointeeType() << FoundVD; 3498 } 3499 } 3500 } 3501 3502 if (!Decls.count(FoundVD)) 3503 return; 3504 3505 const bool IsReference = FoundVD->getType()->isReferenceType(); 3506 3507 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3508 // Special checking for initializer lists. 3509 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3510 return; 3511 } 3512 } else { 3513 // Prevent double warnings on use of unbounded references. 3514 if (CheckReferenceOnly && !IsReference) 3515 return; 3516 } 3517 3518 unsigned diag = IsReference 3519 ? diag::warn_reference_field_is_uninit 3520 : diag::warn_field_is_uninit; 3521 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3522 if (Constructor) 3523 S.Diag(Constructor->getLocation(), 3524 diag::note_uninit_in_this_constructor) 3525 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3526 3527 } 3528 3529 void HandleValue(Expr *E, bool AddressOf) { 3530 E = E->IgnoreParens(); 3531 3532 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3533 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3534 AddressOf /*AddressOf*/); 3535 return; 3536 } 3537 3538 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3539 Visit(CO->getCond()); 3540 HandleValue(CO->getTrueExpr(), AddressOf); 3541 HandleValue(CO->getFalseExpr(), AddressOf); 3542 return; 3543 } 3544 3545 if (BinaryConditionalOperator *BCO = 3546 dyn_cast<BinaryConditionalOperator>(E)) { 3547 Visit(BCO->getCond()); 3548 HandleValue(BCO->getFalseExpr(), AddressOf); 3549 return; 3550 } 3551 3552 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3553 HandleValue(OVE->getSourceExpr(), AddressOf); 3554 return; 3555 } 3556 3557 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3558 switch (BO->getOpcode()) { 3559 default: 3560 break; 3561 case(BO_PtrMemD): 3562 case(BO_PtrMemI): 3563 HandleValue(BO->getLHS(), AddressOf); 3564 Visit(BO->getRHS()); 3565 return; 3566 case(BO_Comma): 3567 Visit(BO->getLHS()); 3568 HandleValue(BO->getRHS(), AddressOf); 3569 return; 3570 } 3571 } 3572 3573 Visit(E); 3574 } 3575 3576 void CheckInitListExpr(InitListExpr *ILE) { 3577 InitFieldIndex.push_back(0); 3578 for (auto Child : ILE->children()) { 3579 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3580 CheckInitListExpr(SubList); 3581 } else { 3582 Visit(Child); 3583 } 3584 ++InitFieldIndex.back(); 3585 } 3586 InitFieldIndex.pop_back(); 3587 } 3588 3589 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3590 FieldDecl *Field, const Type *BaseClass) { 3591 // Remove Decls that may have been initialized in the previous 3592 // initializer. 3593 for (ValueDecl* VD : DeclsToRemove) 3594 Decls.erase(VD); 3595 DeclsToRemove.clear(); 3596 3597 Constructor = FieldConstructor; 3598 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3599 3600 if (ILE && Field) { 3601 InitList = true; 3602 InitListFieldDecl = Field; 3603 InitFieldIndex.clear(); 3604 CheckInitListExpr(ILE); 3605 } else { 3606 InitList = false; 3607 Visit(E); 3608 } 3609 3610 if (Field) 3611 Decls.erase(Field); 3612 if (BaseClass) 3613 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3614 } 3615 3616 void VisitMemberExpr(MemberExpr *ME) { 3617 // All uses of unbounded reference fields will warn. 3618 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3619 } 3620 3621 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3622 if (E->getCastKind() == CK_LValueToRValue) { 3623 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3624 return; 3625 } 3626 3627 Inherited::VisitImplicitCastExpr(E); 3628 } 3629 3630 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3631 if (E->getConstructor()->isCopyConstructor()) { 3632 Expr *ArgExpr = E->getArg(0); 3633 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3634 if (ILE->getNumInits() == 1) 3635 ArgExpr = ILE->getInit(0); 3636 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3637 if (ICE->getCastKind() == CK_NoOp) 3638 ArgExpr = ICE->getSubExpr(); 3639 HandleValue(ArgExpr, false /*AddressOf*/); 3640 return; 3641 } 3642 Inherited::VisitCXXConstructExpr(E); 3643 } 3644 3645 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3646 Expr *Callee = E->getCallee(); 3647 if (isa<MemberExpr>(Callee)) { 3648 HandleValue(Callee, false /*AddressOf*/); 3649 for (auto Arg : E->arguments()) 3650 Visit(Arg); 3651 return; 3652 } 3653 3654 Inherited::VisitCXXMemberCallExpr(E); 3655 } 3656 3657 void VisitCallExpr(CallExpr *E) { 3658 // Treat std::move as a use. 3659 if (E->isCallToStdMove()) { 3660 HandleValue(E->getArg(0), /*AddressOf=*/false); 3661 return; 3662 } 3663 3664 Inherited::VisitCallExpr(E); 3665 } 3666 3667 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3668 Expr *Callee = E->getCallee(); 3669 3670 if (isa<UnresolvedLookupExpr>(Callee)) 3671 return Inherited::VisitCXXOperatorCallExpr(E); 3672 3673 Visit(Callee); 3674 for (auto Arg : E->arguments()) 3675 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3676 } 3677 3678 void VisitBinaryOperator(BinaryOperator *E) { 3679 // If a field assignment is detected, remove the field from the 3680 // uninitiailized field set. 3681 if (E->getOpcode() == BO_Assign) 3682 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3683 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3684 if (!FD->getType()->isReferenceType()) 3685 DeclsToRemove.push_back(FD); 3686 3687 if (E->isCompoundAssignmentOp()) { 3688 HandleValue(E->getLHS(), false /*AddressOf*/); 3689 Visit(E->getRHS()); 3690 return; 3691 } 3692 3693 Inherited::VisitBinaryOperator(E); 3694 } 3695 3696 void VisitUnaryOperator(UnaryOperator *E) { 3697 if (E->isIncrementDecrementOp()) { 3698 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3699 return; 3700 } 3701 if (E->getOpcode() == UO_AddrOf) { 3702 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3703 HandleValue(ME->getBase(), true /*AddressOf*/); 3704 return; 3705 } 3706 } 3707 3708 Inherited::VisitUnaryOperator(E); 3709 } 3710 }; 3711 3712 // Diagnose value-uses of fields to initialize themselves, e.g. 3713 // foo(foo) 3714 // where foo is not also a parameter to the constructor. 3715 // Also diagnose across field uninitialized use such as 3716 // x(y), y(x) 3717 // TODO: implement -Wuninitialized and fold this into that framework. 3718 static void DiagnoseUninitializedFields( 3719 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3720 3721 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3722 Constructor->getLocation())) { 3723 return; 3724 } 3725 3726 if (Constructor->isInvalidDecl()) 3727 return; 3728 3729 const CXXRecordDecl *RD = Constructor->getParent(); 3730 3731 if (RD->getDescribedClassTemplate()) 3732 return; 3733 3734 // Holds fields that are uninitialized. 3735 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3736 3737 // At the beginning, all fields are uninitialized. 3738 for (auto *I : RD->decls()) { 3739 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3740 UninitializedFields.insert(FD); 3741 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3742 UninitializedFields.insert(IFD->getAnonField()); 3743 } 3744 } 3745 3746 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3747 for (auto I : RD->bases()) 3748 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3749 3750 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3751 return; 3752 3753 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3754 UninitializedFields, 3755 UninitializedBaseClasses); 3756 3757 for (const auto *FieldInit : Constructor->inits()) { 3758 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3759 break; 3760 3761 Expr *InitExpr = FieldInit->getInit(); 3762 if (!InitExpr) 3763 continue; 3764 3765 if (CXXDefaultInitExpr *Default = 3766 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3767 InitExpr = Default->getExpr(); 3768 if (!InitExpr) 3769 continue; 3770 // In class initializers will point to the constructor. 3771 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3772 FieldInit->getAnyMember(), 3773 FieldInit->getBaseClass()); 3774 } else { 3775 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3776 FieldInit->getAnyMember(), 3777 FieldInit->getBaseClass()); 3778 } 3779 } 3780 } 3781 } // namespace 3782 3783 /// Enter a new C++ default initializer scope. After calling this, the 3784 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3785 /// parsing or instantiating the initializer failed. 3786 void Sema::ActOnStartCXXInClassMemberInitializer() { 3787 // Create a synthetic function scope to represent the call to the constructor 3788 // that notionally surrounds a use of this initializer. 3789 PushFunctionScope(); 3790 } 3791 3792 /// This is invoked after parsing an in-class initializer for a 3793 /// non-static C++ class member, and after instantiating an in-class initializer 3794 /// in a class template. Such actions are deferred until the class is complete. 3795 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3796 SourceLocation InitLoc, 3797 Expr *InitExpr) { 3798 // Pop the notional constructor scope we created earlier. 3799 PopFunctionScopeInfo(nullptr, D); 3800 3801 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3802 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3803 "must set init style when field is created"); 3804 3805 if (!InitExpr) { 3806 D->setInvalidDecl(); 3807 if (FD) 3808 FD->removeInClassInitializer(); 3809 return; 3810 } 3811 3812 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3813 FD->setInvalidDecl(); 3814 FD->removeInClassInitializer(); 3815 return; 3816 } 3817 3818 ExprResult Init = InitExpr; 3819 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3820 InitializedEntity Entity = 3821 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3822 InitializationKind Kind = 3823 FD->getInClassInitStyle() == ICIS_ListInit 3824 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3825 InitExpr->getBeginLoc(), 3826 InitExpr->getEndLoc()) 3827 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3828 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3829 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3830 if (Init.isInvalid()) { 3831 FD->setInvalidDecl(); 3832 return; 3833 } 3834 } 3835 3836 // C++11 [class.base.init]p7: 3837 // The initialization of each base and member constitutes a 3838 // full-expression. 3839 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3840 if (Init.isInvalid()) { 3841 FD->setInvalidDecl(); 3842 return; 3843 } 3844 3845 InitExpr = Init.get(); 3846 3847 FD->setInClassInitializer(InitExpr); 3848 } 3849 3850 /// Find the direct and/or virtual base specifiers that 3851 /// correspond to the given base type, for use in base initialization 3852 /// within a constructor. 3853 static bool FindBaseInitializer(Sema &SemaRef, 3854 CXXRecordDecl *ClassDecl, 3855 QualType BaseType, 3856 const CXXBaseSpecifier *&DirectBaseSpec, 3857 const CXXBaseSpecifier *&VirtualBaseSpec) { 3858 // First, check for a direct base class. 3859 DirectBaseSpec = nullptr; 3860 for (const auto &Base : ClassDecl->bases()) { 3861 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3862 // We found a direct base of this type. That's what we're 3863 // initializing. 3864 DirectBaseSpec = &Base; 3865 break; 3866 } 3867 } 3868 3869 // Check for a virtual base class. 3870 // FIXME: We might be able to short-circuit this if we know in advance that 3871 // there are no virtual bases. 3872 VirtualBaseSpec = nullptr; 3873 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3874 // We haven't found a base yet; search the class hierarchy for a 3875 // virtual base class. 3876 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3877 /*DetectVirtual=*/false); 3878 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3879 SemaRef.Context.getTypeDeclType(ClassDecl), 3880 BaseType, Paths)) { 3881 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3882 Path != Paths.end(); ++Path) { 3883 if (Path->back().Base->isVirtual()) { 3884 VirtualBaseSpec = Path->back().Base; 3885 break; 3886 } 3887 } 3888 } 3889 } 3890 3891 return DirectBaseSpec || VirtualBaseSpec; 3892 } 3893 3894 /// Handle a C++ member initializer using braced-init-list syntax. 3895 MemInitResult 3896 Sema::ActOnMemInitializer(Decl *ConstructorD, 3897 Scope *S, 3898 CXXScopeSpec &SS, 3899 IdentifierInfo *MemberOrBase, 3900 ParsedType TemplateTypeTy, 3901 const DeclSpec &DS, 3902 SourceLocation IdLoc, 3903 Expr *InitList, 3904 SourceLocation EllipsisLoc) { 3905 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3906 DS, IdLoc, InitList, 3907 EllipsisLoc); 3908 } 3909 3910 /// Handle a C++ member initializer using parentheses syntax. 3911 MemInitResult 3912 Sema::ActOnMemInitializer(Decl *ConstructorD, 3913 Scope *S, 3914 CXXScopeSpec &SS, 3915 IdentifierInfo *MemberOrBase, 3916 ParsedType TemplateTypeTy, 3917 const DeclSpec &DS, 3918 SourceLocation IdLoc, 3919 SourceLocation LParenLoc, 3920 ArrayRef<Expr *> Args, 3921 SourceLocation RParenLoc, 3922 SourceLocation EllipsisLoc) { 3923 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 3924 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3925 DS, IdLoc, List, EllipsisLoc); 3926 } 3927 3928 namespace { 3929 3930 // Callback to only accept typo corrections that can be a valid C++ member 3931 // intializer: either a non-static field member or a base class. 3932 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 3933 public: 3934 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3935 : ClassDecl(ClassDecl) {} 3936 3937 bool ValidateCandidate(const TypoCorrection &candidate) override { 3938 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3939 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3940 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3941 return isa<TypeDecl>(ND); 3942 } 3943 return false; 3944 } 3945 3946 std::unique_ptr<CorrectionCandidateCallback> clone() override { 3947 return std::make_unique<MemInitializerValidatorCCC>(*this); 3948 } 3949 3950 private: 3951 CXXRecordDecl *ClassDecl; 3952 }; 3953 3954 } 3955 3956 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 3957 CXXScopeSpec &SS, 3958 ParsedType TemplateTypeTy, 3959 IdentifierInfo *MemberOrBase) { 3960 if (SS.getScopeRep() || TemplateTypeTy) 3961 return nullptr; 3962 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3963 if (Result.empty()) 3964 return nullptr; 3965 ValueDecl *Member; 3966 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3967 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 3968 return Member; 3969 return nullptr; 3970 } 3971 3972 /// Handle a C++ member initializer. 3973 MemInitResult 3974 Sema::BuildMemInitializer(Decl *ConstructorD, 3975 Scope *S, 3976 CXXScopeSpec &SS, 3977 IdentifierInfo *MemberOrBase, 3978 ParsedType TemplateTypeTy, 3979 const DeclSpec &DS, 3980 SourceLocation IdLoc, 3981 Expr *Init, 3982 SourceLocation EllipsisLoc) { 3983 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3984 if (!Res.isUsable()) 3985 return true; 3986 Init = Res.get(); 3987 3988 if (!ConstructorD) 3989 return true; 3990 3991 AdjustDeclIfTemplate(ConstructorD); 3992 3993 CXXConstructorDecl *Constructor 3994 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3995 if (!Constructor) { 3996 // The user wrote a constructor initializer on a function that is 3997 // not a C++ constructor. Ignore the error for now, because we may 3998 // have more member initializers coming; we'll diagnose it just 3999 // once in ActOnMemInitializers. 4000 return true; 4001 } 4002 4003 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4004 4005 // C++ [class.base.init]p2: 4006 // Names in a mem-initializer-id are looked up in the scope of the 4007 // constructor's class and, if not found in that scope, are looked 4008 // up in the scope containing the constructor's definition. 4009 // [Note: if the constructor's class contains a member with the 4010 // same name as a direct or virtual base class of the class, a 4011 // mem-initializer-id naming the member or base class and composed 4012 // of a single identifier refers to the class member. A 4013 // mem-initializer-id for the hidden base class may be specified 4014 // using a qualified name. ] 4015 4016 // Look for a member, first. 4017 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4018 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4019 if (EllipsisLoc.isValid()) 4020 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4021 << MemberOrBase 4022 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4023 4024 return BuildMemberInitializer(Member, Init, IdLoc); 4025 } 4026 // It didn't name a member, so see if it names a class. 4027 QualType BaseType; 4028 TypeSourceInfo *TInfo = nullptr; 4029 4030 if (TemplateTypeTy) { 4031 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4032 if (BaseType.isNull()) 4033 return true; 4034 } else if (DS.getTypeSpecType() == TST_decltype) { 4035 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4036 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4037 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4038 return true; 4039 } else { 4040 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4041 LookupParsedName(R, S, &SS); 4042 4043 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4044 if (!TyD) { 4045 if (R.isAmbiguous()) return true; 4046 4047 // We don't want access-control diagnostics here. 4048 R.suppressDiagnostics(); 4049 4050 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4051 bool NotUnknownSpecialization = false; 4052 DeclContext *DC = computeDeclContext(SS, false); 4053 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4054 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4055 4056 if (!NotUnknownSpecialization) { 4057 // When the scope specifier can refer to a member of an unknown 4058 // specialization, we take it as a type name. 4059 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4060 SS.getWithLocInContext(Context), 4061 *MemberOrBase, IdLoc); 4062 if (BaseType.isNull()) 4063 return true; 4064 4065 TInfo = Context.CreateTypeSourceInfo(BaseType); 4066 DependentNameTypeLoc TL = 4067 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4068 if (!TL.isNull()) { 4069 TL.setNameLoc(IdLoc); 4070 TL.setElaboratedKeywordLoc(SourceLocation()); 4071 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4072 } 4073 4074 R.clear(); 4075 R.setLookupName(MemberOrBase); 4076 } 4077 } 4078 4079 // If no results were found, try to correct typos. 4080 TypoCorrection Corr; 4081 MemInitializerValidatorCCC CCC(ClassDecl); 4082 if (R.empty() && BaseType.isNull() && 4083 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4084 CCC, CTK_ErrorRecovery, ClassDecl))) { 4085 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4086 // We have found a non-static data member with a similar 4087 // name to what was typed; complain and initialize that 4088 // member. 4089 diagnoseTypo(Corr, 4090 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4091 << MemberOrBase << true); 4092 return BuildMemberInitializer(Member, Init, IdLoc); 4093 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4094 const CXXBaseSpecifier *DirectBaseSpec; 4095 const CXXBaseSpecifier *VirtualBaseSpec; 4096 if (FindBaseInitializer(*this, ClassDecl, 4097 Context.getTypeDeclType(Type), 4098 DirectBaseSpec, VirtualBaseSpec)) { 4099 // We have found a direct or virtual base class with a 4100 // similar name to what was typed; complain and initialize 4101 // that base class. 4102 diagnoseTypo(Corr, 4103 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4104 << MemberOrBase << false, 4105 PDiag() /*Suppress note, we provide our own.*/); 4106 4107 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4108 : VirtualBaseSpec; 4109 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4110 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4111 4112 TyD = Type; 4113 } 4114 } 4115 } 4116 4117 if (!TyD && BaseType.isNull()) { 4118 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4119 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4120 return true; 4121 } 4122 } 4123 4124 if (BaseType.isNull()) { 4125 BaseType = Context.getTypeDeclType(TyD); 4126 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4127 if (SS.isSet()) { 4128 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4129 BaseType); 4130 TInfo = Context.CreateTypeSourceInfo(BaseType); 4131 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4132 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4133 TL.setElaboratedKeywordLoc(SourceLocation()); 4134 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4135 } 4136 } 4137 } 4138 4139 if (!TInfo) 4140 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4141 4142 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4143 } 4144 4145 MemInitResult 4146 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4147 SourceLocation IdLoc) { 4148 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4149 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4150 assert((DirectMember || IndirectMember) && 4151 "Member must be a FieldDecl or IndirectFieldDecl"); 4152 4153 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4154 return true; 4155 4156 if (Member->isInvalidDecl()) 4157 return true; 4158 4159 MultiExprArg Args; 4160 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4161 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4162 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4163 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4164 } else { 4165 // Template instantiation doesn't reconstruct ParenListExprs for us. 4166 Args = Init; 4167 } 4168 4169 SourceRange InitRange = Init->getSourceRange(); 4170 4171 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4172 // Can't check initialization for a member of dependent type or when 4173 // any of the arguments are type-dependent expressions. 4174 DiscardCleanupsInEvaluationContext(); 4175 } else { 4176 bool InitList = false; 4177 if (isa<InitListExpr>(Init)) { 4178 InitList = true; 4179 Args = Init; 4180 } 4181 4182 // Initialize the member. 4183 InitializedEntity MemberEntity = 4184 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4185 : InitializedEntity::InitializeMember(IndirectMember, 4186 nullptr); 4187 InitializationKind Kind = 4188 InitList ? InitializationKind::CreateDirectList( 4189 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4190 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4191 InitRange.getEnd()); 4192 4193 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4194 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4195 nullptr); 4196 if (MemberInit.isInvalid()) 4197 return true; 4198 4199 // C++11 [class.base.init]p7: 4200 // The initialization of each base and member constitutes a 4201 // full-expression. 4202 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4203 /*DiscardedValue*/ false); 4204 if (MemberInit.isInvalid()) 4205 return true; 4206 4207 Init = MemberInit.get(); 4208 } 4209 4210 if (DirectMember) { 4211 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4212 InitRange.getBegin(), Init, 4213 InitRange.getEnd()); 4214 } else { 4215 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4216 InitRange.getBegin(), Init, 4217 InitRange.getEnd()); 4218 } 4219 } 4220 4221 MemInitResult 4222 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4223 CXXRecordDecl *ClassDecl) { 4224 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4225 if (!LangOpts.CPlusPlus11) 4226 return Diag(NameLoc, diag::err_delegating_ctor) 4227 << TInfo->getTypeLoc().getLocalSourceRange(); 4228 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4229 4230 bool InitList = true; 4231 MultiExprArg Args = Init; 4232 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4233 InitList = false; 4234 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4235 } 4236 4237 SourceRange InitRange = Init->getSourceRange(); 4238 // Initialize the object. 4239 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4240 QualType(ClassDecl->getTypeForDecl(), 0)); 4241 InitializationKind Kind = 4242 InitList ? InitializationKind::CreateDirectList( 4243 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4244 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4245 InitRange.getEnd()); 4246 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4247 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4248 Args, nullptr); 4249 if (DelegationInit.isInvalid()) 4250 return true; 4251 4252 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4253 "Delegating constructor with no target?"); 4254 4255 // C++11 [class.base.init]p7: 4256 // The initialization of each base and member constitutes a 4257 // full-expression. 4258 DelegationInit = ActOnFinishFullExpr( 4259 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4260 if (DelegationInit.isInvalid()) 4261 return true; 4262 4263 // If we are in a dependent context, template instantiation will 4264 // perform this type-checking again. Just save the arguments that we 4265 // received in a ParenListExpr. 4266 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4267 // of the information that we have about the base 4268 // initializer. However, deconstructing the ASTs is a dicey process, 4269 // and this approach is far more likely to get the corner cases right. 4270 if (CurContext->isDependentContext()) 4271 DelegationInit = Init; 4272 4273 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4274 DelegationInit.getAs<Expr>(), 4275 InitRange.getEnd()); 4276 } 4277 4278 MemInitResult 4279 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4280 Expr *Init, CXXRecordDecl *ClassDecl, 4281 SourceLocation EllipsisLoc) { 4282 SourceLocation BaseLoc 4283 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4284 4285 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4286 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4287 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4288 4289 // C++ [class.base.init]p2: 4290 // [...] Unless the mem-initializer-id names a nonstatic data 4291 // member of the constructor's class or a direct or virtual base 4292 // of that class, the mem-initializer is ill-formed. A 4293 // mem-initializer-list can initialize a base class using any 4294 // name that denotes that base class type. 4295 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4296 4297 SourceRange InitRange = Init->getSourceRange(); 4298 if (EllipsisLoc.isValid()) { 4299 // This is a pack expansion. 4300 if (!BaseType->containsUnexpandedParameterPack()) { 4301 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4302 << SourceRange(BaseLoc, InitRange.getEnd()); 4303 4304 EllipsisLoc = SourceLocation(); 4305 } 4306 } else { 4307 // Check for any unexpanded parameter packs. 4308 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4309 return true; 4310 4311 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4312 return true; 4313 } 4314 4315 // Check for direct and virtual base classes. 4316 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4317 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4318 if (!Dependent) { 4319 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4320 BaseType)) 4321 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4322 4323 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4324 VirtualBaseSpec); 4325 4326 // C++ [base.class.init]p2: 4327 // Unless the mem-initializer-id names a nonstatic data member of the 4328 // constructor's class or a direct or virtual base of that class, the 4329 // mem-initializer is ill-formed. 4330 if (!DirectBaseSpec && !VirtualBaseSpec) { 4331 // If the class has any dependent bases, then it's possible that 4332 // one of those types will resolve to the same type as 4333 // BaseType. Therefore, just treat this as a dependent base 4334 // class initialization. FIXME: Should we try to check the 4335 // initialization anyway? It seems odd. 4336 if (ClassDecl->hasAnyDependentBases()) 4337 Dependent = true; 4338 else 4339 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4340 << BaseType << Context.getTypeDeclType(ClassDecl) 4341 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4342 } 4343 } 4344 4345 if (Dependent) { 4346 DiscardCleanupsInEvaluationContext(); 4347 4348 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4349 /*IsVirtual=*/false, 4350 InitRange.getBegin(), Init, 4351 InitRange.getEnd(), EllipsisLoc); 4352 } 4353 4354 // C++ [base.class.init]p2: 4355 // If a mem-initializer-id is ambiguous because it designates both 4356 // a direct non-virtual base class and an inherited virtual base 4357 // class, the mem-initializer is ill-formed. 4358 if (DirectBaseSpec && VirtualBaseSpec) 4359 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4360 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4361 4362 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4363 if (!BaseSpec) 4364 BaseSpec = VirtualBaseSpec; 4365 4366 // Initialize the base. 4367 bool InitList = true; 4368 MultiExprArg Args = Init; 4369 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4370 InitList = false; 4371 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4372 } 4373 4374 InitializedEntity BaseEntity = 4375 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4376 InitializationKind Kind = 4377 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4378 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4379 InitRange.getEnd()); 4380 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4381 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4382 if (BaseInit.isInvalid()) 4383 return true; 4384 4385 // C++11 [class.base.init]p7: 4386 // The initialization of each base and member constitutes a 4387 // full-expression. 4388 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4389 /*DiscardedValue*/ false); 4390 if (BaseInit.isInvalid()) 4391 return true; 4392 4393 // If we are in a dependent context, template instantiation will 4394 // perform this type-checking again. Just save the arguments that we 4395 // received in a ParenListExpr. 4396 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4397 // of the information that we have about the base 4398 // initializer. However, deconstructing the ASTs is a dicey process, 4399 // and this approach is far more likely to get the corner cases right. 4400 if (CurContext->isDependentContext()) 4401 BaseInit = Init; 4402 4403 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4404 BaseSpec->isVirtual(), 4405 InitRange.getBegin(), 4406 BaseInit.getAs<Expr>(), 4407 InitRange.getEnd(), EllipsisLoc); 4408 } 4409 4410 // Create a static_cast\<T&&>(expr). 4411 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4412 if (T.isNull()) T = E->getType(); 4413 QualType TargetType = SemaRef.BuildReferenceType( 4414 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4415 SourceLocation ExprLoc = E->getBeginLoc(); 4416 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4417 TargetType, ExprLoc); 4418 4419 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4420 SourceRange(ExprLoc, ExprLoc), 4421 E->getSourceRange()).get(); 4422 } 4423 4424 /// ImplicitInitializerKind - How an implicit base or member initializer should 4425 /// initialize its base or member. 4426 enum ImplicitInitializerKind { 4427 IIK_Default, 4428 IIK_Copy, 4429 IIK_Move, 4430 IIK_Inherit 4431 }; 4432 4433 static bool 4434 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4435 ImplicitInitializerKind ImplicitInitKind, 4436 CXXBaseSpecifier *BaseSpec, 4437 bool IsInheritedVirtualBase, 4438 CXXCtorInitializer *&CXXBaseInit) { 4439 InitializedEntity InitEntity 4440 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4441 IsInheritedVirtualBase); 4442 4443 ExprResult BaseInit; 4444 4445 switch (ImplicitInitKind) { 4446 case IIK_Inherit: 4447 case IIK_Default: { 4448 InitializationKind InitKind 4449 = InitializationKind::CreateDefault(Constructor->getLocation()); 4450 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4451 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4452 break; 4453 } 4454 4455 case IIK_Move: 4456 case IIK_Copy: { 4457 bool Moving = ImplicitInitKind == IIK_Move; 4458 ParmVarDecl *Param = Constructor->getParamDecl(0); 4459 QualType ParamType = Param->getType().getNonReferenceType(); 4460 4461 Expr *CopyCtorArg = 4462 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4463 SourceLocation(), Param, false, 4464 Constructor->getLocation(), ParamType, 4465 VK_LValue, nullptr); 4466 4467 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4468 4469 // Cast to the base class to avoid ambiguities. 4470 QualType ArgTy = 4471 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4472 ParamType.getQualifiers()); 4473 4474 if (Moving) { 4475 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4476 } 4477 4478 CXXCastPath BasePath; 4479 BasePath.push_back(BaseSpec); 4480 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4481 CK_UncheckedDerivedToBase, 4482 Moving ? VK_XValue : VK_LValue, 4483 &BasePath).get(); 4484 4485 InitializationKind InitKind 4486 = InitializationKind::CreateDirect(Constructor->getLocation(), 4487 SourceLocation(), SourceLocation()); 4488 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4489 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4490 break; 4491 } 4492 } 4493 4494 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4495 if (BaseInit.isInvalid()) 4496 return true; 4497 4498 CXXBaseInit = 4499 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4500 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4501 SourceLocation()), 4502 BaseSpec->isVirtual(), 4503 SourceLocation(), 4504 BaseInit.getAs<Expr>(), 4505 SourceLocation(), 4506 SourceLocation()); 4507 4508 return false; 4509 } 4510 4511 static bool RefersToRValueRef(Expr *MemRef) { 4512 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4513 return Referenced->getType()->isRValueReferenceType(); 4514 } 4515 4516 static bool 4517 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4518 ImplicitInitializerKind ImplicitInitKind, 4519 FieldDecl *Field, IndirectFieldDecl *Indirect, 4520 CXXCtorInitializer *&CXXMemberInit) { 4521 if (Field->isInvalidDecl()) 4522 return true; 4523 4524 SourceLocation Loc = Constructor->getLocation(); 4525 4526 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4527 bool Moving = ImplicitInitKind == IIK_Move; 4528 ParmVarDecl *Param = Constructor->getParamDecl(0); 4529 QualType ParamType = Param->getType().getNonReferenceType(); 4530 4531 // Suppress copying zero-width bitfields. 4532 if (Field->isZeroLengthBitField(SemaRef.Context)) 4533 return false; 4534 4535 Expr *MemberExprBase = 4536 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4537 SourceLocation(), Param, false, 4538 Loc, ParamType, VK_LValue, nullptr); 4539 4540 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4541 4542 if (Moving) { 4543 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4544 } 4545 4546 // Build a reference to this field within the parameter. 4547 CXXScopeSpec SS; 4548 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4549 Sema::LookupMemberName); 4550 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4551 : cast<ValueDecl>(Field), AS_public); 4552 MemberLookup.resolveKind(); 4553 ExprResult CtorArg 4554 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4555 ParamType, Loc, 4556 /*IsArrow=*/false, 4557 SS, 4558 /*TemplateKWLoc=*/SourceLocation(), 4559 /*FirstQualifierInScope=*/nullptr, 4560 MemberLookup, 4561 /*TemplateArgs=*/nullptr, 4562 /*S*/nullptr); 4563 if (CtorArg.isInvalid()) 4564 return true; 4565 4566 // C++11 [class.copy]p15: 4567 // - if a member m has rvalue reference type T&&, it is direct-initialized 4568 // with static_cast<T&&>(x.m); 4569 if (RefersToRValueRef(CtorArg.get())) { 4570 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4571 } 4572 4573 InitializedEntity Entity = 4574 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4575 /*Implicit*/ true) 4576 : InitializedEntity::InitializeMember(Field, nullptr, 4577 /*Implicit*/ true); 4578 4579 // Direct-initialize to use the copy constructor. 4580 InitializationKind InitKind = 4581 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4582 4583 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4584 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4585 ExprResult MemberInit = 4586 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4587 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4588 if (MemberInit.isInvalid()) 4589 return true; 4590 4591 if (Indirect) 4592 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4593 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4594 else 4595 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4596 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4597 return false; 4598 } 4599 4600 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4601 "Unhandled implicit init kind!"); 4602 4603 QualType FieldBaseElementType = 4604 SemaRef.Context.getBaseElementType(Field->getType()); 4605 4606 if (FieldBaseElementType->isRecordType()) { 4607 InitializedEntity InitEntity = 4608 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4609 /*Implicit*/ true) 4610 : InitializedEntity::InitializeMember(Field, nullptr, 4611 /*Implicit*/ true); 4612 InitializationKind InitKind = 4613 InitializationKind::CreateDefault(Loc); 4614 4615 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4616 ExprResult MemberInit = 4617 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4618 4619 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4620 if (MemberInit.isInvalid()) 4621 return true; 4622 4623 if (Indirect) 4624 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4625 Indirect, Loc, 4626 Loc, 4627 MemberInit.get(), 4628 Loc); 4629 else 4630 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4631 Field, Loc, Loc, 4632 MemberInit.get(), 4633 Loc); 4634 return false; 4635 } 4636 4637 if (!Field->getParent()->isUnion()) { 4638 if (FieldBaseElementType->isReferenceType()) { 4639 SemaRef.Diag(Constructor->getLocation(), 4640 diag::err_uninitialized_member_in_ctor) 4641 << (int)Constructor->isImplicit() 4642 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4643 << 0 << Field->getDeclName(); 4644 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4645 return true; 4646 } 4647 4648 if (FieldBaseElementType.isConstQualified()) { 4649 SemaRef.Diag(Constructor->getLocation(), 4650 diag::err_uninitialized_member_in_ctor) 4651 << (int)Constructor->isImplicit() 4652 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4653 << 1 << Field->getDeclName(); 4654 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4655 return true; 4656 } 4657 } 4658 4659 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4660 // ARC and Weak: 4661 // Default-initialize Objective-C pointers to NULL. 4662 CXXMemberInit 4663 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4664 Loc, Loc, 4665 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4666 Loc); 4667 return false; 4668 } 4669 4670 // Nothing to initialize. 4671 CXXMemberInit = nullptr; 4672 return false; 4673 } 4674 4675 namespace { 4676 struct BaseAndFieldInfo { 4677 Sema &S; 4678 CXXConstructorDecl *Ctor; 4679 bool AnyErrorsInInits; 4680 ImplicitInitializerKind IIK; 4681 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4682 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4683 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4684 4685 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4686 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4687 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4688 if (Ctor->getInheritedConstructor()) 4689 IIK = IIK_Inherit; 4690 else if (Generated && Ctor->isCopyConstructor()) 4691 IIK = IIK_Copy; 4692 else if (Generated && Ctor->isMoveConstructor()) 4693 IIK = IIK_Move; 4694 else 4695 IIK = IIK_Default; 4696 } 4697 4698 bool isImplicitCopyOrMove() const { 4699 switch (IIK) { 4700 case IIK_Copy: 4701 case IIK_Move: 4702 return true; 4703 4704 case IIK_Default: 4705 case IIK_Inherit: 4706 return false; 4707 } 4708 4709 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4710 } 4711 4712 bool addFieldInitializer(CXXCtorInitializer *Init) { 4713 AllToInit.push_back(Init); 4714 4715 // Check whether this initializer makes the field "used". 4716 if (Init->getInit()->HasSideEffects(S.Context)) 4717 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4718 4719 return false; 4720 } 4721 4722 bool isInactiveUnionMember(FieldDecl *Field) { 4723 RecordDecl *Record = Field->getParent(); 4724 if (!Record->isUnion()) 4725 return false; 4726 4727 if (FieldDecl *Active = 4728 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4729 return Active != Field->getCanonicalDecl(); 4730 4731 // In an implicit copy or move constructor, ignore any in-class initializer. 4732 if (isImplicitCopyOrMove()) 4733 return true; 4734 4735 // If there's no explicit initialization, the field is active only if it 4736 // has an in-class initializer... 4737 if (Field->hasInClassInitializer()) 4738 return false; 4739 // ... or it's an anonymous struct or union whose class has an in-class 4740 // initializer. 4741 if (!Field->isAnonymousStructOrUnion()) 4742 return true; 4743 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4744 return !FieldRD->hasInClassInitializer(); 4745 } 4746 4747 /// Determine whether the given field is, or is within, a union member 4748 /// that is inactive (because there was an initializer given for a different 4749 /// member of the union, or because the union was not initialized at all). 4750 bool isWithinInactiveUnionMember(FieldDecl *Field, 4751 IndirectFieldDecl *Indirect) { 4752 if (!Indirect) 4753 return isInactiveUnionMember(Field); 4754 4755 for (auto *C : Indirect->chain()) { 4756 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4757 if (Field && isInactiveUnionMember(Field)) 4758 return true; 4759 } 4760 return false; 4761 } 4762 }; 4763 } 4764 4765 /// Determine whether the given type is an incomplete or zero-lenfgth 4766 /// array type. 4767 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4768 if (T->isIncompleteArrayType()) 4769 return true; 4770 4771 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4772 if (!ArrayT->getSize()) 4773 return true; 4774 4775 T = ArrayT->getElementType(); 4776 } 4777 4778 return false; 4779 } 4780 4781 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4782 FieldDecl *Field, 4783 IndirectFieldDecl *Indirect = nullptr) { 4784 if (Field->isInvalidDecl()) 4785 return false; 4786 4787 // Overwhelmingly common case: we have a direct initializer for this field. 4788 if (CXXCtorInitializer *Init = 4789 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4790 return Info.addFieldInitializer(Init); 4791 4792 // C++11 [class.base.init]p8: 4793 // if the entity is a non-static data member that has a 4794 // brace-or-equal-initializer and either 4795 // -- the constructor's class is a union and no other variant member of that 4796 // union is designated by a mem-initializer-id or 4797 // -- the constructor's class is not a union, and, if the entity is a member 4798 // of an anonymous union, no other member of that union is designated by 4799 // a mem-initializer-id, 4800 // the entity is initialized as specified in [dcl.init]. 4801 // 4802 // We also apply the same rules to handle anonymous structs within anonymous 4803 // unions. 4804 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4805 return false; 4806 4807 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4808 ExprResult DIE = 4809 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4810 if (DIE.isInvalid()) 4811 return true; 4812 4813 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4814 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4815 4816 CXXCtorInitializer *Init; 4817 if (Indirect) 4818 Init = new (SemaRef.Context) 4819 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4820 SourceLocation(), DIE.get(), SourceLocation()); 4821 else 4822 Init = new (SemaRef.Context) 4823 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4824 SourceLocation(), DIE.get(), SourceLocation()); 4825 return Info.addFieldInitializer(Init); 4826 } 4827 4828 // Don't initialize incomplete or zero-length arrays. 4829 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4830 return false; 4831 4832 // Don't try to build an implicit initializer if there were semantic 4833 // errors in any of the initializers (and therefore we might be 4834 // missing some that the user actually wrote). 4835 if (Info.AnyErrorsInInits) 4836 return false; 4837 4838 CXXCtorInitializer *Init = nullptr; 4839 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4840 Indirect, Init)) 4841 return true; 4842 4843 if (!Init) 4844 return false; 4845 4846 return Info.addFieldInitializer(Init); 4847 } 4848 4849 bool 4850 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4851 CXXCtorInitializer *Initializer) { 4852 assert(Initializer->isDelegatingInitializer()); 4853 Constructor->setNumCtorInitializers(1); 4854 CXXCtorInitializer **initializer = 4855 new (Context) CXXCtorInitializer*[1]; 4856 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4857 Constructor->setCtorInitializers(initializer); 4858 4859 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4860 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4861 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4862 } 4863 4864 DelegatingCtorDecls.push_back(Constructor); 4865 4866 DiagnoseUninitializedFields(*this, Constructor); 4867 4868 return false; 4869 } 4870 4871 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4872 ArrayRef<CXXCtorInitializer *> Initializers) { 4873 if (Constructor->isDependentContext()) { 4874 // Just store the initializers as written, they will be checked during 4875 // instantiation. 4876 if (!Initializers.empty()) { 4877 Constructor->setNumCtorInitializers(Initializers.size()); 4878 CXXCtorInitializer **baseOrMemberInitializers = 4879 new (Context) CXXCtorInitializer*[Initializers.size()]; 4880 memcpy(baseOrMemberInitializers, Initializers.data(), 4881 Initializers.size() * sizeof(CXXCtorInitializer*)); 4882 Constructor->setCtorInitializers(baseOrMemberInitializers); 4883 } 4884 4885 // Let template instantiation know whether we had errors. 4886 if (AnyErrors) 4887 Constructor->setInvalidDecl(); 4888 4889 return false; 4890 } 4891 4892 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4893 4894 // We need to build the initializer AST according to order of construction 4895 // and not what user specified in the Initializers list. 4896 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4897 if (!ClassDecl) 4898 return true; 4899 4900 bool HadError = false; 4901 4902 for (unsigned i = 0; i < Initializers.size(); i++) { 4903 CXXCtorInitializer *Member = Initializers[i]; 4904 4905 if (Member->isBaseInitializer()) 4906 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4907 else { 4908 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4909 4910 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4911 for (auto *C : F->chain()) { 4912 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4913 if (FD && FD->getParent()->isUnion()) 4914 Info.ActiveUnionMember.insert(std::make_pair( 4915 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4916 } 4917 } else if (FieldDecl *FD = Member->getMember()) { 4918 if (FD->getParent()->isUnion()) 4919 Info.ActiveUnionMember.insert(std::make_pair( 4920 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4921 } 4922 } 4923 } 4924 4925 // Keep track of the direct virtual bases. 4926 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4927 for (auto &I : ClassDecl->bases()) { 4928 if (I.isVirtual()) 4929 DirectVBases.insert(&I); 4930 } 4931 4932 // Push virtual bases before others. 4933 for (auto &VBase : ClassDecl->vbases()) { 4934 if (CXXCtorInitializer *Value 4935 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4936 // [class.base.init]p7, per DR257: 4937 // A mem-initializer where the mem-initializer-id names a virtual base 4938 // class is ignored during execution of a constructor of any class that 4939 // is not the most derived class. 4940 if (ClassDecl->isAbstract()) { 4941 // FIXME: Provide a fixit to remove the base specifier. This requires 4942 // tracking the location of the associated comma for a base specifier. 4943 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4944 << VBase.getType() << ClassDecl; 4945 DiagnoseAbstractType(ClassDecl); 4946 } 4947 4948 Info.AllToInit.push_back(Value); 4949 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4950 // [class.base.init]p8, per DR257: 4951 // If a given [...] base class is not named by a mem-initializer-id 4952 // [...] and the entity is not a virtual base class of an abstract 4953 // class, then [...] the entity is default-initialized. 4954 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4955 CXXCtorInitializer *CXXBaseInit; 4956 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4957 &VBase, IsInheritedVirtualBase, 4958 CXXBaseInit)) { 4959 HadError = true; 4960 continue; 4961 } 4962 4963 Info.AllToInit.push_back(CXXBaseInit); 4964 } 4965 } 4966 4967 // Non-virtual bases. 4968 for (auto &Base : ClassDecl->bases()) { 4969 // Virtuals are in the virtual base list and already constructed. 4970 if (Base.isVirtual()) 4971 continue; 4972 4973 if (CXXCtorInitializer *Value 4974 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4975 Info.AllToInit.push_back(Value); 4976 } else if (!AnyErrors) { 4977 CXXCtorInitializer *CXXBaseInit; 4978 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4979 &Base, /*IsInheritedVirtualBase=*/false, 4980 CXXBaseInit)) { 4981 HadError = true; 4982 continue; 4983 } 4984 4985 Info.AllToInit.push_back(CXXBaseInit); 4986 } 4987 } 4988 4989 // Fields. 4990 for (auto *Mem : ClassDecl->decls()) { 4991 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4992 // C++ [class.bit]p2: 4993 // A declaration for a bit-field that omits the identifier declares an 4994 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4995 // initialized. 4996 if (F->isUnnamedBitfield()) 4997 continue; 4998 4999 // If we're not generating the implicit copy/move constructor, then we'll 5000 // handle anonymous struct/union fields based on their individual 5001 // indirect fields. 5002 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5003 continue; 5004 5005 if (CollectFieldInitializer(*this, Info, F)) 5006 HadError = true; 5007 continue; 5008 } 5009 5010 // Beyond this point, we only consider default initialization. 5011 if (Info.isImplicitCopyOrMove()) 5012 continue; 5013 5014 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5015 if (F->getType()->isIncompleteArrayType()) { 5016 assert(ClassDecl->hasFlexibleArrayMember() && 5017 "Incomplete array type is not valid"); 5018 continue; 5019 } 5020 5021 // Initialize each field of an anonymous struct individually. 5022 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5023 HadError = true; 5024 5025 continue; 5026 } 5027 } 5028 5029 unsigned NumInitializers = Info.AllToInit.size(); 5030 if (NumInitializers > 0) { 5031 Constructor->setNumCtorInitializers(NumInitializers); 5032 CXXCtorInitializer **baseOrMemberInitializers = 5033 new (Context) CXXCtorInitializer*[NumInitializers]; 5034 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5035 NumInitializers * sizeof(CXXCtorInitializer*)); 5036 Constructor->setCtorInitializers(baseOrMemberInitializers); 5037 5038 // Constructors implicitly reference the base and member 5039 // destructors. 5040 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5041 Constructor->getParent()); 5042 } 5043 5044 return HadError; 5045 } 5046 5047 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5048 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5049 const RecordDecl *RD = RT->getDecl(); 5050 if (RD->isAnonymousStructOrUnion()) { 5051 for (auto *Field : RD->fields()) 5052 PopulateKeysForFields(Field, IdealInits); 5053 return; 5054 } 5055 } 5056 IdealInits.push_back(Field->getCanonicalDecl()); 5057 } 5058 5059 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5060 return Context.getCanonicalType(BaseType).getTypePtr(); 5061 } 5062 5063 static const void *GetKeyForMember(ASTContext &Context, 5064 CXXCtorInitializer *Member) { 5065 if (!Member->isAnyMemberInitializer()) 5066 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5067 5068 return Member->getAnyMember()->getCanonicalDecl(); 5069 } 5070 5071 static void DiagnoseBaseOrMemInitializerOrder( 5072 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5073 ArrayRef<CXXCtorInitializer *> Inits) { 5074 if (Constructor->getDeclContext()->isDependentContext()) 5075 return; 5076 5077 // Don't check initializers order unless the warning is enabled at the 5078 // location of at least one initializer. 5079 bool ShouldCheckOrder = false; 5080 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5081 CXXCtorInitializer *Init = Inits[InitIndex]; 5082 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5083 Init->getSourceLocation())) { 5084 ShouldCheckOrder = true; 5085 break; 5086 } 5087 } 5088 if (!ShouldCheckOrder) 5089 return; 5090 5091 // Build the list of bases and members in the order that they'll 5092 // actually be initialized. The explicit initializers should be in 5093 // this same order but may be missing things. 5094 SmallVector<const void*, 32> IdealInitKeys; 5095 5096 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5097 5098 // 1. Virtual bases. 5099 for (const auto &VBase : ClassDecl->vbases()) 5100 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5101 5102 // 2. Non-virtual bases. 5103 for (const auto &Base : ClassDecl->bases()) { 5104 if (Base.isVirtual()) 5105 continue; 5106 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5107 } 5108 5109 // 3. Direct fields. 5110 for (auto *Field : ClassDecl->fields()) { 5111 if (Field->isUnnamedBitfield()) 5112 continue; 5113 5114 PopulateKeysForFields(Field, IdealInitKeys); 5115 } 5116 5117 unsigned NumIdealInits = IdealInitKeys.size(); 5118 unsigned IdealIndex = 0; 5119 5120 CXXCtorInitializer *PrevInit = nullptr; 5121 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5122 CXXCtorInitializer *Init = Inits[InitIndex]; 5123 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5124 5125 // Scan forward to try to find this initializer in the idealized 5126 // initializers list. 5127 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5128 if (InitKey == IdealInitKeys[IdealIndex]) 5129 break; 5130 5131 // If we didn't find this initializer, it must be because we 5132 // scanned past it on a previous iteration. That can only 5133 // happen if we're out of order; emit a warning. 5134 if (IdealIndex == NumIdealInits && PrevInit) { 5135 Sema::SemaDiagnosticBuilder D = 5136 SemaRef.Diag(PrevInit->getSourceLocation(), 5137 diag::warn_initializer_out_of_order); 5138 5139 if (PrevInit->isAnyMemberInitializer()) 5140 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5141 else 5142 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5143 5144 if (Init->isAnyMemberInitializer()) 5145 D << 0 << Init->getAnyMember()->getDeclName(); 5146 else 5147 D << 1 << Init->getTypeSourceInfo()->getType(); 5148 5149 // Move back to the initializer's location in the ideal list. 5150 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5151 if (InitKey == IdealInitKeys[IdealIndex]) 5152 break; 5153 5154 assert(IdealIndex < NumIdealInits && 5155 "initializer not found in initializer list"); 5156 } 5157 5158 PrevInit = Init; 5159 } 5160 } 5161 5162 namespace { 5163 bool CheckRedundantInit(Sema &S, 5164 CXXCtorInitializer *Init, 5165 CXXCtorInitializer *&PrevInit) { 5166 if (!PrevInit) { 5167 PrevInit = Init; 5168 return false; 5169 } 5170 5171 if (FieldDecl *Field = Init->getAnyMember()) 5172 S.Diag(Init->getSourceLocation(), 5173 diag::err_multiple_mem_initialization) 5174 << Field->getDeclName() 5175 << Init->getSourceRange(); 5176 else { 5177 const Type *BaseClass = Init->getBaseClass(); 5178 assert(BaseClass && "neither field nor base"); 5179 S.Diag(Init->getSourceLocation(), 5180 diag::err_multiple_base_initialization) 5181 << QualType(BaseClass, 0) 5182 << Init->getSourceRange(); 5183 } 5184 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5185 << 0 << PrevInit->getSourceRange(); 5186 5187 return true; 5188 } 5189 5190 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5191 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5192 5193 bool CheckRedundantUnionInit(Sema &S, 5194 CXXCtorInitializer *Init, 5195 RedundantUnionMap &Unions) { 5196 FieldDecl *Field = Init->getAnyMember(); 5197 RecordDecl *Parent = Field->getParent(); 5198 NamedDecl *Child = Field; 5199 5200 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5201 if (Parent->isUnion()) { 5202 UnionEntry &En = Unions[Parent]; 5203 if (En.first && En.first != Child) { 5204 S.Diag(Init->getSourceLocation(), 5205 diag::err_multiple_mem_union_initialization) 5206 << Field->getDeclName() 5207 << Init->getSourceRange(); 5208 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5209 << 0 << En.second->getSourceRange(); 5210 return true; 5211 } 5212 if (!En.first) { 5213 En.first = Child; 5214 En.second = Init; 5215 } 5216 if (!Parent->isAnonymousStructOrUnion()) 5217 return false; 5218 } 5219 5220 Child = Parent; 5221 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5222 } 5223 5224 return false; 5225 } 5226 } 5227 5228 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5229 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5230 SourceLocation ColonLoc, 5231 ArrayRef<CXXCtorInitializer*> MemInits, 5232 bool AnyErrors) { 5233 if (!ConstructorDecl) 5234 return; 5235 5236 AdjustDeclIfTemplate(ConstructorDecl); 5237 5238 CXXConstructorDecl *Constructor 5239 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5240 5241 if (!Constructor) { 5242 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5243 return; 5244 } 5245 5246 // Mapping for the duplicate initializers check. 5247 // For member initializers, this is keyed with a FieldDecl*. 5248 // For base initializers, this is keyed with a Type*. 5249 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5250 5251 // Mapping for the inconsistent anonymous-union initializers check. 5252 RedundantUnionMap MemberUnions; 5253 5254 bool HadError = false; 5255 for (unsigned i = 0; i < MemInits.size(); i++) { 5256 CXXCtorInitializer *Init = MemInits[i]; 5257 5258 // Set the source order index. 5259 Init->setSourceOrder(i); 5260 5261 if (Init->isAnyMemberInitializer()) { 5262 const void *Key = GetKeyForMember(Context, Init); 5263 if (CheckRedundantInit(*this, Init, Members[Key]) || 5264 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5265 HadError = true; 5266 } else if (Init->isBaseInitializer()) { 5267 const void *Key = GetKeyForMember(Context, Init); 5268 if (CheckRedundantInit(*this, Init, Members[Key])) 5269 HadError = true; 5270 } else { 5271 assert(Init->isDelegatingInitializer()); 5272 // This must be the only initializer 5273 if (MemInits.size() != 1) { 5274 Diag(Init->getSourceLocation(), 5275 diag::err_delegating_initializer_alone) 5276 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5277 // We will treat this as being the only initializer. 5278 } 5279 SetDelegatingInitializer(Constructor, MemInits[i]); 5280 // Return immediately as the initializer is set. 5281 return; 5282 } 5283 } 5284 5285 if (HadError) 5286 return; 5287 5288 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5289 5290 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5291 5292 DiagnoseUninitializedFields(*this, Constructor); 5293 } 5294 5295 void 5296 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5297 CXXRecordDecl *ClassDecl) { 5298 // Ignore dependent contexts. Also ignore unions, since their members never 5299 // have destructors implicitly called. 5300 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5301 return; 5302 5303 // FIXME: all the access-control diagnostics are positioned on the 5304 // field/base declaration. That's probably good; that said, the 5305 // user might reasonably want to know why the destructor is being 5306 // emitted, and we currently don't say. 5307 5308 // Non-static data members. 5309 for (auto *Field : ClassDecl->fields()) { 5310 if (Field->isInvalidDecl()) 5311 continue; 5312 5313 // Don't destroy incomplete or zero-length arrays. 5314 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5315 continue; 5316 5317 QualType FieldType = Context.getBaseElementType(Field->getType()); 5318 5319 const RecordType* RT = FieldType->getAs<RecordType>(); 5320 if (!RT) 5321 continue; 5322 5323 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5324 if (FieldClassDecl->isInvalidDecl()) 5325 continue; 5326 if (FieldClassDecl->hasIrrelevantDestructor()) 5327 continue; 5328 // The destructor for an implicit anonymous union member is never invoked. 5329 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5330 continue; 5331 5332 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5333 assert(Dtor && "No dtor found for FieldClassDecl!"); 5334 CheckDestructorAccess(Field->getLocation(), Dtor, 5335 PDiag(diag::err_access_dtor_field) 5336 << Field->getDeclName() 5337 << FieldType); 5338 5339 MarkFunctionReferenced(Location, Dtor); 5340 DiagnoseUseOfDecl(Dtor, Location); 5341 } 5342 5343 // We only potentially invoke the destructors of potentially constructed 5344 // subobjects. 5345 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5346 5347 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5348 5349 // Bases. 5350 for (const auto &Base : ClassDecl->bases()) { 5351 // Bases are always records in a well-formed non-dependent class. 5352 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5353 5354 // Remember direct virtual bases. 5355 if (Base.isVirtual()) { 5356 if (!VisitVirtualBases) 5357 continue; 5358 DirectVirtualBases.insert(RT); 5359 } 5360 5361 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5362 // If our base class is invalid, we probably can't get its dtor anyway. 5363 if (BaseClassDecl->isInvalidDecl()) 5364 continue; 5365 if (BaseClassDecl->hasIrrelevantDestructor()) 5366 continue; 5367 5368 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5369 assert(Dtor && "No dtor found for BaseClassDecl!"); 5370 5371 // FIXME: caret should be on the start of the class name 5372 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5373 PDiag(diag::err_access_dtor_base) 5374 << Base.getType() << Base.getSourceRange(), 5375 Context.getTypeDeclType(ClassDecl)); 5376 5377 MarkFunctionReferenced(Location, Dtor); 5378 DiagnoseUseOfDecl(Dtor, Location); 5379 } 5380 5381 if (!VisitVirtualBases) 5382 return; 5383 5384 // Virtual bases. 5385 for (const auto &VBase : ClassDecl->vbases()) { 5386 // Bases are always records in a well-formed non-dependent class. 5387 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5388 5389 // Ignore direct virtual bases. 5390 if (DirectVirtualBases.count(RT)) 5391 continue; 5392 5393 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5394 // If our base class is invalid, we probably can't get its dtor anyway. 5395 if (BaseClassDecl->isInvalidDecl()) 5396 continue; 5397 if (BaseClassDecl->hasIrrelevantDestructor()) 5398 continue; 5399 5400 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5401 assert(Dtor && "No dtor found for BaseClassDecl!"); 5402 if (CheckDestructorAccess( 5403 ClassDecl->getLocation(), Dtor, 5404 PDiag(diag::err_access_dtor_vbase) 5405 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5406 Context.getTypeDeclType(ClassDecl)) == 5407 AR_accessible) { 5408 CheckDerivedToBaseConversion( 5409 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5410 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5411 SourceRange(), DeclarationName(), nullptr); 5412 } 5413 5414 MarkFunctionReferenced(Location, Dtor); 5415 DiagnoseUseOfDecl(Dtor, Location); 5416 } 5417 } 5418 5419 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5420 if (!CDtorDecl) 5421 return; 5422 5423 if (CXXConstructorDecl *Constructor 5424 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5425 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5426 DiagnoseUninitializedFields(*this, Constructor); 5427 } 5428 } 5429 5430 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5431 if (!getLangOpts().CPlusPlus) 5432 return false; 5433 5434 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5435 if (!RD) 5436 return false; 5437 5438 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5439 // class template specialization here, but doing so breaks a lot of code. 5440 5441 // We can't answer whether something is abstract until it has a 5442 // definition. If it's currently being defined, we'll walk back 5443 // over all the declarations when we have a full definition. 5444 const CXXRecordDecl *Def = RD->getDefinition(); 5445 if (!Def || Def->isBeingDefined()) 5446 return false; 5447 5448 return RD->isAbstract(); 5449 } 5450 5451 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5452 TypeDiagnoser &Diagnoser) { 5453 if (!isAbstractType(Loc, T)) 5454 return false; 5455 5456 T = Context.getBaseElementType(T); 5457 Diagnoser.diagnose(*this, Loc, T); 5458 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5459 return true; 5460 } 5461 5462 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5463 // Check if we've already emitted the list of pure virtual functions 5464 // for this class. 5465 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5466 return; 5467 5468 // If the diagnostic is suppressed, don't emit the notes. We're only 5469 // going to emit them once, so try to attach them to a diagnostic we're 5470 // actually going to show. 5471 if (Diags.isLastDiagnosticIgnored()) 5472 return; 5473 5474 CXXFinalOverriderMap FinalOverriders; 5475 RD->getFinalOverriders(FinalOverriders); 5476 5477 // Keep a set of seen pure methods so we won't diagnose the same method 5478 // more than once. 5479 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5480 5481 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5482 MEnd = FinalOverriders.end(); 5483 M != MEnd; 5484 ++M) { 5485 for (OverridingMethods::iterator SO = M->second.begin(), 5486 SOEnd = M->second.end(); 5487 SO != SOEnd; ++SO) { 5488 // C++ [class.abstract]p4: 5489 // A class is abstract if it contains or inherits at least one 5490 // pure virtual function for which the final overrider is pure 5491 // virtual. 5492 5493 // 5494 if (SO->second.size() != 1) 5495 continue; 5496 5497 if (!SO->second.front().Method->isPure()) 5498 continue; 5499 5500 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5501 continue; 5502 5503 Diag(SO->second.front().Method->getLocation(), 5504 diag::note_pure_virtual_function) 5505 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5506 } 5507 } 5508 5509 if (!PureVirtualClassDiagSet) 5510 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5511 PureVirtualClassDiagSet->insert(RD); 5512 } 5513 5514 namespace { 5515 struct AbstractUsageInfo { 5516 Sema &S; 5517 CXXRecordDecl *Record; 5518 CanQualType AbstractType; 5519 bool Invalid; 5520 5521 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5522 : S(S), Record(Record), 5523 AbstractType(S.Context.getCanonicalType( 5524 S.Context.getTypeDeclType(Record))), 5525 Invalid(false) {} 5526 5527 void DiagnoseAbstractType() { 5528 if (Invalid) return; 5529 S.DiagnoseAbstractType(Record); 5530 Invalid = true; 5531 } 5532 5533 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5534 }; 5535 5536 struct CheckAbstractUsage { 5537 AbstractUsageInfo &Info; 5538 const NamedDecl *Ctx; 5539 5540 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5541 : Info(Info), Ctx(Ctx) {} 5542 5543 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5544 switch (TL.getTypeLocClass()) { 5545 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5546 #define TYPELOC(CLASS, PARENT) \ 5547 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5548 #include "clang/AST/TypeLocNodes.def" 5549 } 5550 } 5551 5552 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5553 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5554 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5555 if (!TL.getParam(I)) 5556 continue; 5557 5558 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5559 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5560 } 5561 } 5562 5563 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5564 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5565 } 5566 5567 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5568 // Visit the type parameters from a permissive context. 5569 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5570 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5571 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5572 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5573 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5574 // TODO: other template argument types? 5575 } 5576 } 5577 5578 // Visit pointee types from a permissive context. 5579 #define CheckPolymorphic(Type) \ 5580 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5581 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5582 } 5583 CheckPolymorphic(PointerTypeLoc) 5584 CheckPolymorphic(ReferenceTypeLoc) 5585 CheckPolymorphic(MemberPointerTypeLoc) 5586 CheckPolymorphic(BlockPointerTypeLoc) 5587 CheckPolymorphic(AtomicTypeLoc) 5588 5589 /// Handle all the types we haven't given a more specific 5590 /// implementation for above. 5591 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5592 // Every other kind of type that we haven't called out already 5593 // that has an inner type is either (1) sugar or (2) contains that 5594 // inner type in some way as a subobject. 5595 if (TypeLoc Next = TL.getNextTypeLoc()) 5596 return Visit(Next, Sel); 5597 5598 // If there's no inner type and we're in a permissive context, 5599 // don't diagnose. 5600 if (Sel == Sema::AbstractNone) return; 5601 5602 // Check whether the type matches the abstract type. 5603 QualType T = TL.getType(); 5604 if (T->isArrayType()) { 5605 Sel = Sema::AbstractArrayType; 5606 T = Info.S.Context.getBaseElementType(T); 5607 } 5608 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5609 if (CT != Info.AbstractType) return; 5610 5611 // It matched; do some magic. 5612 if (Sel == Sema::AbstractArrayType) { 5613 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5614 << T << TL.getSourceRange(); 5615 } else { 5616 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5617 << Sel << T << TL.getSourceRange(); 5618 } 5619 Info.DiagnoseAbstractType(); 5620 } 5621 }; 5622 5623 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5624 Sema::AbstractDiagSelID Sel) { 5625 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5626 } 5627 5628 } 5629 5630 /// Check for invalid uses of an abstract type in a method declaration. 5631 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5632 CXXMethodDecl *MD) { 5633 // No need to do the check on definitions, which require that 5634 // the return/param types be complete. 5635 if (MD->doesThisDeclarationHaveABody()) 5636 return; 5637 5638 // For safety's sake, just ignore it if we don't have type source 5639 // information. This should never happen for non-implicit methods, 5640 // but... 5641 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5642 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5643 } 5644 5645 /// Check for invalid uses of an abstract type within a class definition. 5646 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5647 CXXRecordDecl *RD) { 5648 for (auto *D : RD->decls()) { 5649 if (D->isImplicit()) continue; 5650 5651 // Methods and method templates. 5652 if (isa<CXXMethodDecl>(D)) { 5653 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5654 } else if (isa<FunctionTemplateDecl>(D)) { 5655 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5656 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5657 5658 // Fields and static variables. 5659 } else if (isa<FieldDecl>(D)) { 5660 FieldDecl *FD = cast<FieldDecl>(D); 5661 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5662 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5663 } else if (isa<VarDecl>(D)) { 5664 VarDecl *VD = cast<VarDecl>(D); 5665 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5666 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5667 5668 // Nested classes and class templates. 5669 } else if (isa<CXXRecordDecl>(D)) { 5670 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5671 } else if (isa<ClassTemplateDecl>(D)) { 5672 CheckAbstractClassUsage(Info, 5673 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5674 } 5675 } 5676 } 5677 5678 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5679 Attr *ClassAttr = getDLLAttr(Class); 5680 if (!ClassAttr) 5681 return; 5682 5683 assert(ClassAttr->getKind() == attr::DLLExport); 5684 5685 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5686 5687 if (TSK == TSK_ExplicitInstantiationDeclaration) 5688 // Don't go any further if this is just an explicit instantiation 5689 // declaration. 5690 return; 5691 5692 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5693 S.MarkVTableUsed(Class->getLocation(), Class, true); 5694 5695 for (Decl *Member : Class->decls()) { 5696 // Defined static variables that are members of an exported base 5697 // class must be marked export too. 5698 auto *VD = dyn_cast<VarDecl>(Member); 5699 if (VD && Member->getAttr<DLLExportAttr>() && 5700 VD->getStorageClass() == SC_Static && 5701 TSK == TSK_ImplicitInstantiation) 5702 S.MarkVariableReferenced(VD->getLocation(), VD); 5703 5704 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5705 if (!MD) 5706 continue; 5707 5708 if (Member->getAttr<DLLExportAttr>()) { 5709 if (MD->isUserProvided()) { 5710 // Instantiate non-default class member functions ... 5711 5712 // .. except for certain kinds of template specializations. 5713 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5714 continue; 5715 5716 S.MarkFunctionReferenced(Class->getLocation(), MD); 5717 5718 // The function will be passed to the consumer when its definition is 5719 // encountered. 5720 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5721 MD->isCopyAssignmentOperator() || 5722 MD->isMoveAssignmentOperator()) { 5723 // Synthesize and instantiate non-trivial implicit methods, explicitly 5724 // defaulted methods, and the copy and move assignment operators. The 5725 // latter are exported even if they are trivial, because the address of 5726 // an operator can be taken and should compare equal across libraries. 5727 DiagnosticErrorTrap Trap(S.Diags); 5728 S.MarkFunctionReferenced(Class->getLocation(), MD); 5729 if (Trap.hasErrorOccurred()) { 5730 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5731 << Class << !S.getLangOpts().CPlusPlus11; 5732 break; 5733 } 5734 5735 // There is no later point when we will see the definition of this 5736 // function, so pass it to the consumer now. 5737 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5738 } 5739 } 5740 } 5741 } 5742 5743 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5744 CXXRecordDecl *Class) { 5745 // Only the MS ABI has default constructor closures, so we don't need to do 5746 // this semantic checking anywhere else. 5747 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5748 return; 5749 5750 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5751 for (Decl *Member : Class->decls()) { 5752 // Look for exported default constructors. 5753 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5754 if (!CD || !CD->isDefaultConstructor()) 5755 continue; 5756 auto *Attr = CD->getAttr<DLLExportAttr>(); 5757 if (!Attr) 5758 continue; 5759 5760 // If the class is non-dependent, mark the default arguments as ODR-used so 5761 // that we can properly codegen the constructor closure. 5762 if (!Class->isDependentContext()) { 5763 for (ParmVarDecl *PD : CD->parameters()) { 5764 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5765 S.DiscardCleanupsInEvaluationContext(); 5766 } 5767 } 5768 5769 if (LastExportedDefaultCtor) { 5770 S.Diag(LastExportedDefaultCtor->getLocation(), 5771 diag::err_attribute_dll_ambiguous_default_ctor) 5772 << Class; 5773 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5774 << CD->getDeclName(); 5775 return; 5776 } 5777 LastExportedDefaultCtor = CD; 5778 } 5779 } 5780 5781 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5782 // Mark any compiler-generated routines with the implicit code_seg attribute. 5783 for (auto *Method : Class->methods()) { 5784 if (Method->isUserProvided()) 5785 continue; 5786 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5787 Method->addAttr(A); 5788 } 5789 } 5790 5791 /// Check class-level dllimport/dllexport attribute. 5792 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5793 Attr *ClassAttr = getDLLAttr(Class); 5794 5795 // MSVC inherits DLL attributes to partial class template specializations. 5796 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5797 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5798 if (Attr *TemplateAttr = 5799 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5800 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5801 A->setInherited(true); 5802 ClassAttr = A; 5803 } 5804 } 5805 } 5806 5807 if (!ClassAttr) 5808 return; 5809 5810 if (!Class->isExternallyVisible()) { 5811 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5812 << Class << ClassAttr; 5813 return; 5814 } 5815 5816 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5817 !ClassAttr->isInherited()) { 5818 // Diagnose dll attributes on members of class with dll attribute. 5819 for (Decl *Member : Class->decls()) { 5820 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5821 continue; 5822 InheritableAttr *MemberAttr = getDLLAttr(Member); 5823 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5824 continue; 5825 5826 Diag(MemberAttr->getLocation(), 5827 diag::err_attribute_dll_member_of_dll_class) 5828 << MemberAttr << ClassAttr; 5829 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5830 Member->setInvalidDecl(); 5831 } 5832 } 5833 5834 if (Class->getDescribedClassTemplate()) 5835 // Don't inherit dll attribute until the template is instantiated. 5836 return; 5837 5838 // The class is either imported or exported. 5839 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5840 5841 // Check if this was a dllimport attribute propagated from a derived class to 5842 // a base class template specialization. We don't apply these attributes to 5843 // static data members. 5844 const bool PropagatedImport = 5845 !ClassExported && 5846 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5847 5848 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5849 5850 // Ignore explicit dllexport on explicit class template instantiation 5851 // declarations, except in MinGW mode. 5852 if (ClassExported && !ClassAttr->isInherited() && 5853 TSK == TSK_ExplicitInstantiationDeclaration && 5854 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 5855 Class->dropAttr<DLLExportAttr>(); 5856 return; 5857 } 5858 5859 // Force declaration of implicit members so they can inherit the attribute. 5860 ForceDeclarationOfImplicitMembers(Class); 5861 5862 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5863 // seem to be true in practice? 5864 5865 for (Decl *Member : Class->decls()) { 5866 VarDecl *VD = dyn_cast<VarDecl>(Member); 5867 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5868 5869 // Only methods and static fields inherit the attributes. 5870 if (!VD && !MD) 5871 continue; 5872 5873 if (MD) { 5874 // Don't process deleted methods. 5875 if (MD->isDeleted()) 5876 continue; 5877 5878 if (MD->isInlined()) { 5879 // MinGW does not import or export inline methods. But do it for 5880 // template instantiations. 5881 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5882 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 5883 TSK != TSK_ExplicitInstantiationDeclaration && 5884 TSK != TSK_ExplicitInstantiationDefinition) 5885 continue; 5886 5887 // MSVC versions before 2015 don't export the move assignment operators 5888 // and move constructor, so don't attempt to import/export them if 5889 // we have a definition. 5890 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5891 if ((MD->isMoveAssignmentOperator() || 5892 (Ctor && Ctor->isMoveConstructor())) && 5893 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5894 continue; 5895 5896 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5897 // operator is exported anyway. 5898 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5899 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5900 continue; 5901 } 5902 } 5903 5904 // Don't apply dllimport attributes to static data members of class template 5905 // instantiations when the attribute is propagated from a derived class. 5906 if (VD && PropagatedImport) 5907 continue; 5908 5909 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5910 continue; 5911 5912 if (!getDLLAttr(Member)) { 5913 InheritableAttr *NewAttr = nullptr; 5914 5915 // Do not export/import inline function when -fno-dllexport-inlines is 5916 // passed. But add attribute for later local static var check. 5917 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 5918 TSK != TSK_ExplicitInstantiationDeclaration && 5919 TSK != TSK_ExplicitInstantiationDefinition) { 5920 if (ClassExported) { 5921 NewAttr = ::new (getASTContext()) 5922 DLLExportStaticLocalAttr(ClassAttr->getRange(), 5923 getASTContext(), 5924 ClassAttr->getSpellingListIndex()); 5925 } else { 5926 NewAttr = ::new (getASTContext()) 5927 DLLImportStaticLocalAttr(ClassAttr->getRange(), 5928 getASTContext(), 5929 ClassAttr->getSpellingListIndex()); 5930 } 5931 } else { 5932 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5933 } 5934 5935 NewAttr->setInherited(true); 5936 Member->addAttr(NewAttr); 5937 5938 if (MD) { 5939 // Propagate DLLAttr to friend re-declarations of MD that have already 5940 // been constructed. 5941 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5942 FD = FD->getPreviousDecl()) { 5943 if (FD->getFriendObjectKind() == Decl::FOK_None) 5944 continue; 5945 assert(!getDLLAttr(FD) && 5946 "friend re-decl should not already have a DLLAttr"); 5947 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5948 NewAttr->setInherited(true); 5949 FD->addAttr(NewAttr); 5950 } 5951 } 5952 } 5953 } 5954 5955 if (ClassExported) 5956 DelayedDllExportClasses.push_back(Class); 5957 } 5958 5959 /// Perform propagation of DLL attributes from a derived class to a 5960 /// templated base class for MS compatibility. 5961 void Sema::propagateDLLAttrToBaseClassTemplate( 5962 CXXRecordDecl *Class, Attr *ClassAttr, 5963 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5964 if (getDLLAttr( 5965 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5966 // If the base class template has a DLL attribute, don't try to change it. 5967 return; 5968 } 5969 5970 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5971 if (!getDLLAttr(BaseTemplateSpec) && 5972 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5973 TSK == TSK_ImplicitInstantiation)) { 5974 // The template hasn't been instantiated yet (or it has, but only as an 5975 // explicit instantiation declaration or implicit instantiation, which means 5976 // we haven't codegenned any members yet), so propagate the attribute. 5977 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5978 NewAttr->setInherited(true); 5979 BaseTemplateSpec->addAttr(NewAttr); 5980 5981 // If this was an import, mark that we propagated it from a derived class to 5982 // a base class template specialization. 5983 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 5984 ImportAttr->setPropagatedToBaseTemplate(); 5985 5986 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5987 // needs to be run again to work see the new attribute. Otherwise this will 5988 // get run whenever the template is instantiated. 5989 if (TSK != TSK_Undeclared) 5990 checkClassLevelDLLAttribute(BaseTemplateSpec); 5991 5992 return; 5993 } 5994 5995 if (getDLLAttr(BaseTemplateSpec)) { 5996 // The template has already been specialized or instantiated with an 5997 // attribute, explicitly or through propagation. We should not try to change 5998 // it. 5999 return; 6000 } 6001 6002 // The template was previously instantiated or explicitly specialized without 6003 // a dll attribute, It's too late for us to add an attribute, so warn that 6004 // this is unsupported. 6005 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6006 << BaseTemplateSpec->isExplicitSpecialization(); 6007 Diag(ClassAttr->getLocation(), diag::note_attribute); 6008 if (BaseTemplateSpec->isExplicitSpecialization()) { 6009 Diag(BaseTemplateSpec->getLocation(), 6010 diag::note_template_class_explicit_specialization_was_here) 6011 << BaseTemplateSpec; 6012 } else { 6013 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6014 diag::note_template_class_instantiation_was_here) 6015 << BaseTemplateSpec; 6016 } 6017 } 6018 6019 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 6020 SourceLocation DefaultLoc) { 6021 switch (S.getSpecialMember(MD)) { 6022 case Sema::CXXDefaultConstructor: 6023 S.DefineImplicitDefaultConstructor(DefaultLoc, 6024 cast<CXXConstructorDecl>(MD)); 6025 break; 6026 case Sema::CXXCopyConstructor: 6027 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6028 break; 6029 case Sema::CXXCopyAssignment: 6030 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 6031 break; 6032 case Sema::CXXDestructor: 6033 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 6034 break; 6035 case Sema::CXXMoveConstructor: 6036 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6037 break; 6038 case Sema::CXXMoveAssignment: 6039 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 6040 break; 6041 case Sema::CXXInvalid: 6042 llvm_unreachable("Invalid special member."); 6043 } 6044 } 6045 6046 /// Determine whether a type is permitted to be passed or returned in 6047 /// registers, per C++ [class.temporary]p3. 6048 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6049 TargetInfo::CallingConvKind CCK) { 6050 if (D->isDependentType() || D->isInvalidDecl()) 6051 return false; 6052 6053 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6054 // The PS4 platform ABI follows the behavior of Clang 3.2. 6055 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6056 return !D->hasNonTrivialDestructorForCall() && 6057 !D->hasNonTrivialCopyConstructorForCall(); 6058 6059 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6060 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6061 bool DtorIsTrivialForCall = false; 6062 6063 // If a class has at least one non-deleted, trivial copy constructor, it 6064 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6065 // 6066 // Note: This permits classes with non-trivial copy or move ctors to be 6067 // passed in registers, so long as they *also* have a trivial copy ctor, 6068 // which is non-conforming. 6069 if (D->needsImplicitCopyConstructor()) { 6070 if (!D->defaultedCopyConstructorIsDeleted()) { 6071 if (D->hasTrivialCopyConstructor()) 6072 CopyCtorIsTrivial = true; 6073 if (D->hasTrivialCopyConstructorForCall()) 6074 CopyCtorIsTrivialForCall = true; 6075 } 6076 } else { 6077 for (const CXXConstructorDecl *CD : D->ctors()) { 6078 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6079 if (CD->isTrivial()) 6080 CopyCtorIsTrivial = true; 6081 if (CD->isTrivialForCall()) 6082 CopyCtorIsTrivialForCall = true; 6083 } 6084 } 6085 } 6086 6087 if (D->needsImplicitDestructor()) { 6088 if (!D->defaultedDestructorIsDeleted() && 6089 D->hasTrivialDestructorForCall()) 6090 DtorIsTrivialForCall = true; 6091 } else if (const auto *DD = D->getDestructor()) { 6092 if (!DD->isDeleted() && DD->isTrivialForCall()) 6093 DtorIsTrivialForCall = true; 6094 } 6095 6096 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6097 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6098 return true; 6099 6100 // If a class has a destructor, we'd really like to pass it indirectly 6101 // because it allows us to elide copies. Unfortunately, MSVC makes that 6102 // impossible for small types, which it will pass in a single register or 6103 // stack slot. Most objects with dtors are large-ish, so handle that early. 6104 // We can't call out all large objects as being indirect because there are 6105 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6106 // how we pass large POD types. 6107 6108 // Note: This permits small classes with nontrivial destructors to be 6109 // passed in registers, which is non-conforming. 6110 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6111 uint64_t TypeSize = isAArch64 ? 128 : 64; 6112 6113 if (CopyCtorIsTrivial && 6114 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6115 return true; 6116 return false; 6117 } 6118 6119 // Per C++ [class.temporary]p3, the relevant condition is: 6120 // each copy constructor, move constructor, and destructor of X is 6121 // either trivial or deleted, and X has at least one non-deleted copy 6122 // or move constructor 6123 bool HasNonDeletedCopyOrMove = false; 6124 6125 if (D->needsImplicitCopyConstructor() && 6126 !D->defaultedCopyConstructorIsDeleted()) { 6127 if (!D->hasTrivialCopyConstructorForCall()) 6128 return false; 6129 HasNonDeletedCopyOrMove = true; 6130 } 6131 6132 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6133 !D->defaultedMoveConstructorIsDeleted()) { 6134 if (!D->hasTrivialMoveConstructorForCall()) 6135 return false; 6136 HasNonDeletedCopyOrMove = true; 6137 } 6138 6139 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6140 !D->hasTrivialDestructorForCall()) 6141 return false; 6142 6143 for (const CXXMethodDecl *MD : D->methods()) { 6144 if (MD->isDeleted()) 6145 continue; 6146 6147 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6148 if (CD && CD->isCopyOrMoveConstructor()) 6149 HasNonDeletedCopyOrMove = true; 6150 else if (!isa<CXXDestructorDecl>(MD)) 6151 continue; 6152 6153 if (!MD->isTrivialForCall()) 6154 return false; 6155 } 6156 6157 return HasNonDeletedCopyOrMove; 6158 } 6159 6160 /// Perform semantic checks on a class definition that has been 6161 /// completing, introducing implicitly-declared members, checking for 6162 /// abstract types, etc. 6163 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 6164 if (!Record) 6165 return; 6166 6167 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6168 AbstractUsageInfo Info(*this, Record); 6169 CheckAbstractClassUsage(Info, Record); 6170 } 6171 6172 // If this is not an aggregate type and has no user-declared constructor, 6173 // complain about any non-static data members of reference or const scalar 6174 // type, since they will never get initializers. 6175 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6176 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6177 !Record->isLambda()) { 6178 bool Complained = false; 6179 for (const auto *F : Record->fields()) { 6180 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6181 continue; 6182 6183 if (F->getType()->isReferenceType() || 6184 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6185 if (!Complained) { 6186 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6187 << Record->getTagKind() << Record; 6188 Complained = true; 6189 } 6190 6191 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6192 << F->getType()->isReferenceType() 6193 << F->getDeclName(); 6194 } 6195 } 6196 } 6197 6198 if (Record->getIdentifier()) { 6199 // C++ [class.mem]p13: 6200 // If T is the name of a class, then each of the following shall have a 6201 // name different from T: 6202 // - every member of every anonymous union that is a member of class T. 6203 // 6204 // C++ [class.mem]p14: 6205 // In addition, if class T has a user-declared constructor (12.1), every 6206 // non-static data member of class T shall have a name different from T. 6207 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6208 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6209 ++I) { 6210 NamedDecl *D = (*I)->getUnderlyingDecl(); 6211 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6212 Record->hasUserDeclaredConstructor()) || 6213 isa<IndirectFieldDecl>(D)) { 6214 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6215 << D->getDeclName(); 6216 break; 6217 } 6218 } 6219 } 6220 6221 // Warn if the class has virtual methods but non-virtual public destructor. 6222 if (Record->isPolymorphic() && !Record->isDependentType()) { 6223 CXXDestructorDecl *dtor = Record->getDestructor(); 6224 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6225 !Record->hasAttr<FinalAttr>()) 6226 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6227 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6228 } 6229 6230 if (Record->isAbstract()) { 6231 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6232 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6233 << FA->isSpelledAsSealed(); 6234 DiagnoseAbstractType(Record); 6235 } 6236 } 6237 6238 // See if trivial_abi has to be dropped. 6239 if (Record->hasAttr<TrivialABIAttr>()) 6240 checkIllFormedTrivialABIStruct(*Record); 6241 6242 // Set HasTrivialSpecialMemberForCall if the record has attribute 6243 // "trivial_abi". 6244 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6245 6246 if (HasTrivialABI) 6247 Record->setHasTrivialSpecialMemberForCall(); 6248 6249 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6250 // Check whether the explicitly-defaulted special members are valid. 6251 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6252 CheckExplicitlyDefaultedSpecialMember(M); 6253 6254 // For an explicitly defaulted or deleted special member, we defer 6255 // determining triviality until the class is complete. That time is now! 6256 CXXSpecialMember CSM = getSpecialMember(M); 6257 if (!M->isImplicit() && !M->isUserProvided()) { 6258 if (CSM != CXXInvalid) { 6259 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6260 // Inform the class that we've finished declaring this member. 6261 Record->finishedDefaultedOrDeletedMember(M); 6262 M->setTrivialForCall( 6263 HasTrivialABI || 6264 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6265 Record->setTrivialForCallFlags(M); 6266 } 6267 } 6268 6269 // Set triviality for the purpose of calls if this is a user-provided 6270 // copy/move constructor or destructor. 6271 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6272 CSM == CXXDestructor) && M->isUserProvided()) { 6273 M->setTrivialForCall(HasTrivialABI); 6274 Record->setTrivialForCallFlags(M); 6275 } 6276 6277 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6278 M->hasAttr<DLLExportAttr>()) { 6279 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6280 M->isTrivial() && 6281 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6282 CSM == CXXDestructor)) 6283 M->dropAttr<DLLExportAttr>(); 6284 6285 if (M->hasAttr<DLLExportAttr>()) { 6286 // Define after any fields with in-class initializers have been parsed. 6287 DelayedDllExportMemberFunctions.push_back(M); 6288 } 6289 } 6290 }; 6291 6292 bool HasMethodWithOverrideControl = false, 6293 HasOverridingMethodWithoutOverrideControl = false; 6294 if (!Record->isDependentType()) { 6295 // Check the destructor before any other member function. We need to 6296 // determine whether it's trivial in order to determine whether the claas 6297 // type is a literal type, which is a prerequisite for determining whether 6298 // other special member functions are valid and whether they're implicitly 6299 // 'constexpr'. 6300 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6301 CompleteMemberFunction(Dtor); 6302 6303 for (auto *M : Record->methods()) { 6304 // See if a method overloads virtual methods in a base 6305 // class without overriding any. 6306 if (!M->isStatic()) 6307 DiagnoseHiddenVirtualMethods(M); 6308 if (M->hasAttr<OverrideAttr>()) 6309 HasMethodWithOverrideControl = true; 6310 else if (M->size_overridden_methods() > 0) 6311 HasOverridingMethodWithoutOverrideControl = true; 6312 6313 if (!isa<CXXDestructorDecl>(M)) 6314 CompleteMemberFunction(M); 6315 } 6316 } 6317 6318 if (HasMethodWithOverrideControl && 6319 HasOverridingMethodWithoutOverrideControl) { 6320 // At least one method has the 'override' control declared. 6321 // Diagnose all other overridden methods which do not have 'override' specified on them. 6322 for (auto *M : Record->methods()) 6323 DiagnoseAbsenceOfOverrideControl(M); 6324 } 6325 6326 // ms_struct is a request to use the same ABI rules as MSVC. Check 6327 // whether this class uses any C++ features that are implemented 6328 // completely differently in MSVC, and if so, emit a diagnostic. 6329 // That diagnostic defaults to an error, but we allow projects to 6330 // map it down to a warning (or ignore it). It's a fairly common 6331 // practice among users of the ms_struct pragma to mass-annotate 6332 // headers, sweeping up a bunch of types that the project doesn't 6333 // really rely on MSVC-compatible layout for. We must therefore 6334 // support "ms_struct except for C++ stuff" as a secondary ABI. 6335 if (Record->isMsStruct(Context) && 6336 (Record->isPolymorphic() || Record->getNumBases())) { 6337 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6338 } 6339 6340 checkClassLevelDLLAttribute(Record); 6341 checkClassLevelCodeSegAttribute(Record); 6342 6343 bool ClangABICompat4 = 6344 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6345 TargetInfo::CallingConvKind CCK = 6346 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6347 bool CanPass = canPassInRegisters(*this, Record, CCK); 6348 6349 // Do not change ArgPassingRestrictions if it has already been set to 6350 // APK_CanNeverPassInRegs. 6351 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6352 Record->setArgPassingRestrictions(CanPass 6353 ? RecordDecl::APK_CanPassInRegs 6354 : RecordDecl::APK_CannotPassInRegs); 6355 6356 // If canPassInRegisters returns true despite the record having a non-trivial 6357 // destructor, the record is destructed in the callee. This happens only when 6358 // the record or one of its subobjects has a field annotated with trivial_abi 6359 // or a field qualified with ObjC __strong/__weak. 6360 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6361 Record->setParamDestroyedInCallee(true); 6362 else if (Record->hasNonTrivialDestructor()) 6363 Record->setParamDestroyedInCallee(CanPass); 6364 6365 if (getLangOpts().ForceEmitVTables) { 6366 // If we want to emit all the vtables, we need to mark it as used. This 6367 // is especially required for cases like vtable assumption loads. 6368 MarkVTableUsed(Record->getInnerLocStart(), Record); 6369 } 6370 } 6371 6372 /// Look up the special member function that would be called by a special 6373 /// member function for a subobject of class type. 6374 /// 6375 /// \param Class The class type of the subobject. 6376 /// \param CSM The kind of special member function. 6377 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6378 /// \param ConstRHS True if this is a copy operation with a const object 6379 /// on its RHS, that is, if the argument to the outer special member 6380 /// function is 'const' and this is not a field marked 'mutable'. 6381 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6382 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6383 unsigned FieldQuals, bool ConstRHS) { 6384 unsigned LHSQuals = 0; 6385 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6386 LHSQuals = FieldQuals; 6387 6388 unsigned RHSQuals = FieldQuals; 6389 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6390 RHSQuals = 0; 6391 else if (ConstRHS) 6392 RHSQuals |= Qualifiers::Const; 6393 6394 return S.LookupSpecialMember(Class, CSM, 6395 RHSQuals & Qualifiers::Const, 6396 RHSQuals & Qualifiers::Volatile, 6397 false, 6398 LHSQuals & Qualifiers::Const, 6399 LHSQuals & Qualifiers::Volatile); 6400 } 6401 6402 class Sema::InheritedConstructorInfo { 6403 Sema &S; 6404 SourceLocation UseLoc; 6405 6406 /// A mapping from the base classes through which the constructor was 6407 /// inherited to the using shadow declaration in that base class (or a null 6408 /// pointer if the constructor was declared in that base class). 6409 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6410 InheritedFromBases; 6411 6412 public: 6413 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6414 ConstructorUsingShadowDecl *Shadow) 6415 : S(S), UseLoc(UseLoc) { 6416 bool DiagnosedMultipleConstructedBases = false; 6417 CXXRecordDecl *ConstructedBase = nullptr; 6418 UsingDecl *ConstructedBaseUsing = nullptr; 6419 6420 // Find the set of such base class subobjects and check that there's a 6421 // unique constructed subobject. 6422 for (auto *D : Shadow->redecls()) { 6423 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6424 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6425 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6426 6427 InheritedFromBases.insert( 6428 std::make_pair(DNominatedBase->getCanonicalDecl(), 6429 DShadow->getNominatedBaseClassShadowDecl())); 6430 if (DShadow->constructsVirtualBase()) 6431 InheritedFromBases.insert( 6432 std::make_pair(DConstructedBase->getCanonicalDecl(), 6433 DShadow->getConstructedBaseClassShadowDecl())); 6434 else 6435 assert(DNominatedBase == DConstructedBase); 6436 6437 // [class.inhctor.init]p2: 6438 // If the constructor was inherited from multiple base class subobjects 6439 // of type B, the program is ill-formed. 6440 if (!ConstructedBase) { 6441 ConstructedBase = DConstructedBase; 6442 ConstructedBaseUsing = D->getUsingDecl(); 6443 } else if (ConstructedBase != DConstructedBase && 6444 !Shadow->isInvalidDecl()) { 6445 if (!DiagnosedMultipleConstructedBases) { 6446 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6447 << Shadow->getTargetDecl(); 6448 S.Diag(ConstructedBaseUsing->getLocation(), 6449 diag::note_ambiguous_inherited_constructor_using) 6450 << ConstructedBase; 6451 DiagnosedMultipleConstructedBases = true; 6452 } 6453 S.Diag(D->getUsingDecl()->getLocation(), 6454 diag::note_ambiguous_inherited_constructor_using) 6455 << DConstructedBase; 6456 } 6457 } 6458 6459 if (DiagnosedMultipleConstructedBases) 6460 Shadow->setInvalidDecl(); 6461 } 6462 6463 /// Find the constructor to use for inherited construction of a base class, 6464 /// and whether that base class constructor inherits the constructor from a 6465 /// virtual base class (in which case it won't actually invoke it). 6466 std::pair<CXXConstructorDecl *, bool> 6467 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6468 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6469 if (It == InheritedFromBases.end()) 6470 return std::make_pair(nullptr, false); 6471 6472 // This is an intermediary class. 6473 if (It->second) 6474 return std::make_pair( 6475 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6476 It->second->constructsVirtualBase()); 6477 6478 // This is the base class from which the constructor was inherited. 6479 return std::make_pair(Ctor, false); 6480 } 6481 }; 6482 6483 /// Is the special member function which would be selected to perform the 6484 /// specified operation on the specified class type a constexpr constructor? 6485 static bool 6486 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6487 Sema::CXXSpecialMember CSM, unsigned Quals, 6488 bool ConstRHS, 6489 CXXConstructorDecl *InheritedCtor = nullptr, 6490 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6491 // If we're inheriting a constructor, see if we need to call it for this base 6492 // class. 6493 if (InheritedCtor) { 6494 assert(CSM == Sema::CXXDefaultConstructor); 6495 auto BaseCtor = 6496 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6497 if (BaseCtor) 6498 return BaseCtor->isConstexpr(); 6499 } 6500 6501 if (CSM == Sema::CXXDefaultConstructor) 6502 return ClassDecl->hasConstexprDefaultConstructor(); 6503 6504 Sema::SpecialMemberOverloadResult SMOR = 6505 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6506 if (!SMOR.getMethod()) 6507 // A constructor we wouldn't select can't be "involved in initializing" 6508 // anything. 6509 return true; 6510 return SMOR.getMethod()->isConstexpr(); 6511 } 6512 6513 /// Determine whether the specified special member function would be constexpr 6514 /// if it were implicitly defined. 6515 static bool defaultedSpecialMemberIsConstexpr( 6516 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6517 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6518 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6519 if (!S.getLangOpts().CPlusPlus11) 6520 return false; 6521 6522 // C++11 [dcl.constexpr]p4: 6523 // In the definition of a constexpr constructor [...] 6524 bool Ctor = true; 6525 switch (CSM) { 6526 case Sema::CXXDefaultConstructor: 6527 if (Inherited) 6528 break; 6529 // Since default constructor lookup is essentially trivial (and cannot 6530 // involve, for instance, template instantiation), we compute whether a 6531 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6532 // 6533 // This is important for performance; we need to know whether the default 6534 // constructor is constexpr to determine whether the type is a literal type. 6535 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6536 6537 case Sema::CXXCopyConstructor: 6538 case Sema::CXXMoveConstructor: 6539 // For copy or move constructors, we need to perform overload resolution. 6540 break; 6541 6542 case Sema::CXXCopyAssignment: 6543 case Sema::CXXMoveAssignment: 6544 if (!S.getLangOpts().CPlusPlus14) 6545 return false; 6546 // In C++1y, we need to perform overload resolution. 6547 Ctor = false; 6548 break; 6549 6550 case Sema::CXXDestructor: 6551 case Sema::CXXInvalid: 6552 return false; 6553 } 6554 6555 // -- if the class is a non-empty union, or for each non-empty anonymous 6556 // union member of a non-union class, exactly one non-static data member 6557 // shall be initialized; [DR1359] 6558 // 6559 // If we squint, this is guaranteed, since exactly one non-static data member 6560 // will be initialized (if the constructor isn't deleted), we just don't know 6561 // which one. 6562 if (Ctor && ClassDecl->isUnion()) 6563 return CSM == Sema::CXXDefaultConstructor 6564 ? ClassDecl->hasInClassInitializer() || 6565 !ClassDecl->hasVariantMembers() 6566 : true; 6567 6568 // -- the class shall not have any virtual base classes; 6569 if (Ctor && ClassDecl->getNumVBases()) 6570 return false; 6571 6572 // C++1y [class.copy]p26: 6573 // -- [the class] is a literal type, and 6574 if (!Ctor && !ClassDecl->isLiteral()) 6575 return false; 6576 6577 // -- every constructor involved in initializing [...] base class 6578 // sub-objects shall be a constexpr constructor; 6579 // -- the assignment operator selected to copy/move each direct base 6580 // class is a constexpr function, and 6581 for (const auto &B : ClassDecl->bases()) { 6582 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6583 if (!BaseType) continue; 6584 6585 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6586 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6587 InheritedCtor, Inherited)) 6588 return false; 6589 } 6590 6591 // -- every constructor involved in initializing non-static data members 6592 // [...] shall be a constexpr constructor; 6593 // -- every non-static data member and base class sub-object shall be 6594 // initialized 6595 // -- for each non-static data member of X that is of class type (or array 6596 // thereof), the assignment operator selected to copy/move that member is 6597 // a constexpr function 6598 for (const auto *F : ClassDecl->fields()) { 6599 if (F->isInvalidDecl()) 6600 continue; 6601 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6602 continue; 6603 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6604 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6605 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6606 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6607 BaseType.getCVRQualifiers(), 6608 ConstArg && !F->isMutable())) 6609 return false; 6610 } else if (CSM == Sema::CXXDefaultConstructor) { 6611 return false; 6612 } 6613 } 6614 6615 // All OK, it's constexpr! 6616 return true; 6617 } 6618 6619 static Sema::ImplicitExceptionSpecification 6620 ComputeDefaultedSpecialMemberExceptionSpec( 6621 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6622 Sema::InheritedConstructorInfo *ICI); 6623 6624 static Sema::ImplicitExceptionSpecification 6625 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6626 auto CSM = S.getSpecialMember(MD); 6627 if (CSM != Sema::CXXInvalid) 6628 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6629 6630 auto *CD = cast<CXXConstructorDecl>(MD); 6631 assert(CD->getInheritedConstructor() && 6632 "only special members have implicit exception specs"); 6633 Sema::InheritedConstructorInfo ICI( 6634 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6635 return ComputeDefaultedSpecialMemberExceptionSpec( 6636 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6637 } 6638 6639 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6640 CXXMethodDecl *MD) { 6641 FunctionProtoType::ExtProtoInfo EPI; 6642 6643 // Build an exception specification pointing back at this member. 6644 EPI.ExceptionSpec.Type = EST_Unevaluated; 6645 EPI.ExceptionSpec.SourceDecl = MD; 6646 6647 // Set the calling convention to the default for C++ instance methods. 6648 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6649 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6650 /*IsCXXMethod=*/true)); 6651 return EPI; 6652 } 6653 6654 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6655 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6656 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6657 return; 6658 6659 // Evaluate the exception specification. 6660 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6661 auto ESI = IES.getExceptionSpec(); 6662 6663 // Update the type of the special member to use it. 6664 UpdateExceptionSpec(MD, ESI); 6665 6666 // A user-provided destructor can be defined outside the class. When that 6667 // happens, be sure to update the exception specification on both 6668 // declarations. 6669 const FunctionProtoType *CanonicalFPT = 6670 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6671 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6672 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6673 } 6674 6675 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6676 CXXRecordDecl *RD = MD->getParent(); 6677 CXXSpecialMember CSM = getSpecialMember(MD); 6678 6679 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6680 "not an explicitly-defaulted special member"); 6681 6682 // Whether this was the first-declared instance of the constructor. 6683 // This affects whether we implicitly add an exception spec and constexpr. 6684 bool First = MD == MD->getCanonicalDecl(); 6685 6686 bool HadError = false; 6687 6688 // C++11 [dcl.fct.def.default]p1: 6689 // A function that is explicitly defaulted shall 6690 // -- be a special member function (checked elsewhere), 6691 // -- have the same type (except for ref-qualifiers, and except that a 6692 // copy operation can take a non-const reference) as an implicit 6693 // declaration, and 6694 // -- not have default arguments. 6695 // C++2a changes the second bullet to instead delete the function if it's 6696 // defaulted on its first declaration, unless it's "an assignment operator, 6697 // and its return type differs or its parameter type is not a reference". 6698 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6699 bool ShouldDeleteForTypeMismatch = false; 6700 unsigned ExpectedParams = 1; 6701 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6702 ExpectedParams = 0; 6703 if (MD->getNumParams() != ExpectedParams) { 6704 // This checks for default arguments: a copy or move constructor with a 6705 // default argument is classified as a default constructor, and assignment 6706 // operations and destructors can't have default arguments. 6707 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6708 << CSM << MD->getSourceRange(); 6709 HadError = true; 6710 } else if (MD->isVariadic()) { 6711 if (DeleteOnTypeMismatch) 6712 ShouldDeleteForTypeMismatch = true; 6713 else { 6714 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6715 << CSM << MD->getSourceRange(); 6716 HadError = true; 6717 } 6718 } 6719 6720 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6721 6722 bool CanHaveConstParam = false; 6723 if (CSM == CXXCopyConstructor) 6724 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6725 else if (CSM == CXXCopyAssignment) 6726 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6727 6728 QualType ReturnType = Context.VoidTy; 6729 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6730 // Check for return type matching. 6731 ReturnType = Type->getReturnType(); 6732 6733 QualType DeclType = Context.getTypeDeclType(RD); 6734 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 6735 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6736 6737 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6738 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6739 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6740 HadError = true; 6741 } 6742 6743 // A defaulted special member cannot have cv-qualifiers. 6744 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 6745 if (DeleteOnTypeMismatch) 6746 ShouldDeleteForTypeMismatch = true; 6747 else { 6748 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6749 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6750 HadError = true; 6751 } 6752 } 6753 } 6754 6755 // Check for parameter type matching. 6756 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6757 bool HasConstParam = false; 6758 if (ExpectedParams && ArgType->isReferenceType()) { 6759 // Argument must be reference to possibly-const T. 6760 QualType ReferentType = ArgType->getPointeeType(); 6761 HasConstParam = ReferentType.isConstQualified(); 6762 6763 if (ReferentType.isVolatileQualified()) { 6764 if (DeleteOnTypeMismatch) 6765 ShouldDeleteForTypeMismatch = true; 6766 else { 6767 Diag(MD->getLocation(), 6768 diag::err_defaulted_special_member_volatile_param) << CSM; 6769 HadError = true; 6770 } 6771 } 6772 6773 if (HasConstParam && !CanHaveConstParam) { 6774 if (DeleteOnTypeMismatch) 6775 ShouldDeleteForTypeMismatch = true; 6776 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6777 Diag(MD->getLocation(), 6778 diag::err_defaulted_special_member_copy_const_param) 6779 << (CSM == CXXCopyAssignment); 6780 // FIXME: Explain why this special member can't be const. 6781 HadError = true; 6782 } else { 6783 Diag(MD->getLocation(), 6784 diag::err_defaulted_special_member_move_const_param) 6785 << (CSM == CXXMoveAssignment); 6786 HadError = true; 6787 } 6788 } 6789 } else if (ExpectedParams) { 6790 // A copy assignment operator can take its argument by value, but a 6791 // defaulted one cannot. 6792 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6793 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6794 HadError = true; 6795 } 6796 6797 // C++11 [dcl.fct.def.default]p2: 6798 // An explicitly-defaulted function may be declared constexpr only if it 6799 // would have been implicitly declared as constexpr, 6800 // Do not apply this rule to members of class templates, since core issue 1358 6801 // makes such functions always instantiate to constexpr functions. For 6802 // functions which cannot be constexpr (for non-constructors in C++11 and for 6803 // destructors in C++1y), this is checked elsewhere. 6804 // 6805 // FIXME: This should not apply if the member is deleted. 6806 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6807 HasConstParam); 6808 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6809 : isa<CXXConstructorDecl>(MD)) && 6810 MD->isConstexpr() && !Constexpr && 6811 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6812 Diag(MD->getBeginLoc(), MD->isConsteval() 6813 ? diag::err_incorrect_defaulted_consteval 6814 : diag::err_incorrect_defaulted_constexpr) 6815 << CSM; 6816 // FIXME: Explain why the special member can't be constexpr. 6817 HadError = true; 6818 } 6819 6820 if (First) { 6821 // C++2a [dcl.fct.def.default]p3: 6822 // If a function is explicitly defaulted on its first declaration, it is 6823 // implicitly considered to be constexpr if the implicit declaration 6824 // would be. 6825 MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified); 6826 6827 if (!Type->hasExceptionSpec()) { 6828 // C++2a [except.spec]p3: 6829 // If a declaration of a function does not have a noexcept-specifier 6830 // [and] is defaulted on its first declaration, [...] the exception 6831 // specification is as specified below 6832 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6833 EPI.ExceptionSpec.Type = EST_Unevaluated; 6834 EPI.ExceptionSpec.SourceDecl = MD; 6835 MD->setType(Context.getFunctionType(ReturnType, 6836 llvm::makeArrayRef(&ArgType, 6837 ExpectedParams), 6838 EPI)); 6839 } 6840 } 6841 6842 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 6843 if (First) { 6844 SetDeclDeleted(MD, MD->getLocation()); 6845 if (!inTemplateInstantiation() && !HadError) { 6846 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 6847 if (ShouldDeleteForTypeMismatch) { 6848 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 6849 } else { 6850 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6851 } 6852 } 6853 if (ShouldDeleteForTypeMismatch && !HadError) { 6854 Diag(MD->getLocation(), 6855 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 6856 } 6857 } else { 6858 // C++11 [dcl.fct.def.default]p4: 6859 // [For a] user-provided explicitly-defaulted function [...] if such a 6860 // function is implicitly defined as deleted, the program is ill-formed. 6861 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6862 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 6863 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6864 HadError = true; 6865 } 6866 } 6867 6868 if (HadError) 6869 MD->setInvalidDecl(); 6870 } 6871 6872 void Sema::CheckDelayedMemberExceptionSpecs() { 6873 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 6874 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 6875 6876 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 6877 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 6878 6879 // Perform any deferred checking of exception specifications for virtual 6880 // destructors. 6881 for (auto &Check : Overriding) 6882 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6883 6884 // Perform any deferred checking of exception specifications for befriended 6885 // special members. 6886 for (auto &Check : Equivalent) 6887 CheckEquivalentExceptionSpec(Check.second, Check.first); 6888 } 6889 6890 namespace { 6891 /// CRTP base class for visiting operations performed by a special member 6892 /// function (or inherited constructor). 6893 template<typename Derived> 6894 struct SpecialMemberVisitor { 6895 Sema &S; 6896 CXXMethodDecl *MD; 6897 Sema::CXXSpecialMember CSM; 6898 Sema::InheritedConstructorInfo *ICI; 6899 6900 // Properties of the special member, computed for convenience. 6901 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6902 6903 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6904 Sema::InheritedConstructorInfo *ICI) 6905 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6906 switch (CSM) { 6907 case Sema::CXXDefaultConstructor: 6908 case Sema::CXXCopyConstructor: 6909 case Sema::CXXMoveConstructor: 6910 IsConstructor = true; 6911 break; 6912 case Sema::CXXCopyAssignment: 6913 case Sema::CXXMoveAssignment: 6914 IsAssignment = true; 6915 break; 6916 case Sema::CXXDestructor: 6917 break; 6918 case Sema::CXXInvalid: 6919 llvm_unreachable("invalid special member kind"); 6920 } 6921 6922 if (MD->getNumParams()) { 6923 if (const ReferenceType *RT = 6924 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6925 ConstArg = RT->getPointeeType().isConstQualified(); 6926 } 6927 } 6928 6929 Derived &getDerived() { return static_cast<Derived&>(*this); } 6930 6931 /// Is this a "move" special member? 6932 bool isMove() const { 6933 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6934 } 6935 6936 /// Look up the corresponding special member in the given class. 6937 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6938 unsigned Quals, bool IsMutable) { 6939 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6940 ConstArg && !IsMutable); 6941 } 6942 6943 /// Look up the constructor for the specified base class to see if it's 6944 /// overridden due to this being an inherited constructor. 6945 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6946 if (!ICI) 6947 return {}; 6948 assert(CSM == Sema::CXXDefaultConstructor); 6949 auto *BaseCtor = 6950 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6951 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6952 return MD; 6953 return {}; 6954 } 6955 6956 /// A base or member subobject. 6957 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6958 6959 /// Get the location to use for a subobject in diagnostics. 6960 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6961 // FIXME: For an indirect virtual base, the direct base leading to 6962 // the indirect virtual base would be a more useful choice. 6963 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6964 return B->getBaseTypeLoc(); 6965 else 6966 return Subobj.get<FieldDecl*>()->getLocation(); 6967 } 6968 6969 enum BasesToVisit { 6970 /// Visit all non-virtual (direct) bases. 6971 VisitNonVirtualBases, 6972 /// Visit all direct bases, virtual or not. 6973 VisitDirectBases, 6974 /// Visit all non-virtual bases, and all virtual bases if the class 6975 /// is not abstract. 6976 VisitPotentiallyConstructedBases, 6977 /// Visit all direct or virtual bases. 6978 VisitAllBases 6979 }; 6980 6981 // Visit the bases and members of the class. 6982 bool visit(BasesToVisit Bases) { 6983 CXXRecordDecl *RD = MD->getParent(); 6984 6985 if (Bases == VisitPotentiallyConstructedBases) 6986 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6987 6988 for (auto &B : RD->bases()) 6989 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6990 getDerived().visitBase(&B)) 6991 return true; 6992 6993 if (Bases == VisitAllBases) 6994 for (auto &B : RD->vbases()) 6995 if (getDerived().visitBase(&B)) 6996 return true; 6997 6998 for (auto *F : RD->fields()) 6999 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 7000 getDerived().visitField(F)) 7001 return true; 7002 7003 return false; 7004 } 7005 }; 7006 } 7007 7008 namespace { 7009 struct SpecialMemberDeletionInfo 7010 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 7011 bool Diagnose; 7012 7013 SourceLocation Loc; 7014 7015 bool AllFieldsAreConst; 7016 7017 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 7018 Sema::CXXSpecialMember CSM, 7019 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 7020 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 7021 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 7022 7023 bool inUnion() const { return MD->getParent()->isUnion(); } 7024 7025 Sema::CXXSpecialMember getEffectiveCSM() { 7026 return ICI ? Sema::CXXInvalid : CSM; 7027 } 7028 7029 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 7030 7031 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 7032 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 7033 7034 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 7035 bool shouldDeleteForField(FieldDecl *FD); 7036 bool shouldDeleteForAllConstMembers(); 7037 7038 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 7039 unsigned Quals); 7040 bool shouldDeleteForSubobjectCall(Subobject Subobj, 7041 Sema::SpecialMemberOverloadResult SMOR, 7042 bool IsDtorCallInCtor); 7043 7044 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 7045 }; 7046 } 7047 7048 /// Is the given special member inaccessible when used on the given 7049 /// sub-object. 7050 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 7051 CXXMethodDecl *target) { 7052 /// If we're operating on a base class, the object type is the 7053 /// type of this special member. 7054 QualType objectTy; 7055 AccessSpecifier access = target->getAccess(); 7056 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 7057 objectTy = S.Context.getTypeDeclType(MD->getParent()); 7058 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 7059 7060 // If we're operating on a field, the object type is the type of the field. 7061 } else { 7062 objectTy = S.Context.getTypeDeclType(target->getParent()); 7063 } 7064 7065 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 7066 } 7067 7068 /// Check whether we should delete a special member due to the implicit 7069 /// definition containing a call to a special member of a subobject. 7070 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 7071 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 7072 bool IsDtorCallInCtor) { 7073 CXXMethodDecl *Decl = SMOR.getMethod(); 7074 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 7075 7076 int DiagKind = -1; 7077 7078 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 7079 DiagKind = !Decl ? 0 : 1; 7080 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7081 DiagKind = 2; 7082 else if (!isAccessible(Subobj, Decl)) 7083 DiagKind = 3; 7084 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 7085 !Decl->isTrivial()) { 7086 // A member of a union must have a trivial corresponding special member. 7087 // As a weird special case, a destructor call from a union's constructor 7088 // must be accessible and non-deleted, but need not be trivial. Such a 7089 // destructor is never actually called, but is semantically checked as 7090 // if it were. 7091 DiagKind = 4; 7092 } 7093 7094 if (DiagKind == -1) 7095 return false; 7096 7097 if (Diagnose) { 7098 if (Field) { 7099 S.Diag(Field->getLocation(), 7100 diag::note_deleted_special_member_class_subobject) 7101 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 7102 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 7103 } else { 7104 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 7105 S.Diag(Base->getBeginLoc(), 7106 diag::note_deleted_special_member_class_subobject) 7107 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7108 << Base->getType() << DiagKind << IsDtorCallInCtor 7109 << /*IsObjCPtr*/false; 7110 } 7111 7112 if (DiagKind == 1) 7113 S.NoteDeletedFunction(Decl); 7114 // FIXME: Explain inaccessibility if DiagKind == 3. 7115 } 7116 7117 return true; 7118 } 7119 7120 /// Check whether we should delete a special member function due to having a 7121 /// direct or virtual base class or non-static data member of class type M. 7122 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 7123 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 7124 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 7125 bool IsMutable = Field && Field->isMutable(); 7126 7127 // C++11 [class.ctor]p5: 7128 // -- any direct or virtual base class, or non-static data member with no 7129 // brace-or-equal-initializer, has class type M (or array thereof) and 7130 // either M has no default constructor or overload resolution as applied 7131 // to M's default constructor results in an ambiguity or in a function 7132 // that is deleted or inaccessible 7133 // C++11 [class.copy]p11, C++11 [class.copy]p23: 7134 // -- a direct or virtual base class B that cannot be copied/moved because 7135 // overload resolution, as applied to B's corresponding special member, 7136 // results in an ambiguity or a function that is deleted or inaccessible 7137 // from the defaulted special member 7138 // C++11 [class.dtor]p5: 7139 // -- any direct or virtual base class [...] has a type with a destructor 7140 // that is deleted or inaccessible 7141 if (!(CSM == Sema::CXXDefaultConstructor && 7142 Field && Field->hasInClassInitializer()) && 7143 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 7144 false)) 7145 return true; 7146 7147 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 7148 // -- any direct or virtual base class or non-static data member has a 7149 // type with a destructor that is deleted or inaccessible 7150 if (IsConstructor) { 7151 Sema::SpecialMemberOverloadResult SMOR = 7152 S.LookupSpecialMember(Class, Sema::CXXDestructor, 7153 false, false, false, false, false); 7154 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 7155 return true; 7156 } 7157 7158 return false; 7159 } 7160 7161 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 7162 FieldDecl *FD, QualType FieldType) { 7163 // The defaulted special functions are defined as deleted if this is a variant 7164 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 7165 // type under ARC. 7166 if (!FieldType.hasNonTrivialObjCLifetime()) 7167 return false; 7168 7169 // Don't make the defaulted default constructor defined as deleted if the 7170 // member has an in-class initializer. 7171 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 7172 return false; 7173 7174 if (Diagnose) { 7175 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 7176 S.Diag(FD->getLocation(), 7177 diag::note_deleted_special_member_class_subobject) 7178 << getEffectiveCSM() << ParentClass << /*IsField*/true 7179 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 7180 } 7181 7182 return true; 7183 } 7184 7185 /// Check whether we should delete a special member function due to the class 7186 /// having a particular direct or virtual base class. 7187 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 7188 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 7189 // If program is correct, BaseClass cannot be null, but if it is, the error 7190 // must be reported elsewhere. 7191 if (!BaseClass) 7192 return false; 7193 // If we have an inheriting constructor, check whether we're calling an 7194 // inherited constructor instead of a default constructor. 7195 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 7196 if (auto *BaseCtor = SMOR.getMethod()) { 7197 // Note that we do not check access along this path; other than that, 7198 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 7199 // FIXME: Check that the base has a usable destructor! Sink this into 7200 // shouldDeleteForClassSubobject. 7201 if (BaseCtor->isDeleted() && Diagnose) { 7202 S.Diag(Base->getBeginLoc(), 7203 diag::note_deleted_special_member_class_subobject) 7204 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7205 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 7206 << /*IsObjCPtr*/false; 7207 S.NoteDeletedFunction(BaseCtor); 7208 } 7209 return BaseCtor->isDeleted(); 7210 } 7211 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 7212 } 7213 7214 /// Check whether we should delete a special member function due to the class 7215 /// having a particular non-static data member. 7216 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 7217 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 7218 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 7219 7220 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 7221 return true; 7222 7223 if (CSM == Sema::CXXDefaultConstructor) { 7224 // For a default constructor, all references must be initialized in-class 7225 // and, if a union, it must have a non-const member. 7226 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 7227 if (Diagnose) 7228 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7229 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 7230 return true; 7231 } 7232 // C++11 [class.ctor]p5: any non-variant non-static data member of 7233 // const-qualified type (or array thereof) with no 7234 // brace-or-equal-initializer does not have a user-provided default 7235 // constructor. 7236 if (!inUnion() && FieldType.isConstQualified() && 7237 !FD->hasInClassInitializer() && 7238 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 7239 if (Diagnose) 7240 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7241 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 7242 return true; 7243 } 7244 7245 if (inUnion() && !FieldType.isConstQualified()) 7246 AllFieldsAreConst = false; 7247 } else if (CSM == Sema::CXXCopyConstructor) { 7248 // For a copy constructor, data members must not be of rvalue reference 7249 // type. 7250 if (FieldType->isRValueReferenceType()) { 7251 if (Diagnose) 7252 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 7253 << MD->getParent() << FD << FieldType; 7254 return true; 7255 } 7256 } else if (IsAssignment) { 7257 // For an assignment operator, data members must not be of reference type. 7258 if (FieldType->isReferenceType()) { 7259 if (Diagnose) 7260 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7261 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 7262 return true; 7263 } 7264 if (!FieldRecord && FieldType.isConstQualified()) { 7265 // C++11 [class.copy]p23: 7266 // -- a non-static data member of const non-class type (or array thereof) 7267 if (Diagnose) 7268 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7269 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7270 return true; 7271 } 7272 } 7273 7274 if (FieldRecord) { 7275 // Some additional restrictions exist on the variant members. 7276 if (!inUnion() && FieldRecord->isUnion() && 7277 FieldRecord->isAnonymousStructOrUnion()) { 7278 bool AllVariantFieldsAreConst = true; 7279 7280 // FIXME: Handle anonymous unions declared within anonymous unions. 7281 for (auto *UI : FieldRecord->fields()) { 7282 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7283 7284 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 7285 return true; 7286 7287 if (!UnionFieldType.isConstQualified()) 7288 AllVariantFieldsAreConst = false; 7289 7290 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7291 if (UnionFieldRecord && 7292 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7293 UnionFieldType.getCVRQualifiers())) 7294 return true; 7295 } 7296 7297 // At least one member in each anonymous union must be non-const 7298 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7299 !FieldRecord->field_empty()) { 7300 if (Diagnose) 7301 S.Diag(FieldRecord->getLocation(), 7302 diag::note_deleted_default_ctor_all_const) 7303 << !!ICI << MD->getParent() << /*anonymous union*/1; 7304 return true; 7305 } 7306 7307 // Don't check the implicit member of the anonymous union type. 7308 // This is technically non-conformant, but sanity demands it. 7309 return false; 7310 } 7311 7312 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7313 FieldType.getCVRQualifiers())) 7314 return true; 7315 } 7316 7317 return false; 7318 } 7319 7320 /// C++11 [class.ctor] p5: 7321 /// A defaulted default constructor for a class X is defined as deleted if 7322 /// X is a union and all of its variant members are of const-qualified type. 7323 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7324 // This is a silly definition, because it gives an empty union a deleted 7325 // default constructor. Don't do that. 7326 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7327 bool AnyFields = false; 7328 for (auto *F : MD->getParent()->fields()) 7329 if ((AnyFields = !F->isUnnamedBitfield())) 7330 break; 7331 if (!AnyFields) 7332 return false; 7333 if (Diagnose) 7334 S.Diag(MD->getParent()->getLocation(), 7335 diag::note_deleted_default_ctor_all_const) 7336 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7337 return true; 7338 } 7339 return false; 7340 } 7341 7342 /// Determine whether a defaulted special member function should be defined as 7343 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7344 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7345 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7346 InheritedConstructorInfo *ICI, 7347 bool Diagnose) { 7348 if (MD->isInvalidDecl()) 7349 return false; 7350 CXXRecordDecl *RD = MD->getParent(); 7351 assert(!RD->isDependentType() && "do deletion after instantiation"); 7352 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7353 return false; 7354 7355 // C++11 [expr.lambda.prim]p19: 7356 // The closure type associated with a lambda-expression has a 7357 // deleted (8.4.3) default constructor and a deleted copy 7358 // assignment operator. 7359 // C++2a adds back these operators if the lambda has no lambda-capture. 7360 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 7361 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7362 if (Diagnose) 7363 Diag(RD->getLocation(), diag::note_lambda_decl); 7364 return true; 7365 } 7366 7367 // For an anonymous struct or union, the copy and assignment special members 7368 // will never be used, so skip the check. For an anonymous union declared at 7369 // namespace scope, the constructor and destructor are used. 7370 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7371 RD->isAnonymousStructOrUnion()) 7372 return false; 7373 7374 // C++11 [class.copy]p7, p18: 7375 // If the class definition declares a move constructor or move assignment 7376 // operator, an implicitly declared copy constructor or copy assignment 7377 // operator is defined as deleted. 7378 if (MD->isImplicit() && 7379 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7380 CXXMethodDecl *UserDeclaredMove = nullptr; 7381 7382 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7383 // deletion of the corresponding copy operation, not both copy operations. 7384 // MSVC 2015 has adopted the standards conforming behavior. 7385 bool DeletesOnlyMatchingCopy = 7386 getLangOpts().MSVCCompat && 7387 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7388 7389 if (RD->hasUserDeclaredMoveConstructor() && 7390 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7391 if (!Diagnose) return true; 7392 7393 // Find any user-declared move constructor. 7394 for (auto *I : RD->ctors()) { 7395 if (I->isMoveConstructor()) { 7396 UserDeclaredMove = I; 7397 break; 7398 } 7399 } 7400 assert(UserDeclaredMove); 7401 } else if (RD->hasUserDeclaredMoveAssignment() && 7402 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7403 if (!Diagnose) return true; 7404 7405 // Find any user-declared move assignment operator. 7406 for (auto *I : RD->methods()) { 7407 if (I->isMoveAssignmentOperator()) { 7408 UserDeclaredMove = I; 7409 break; 7410 } 7411 } 7412 assert(UserDeclaredMove); 7413 } 7414 7415 if (UserDeclaredMove) { 7416 Diag(UserDeclaredMove->getLocation(), 7417 diag::note_deleted_copy_user_declared_move) 7418 << (CSM == CXXCopyAssignment) << RD 7419 << UserDeclaredMove->isMoveAssignmentOperator(); 7420 return true; 7421 } 7422 } 7423 7424 // Do access control from the special member function 7425 ContextRAII MethodContext(*this, MD); 7426 7427 // C++11 [class.dtor]p5: 7428 // -- for a virtual destructor, lookup of the non-array deallocation function 7429 // results in an ambiguity or in a function that is deleted or inaccessible 7430 if (CSM == CXXDestructor && MD->isVirtual()) { 7431 FunctionDecl *OperatorDelete = nullptr; 7432 DeclarationName Name = 7433 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7434 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7435 OperatorDelete, /*Diagnose*/false)) { 7436 if (Diagnose) 7437 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7438 return true; 7439 } 7440 } 7441 7442 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7443 7444 // Per DR1611, do not consider virtual bases of constructors of abstract 7445 // classes, since we are not going to construct them. 7446 // Per DR1658, do not consider virtual bases of destructors of abstract 7447 // classes either. 7448 // Per DR2180, for assignment operators we only assign (and thus only 7449 // consider) direct bases. 7450 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7451 : SMI.VisitPotentiallyConstructedBases)) 7452 return true; 7453 7454 if (SMI.shouldDeleteForAllConstMembers()) 7455 return true; 7456 7457 if (getLangOpts().CUDA) { 7458 // We should delete the special member in CUDA mode if target inference 7459 // failed. 7460 // For inherited constructors (non-null ICI), CSM may be passed so that MD 7461 // is treated as certain special member, which may not reflect what special 7462 // member MD really is. However inferCUDATargetForImplicitSpecialMember 7463 // expects CSM to match MD, therefore recalculate CSM. 7464 assert(ICI || CSM == getSpecialMember(MD)); 7465 auto RealCSM = CSM; 7466 if (ICI) 7467 RealCSM = getSpecialMember(MD); 7468 7469 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 7470 SMI.ConstArg, Diagnose); 7471 } 7472 7473 return false; 7474 } 7475 7476 /// Perform lookup for a special member of the specified kind, and determine 7477 /// whether it is trivial. If the triviality can be determined without the 7478 /// lookup, skip it. This is intended for use when determining whether a 7479 /// special member of a containing object is trivial, and thus does not ever 7480 /// perform overload resolution for default constructors. 7481 /// 7482 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7483 /// member that was most likely to be intended to be trivial, if any. 7484 /// 7485 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7486 /// determine whether the special member is trivial. 7487 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7488 Sema::CXXSpecialMember CSM, unsigned Quals, 7489 bool ConstRHS, 7490 Sema::TrivialABIHandling TAH, 7491 CXXMethodDecl **Selected) { 7492 if (Selected) 7493 *Selected = nullptr; 7494 7495 switch (CSM) { 7496 case Sema::CXXInvalid: 7497 llvm_unreachable("not a special member"); 7498 7499 case Sema::CXXDefaultConstructor: 7500 // C++11 [class.ctor]p5: 7501 // A default constructor is trivial if: 7502 // - all the [direct subobjects] have trivial default constructors 7503 // 7504 // Note, no overload resolution is performed in this case. 7505 if (RD->hasTrivialDefaultConstructor()) 7506 return true; 7507 7508 if (Selected) { 7509 // If there's a default constructor which could have been trivial, dig it 7510 // out. Otherwise, if there's any user-provided default constructor, point 7511 // to that as an example of why there's not a trivial one. 7512 CXXConstructorDecl *DefCtor = nullptr; 7513 if (RD->needsImplicitDefaultConstructor()) 7514 S.DeclareImplicitDefaultConstructor(RD); 7515 for (auto *CI : RD->ctors()) { 7516 if (!CI->isDefaultConstructor()) 7517 continue; 7518 DefCtor = CI; 7519 if (!DefCtor->isUserProvided()) 7520 break; 7521 } 7522 7523 *Selected = DefCtor; 7524 } 7525 7526 return false; 7527 7528 case Sema::CXXDestructor: 7529 // C++11 [class.dtor]p5: 7530 // A destructor is trivial if: 7531 // - all the direct [subobjects] have trivial destructors 7532 if (RD->hasTrivialDestructor() || 7533 (TAH == Sema::TAH_ConsiderTrivialABI && 7534 RD->hasTrivialDestructorForCall())) 7535 return true; 7536 7537 if (Selected) { 7538 if (RD->needsImplicitDestructor()) 7539 S.DeclareImplicitDestructor(RD); 7540 *Selected = RD->getDestructor(); 7541 } 7542 7543 return false; 7544 7545 case Sema::CXXCopyConstructor: 7546 // C++11 [class.copy]p12: 7547 // A copy constructor is trivial if: 7548 // - the constructor selected to copy each direct [subobject] is trivial 7549 if (RD->hasTrivialCopyConstructor() || 7550 (TAH == Sema::TAH_ConsiderTrivialABI && 7551 RD->hasTrivialCopyConstructorForCall())) { 7552 if (Quals == Qualifiers::Const) 7553 // We must either select the trivial copy constructor or reach an 7554 // ambiguity; no need to actually perform overload resolution. 7555 return true; 7556 } else if (!Selected) { 7557 return false; 7558 } 7559 // In C++98, we are not supposed to perform overload resolution here, but we 7560 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7561 // cases like B as having a non-trivial copy constructor: 7562 // struct A { template<typename T> A(T&); }; 7563 // struct B { mutable A a; }; 7564 goto NeedOverloadResolution; 7565 7566 case Sema::CXXCopyAssignment: 7567 // C++11 [class.copy]p25: 7568 // A copy assignment operator is trivial if: 7569 // - the assignment operator selected to copy each direct [subobject] is 7570 // trivial 7571 if (RD->hasTrivialCopyAssignment()) { 7572 if (Quals == Qualifiers::Const) 7573 return true; 7574 } else if (!Selected) { 7575 return false; 7576 } 7577 // In C++98, we are not supposed to perform overload resolution here, but we 7578 // treat that as a language defect. 7579 goto NeedOverloadResolution; 7580 7581 case Sema::CXXMoveConstructor: 7582 case Sema::CXXMoveAssignment: 7583 NeedOverloadResolution: 7584 Sema::SpecialMemberOverloadResult SMOR = 7585 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7586 7587 // The standard doesn't describe how to behave if the lookup is ambiguous. 7588 // We treat it as not making the member non-trivial, just like the standard 7589 // mandates for the default constructor. This should rarely matter, because 7590 // the member will also be deleted. 7591 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7592 return true; 7593 7594 if (!SMOR.getMethod()) { 7595 assert(SMOR.getKind() == 7596 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7597 return false; 7598 } 7599 7600 // We deliberately don't check if we found a deleted special member. We're 7601 // not supposed to! 7602 if (Selected) 7603 *Selected = SMOR.getMethod(); 7604 7605 if (TAH == Sema::TAH_ConsiderTrivialABI && 7606 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7607 return SMOR.getMethod()->isTrivialForCall(); 7608 return SMOR.getMethod()->isTrivial(); 7609 } 7610 7611 llvm_unreachable("unknown special method kind"); 7612 } 7613 7614 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7615 for (auto *CI : RD->ctors()) 7616 if (!CI->isImplicit()) 7617 return CI; 7618 7619 // Look for constructor templates. 7620 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7621 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7622 if (CXXConstructorDecl *CD = 7623 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7624 return CD; 7625 } 7626 7627 return nullptr; 7628 } 7629 7630 /// The kind of subobject we are checking for triviality. The values of this 7631 /// enumeration are used in diagnostics. 7632 enum TrivialSubobjectKind { 7633 /// The subobject is a base class. 7634 TSK_BaseClass, 7635 /// The subobject is a non-static data member. 7636 TSK_Field, 7637 /// The object is actually the complete object. 7638 TSK_CompleteObject 7639 }; 7640 7641 /// Check whether the special member selected for a given type would be trivial. 7642 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7643 QualType SubType, bool ConstRHS, 7644 Sema::CXXSpecialMember CSM, 7645 TrivialSubobjectKind Kind, 7646 Sema::TrivialABIHandling TAH, bool Diagnose) { 7647 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7648 if (!SubRD) 7649 return true; 7650 7651 CXXMethodDecl *Selected; 7652 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7653 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7654 return true; 7655 7656 if (Diagnose) { 7657 if (ConstRHS) 7658 SubType.addConst(); 7659 7660 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7661 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7662 << Kind << SubType.getUnqualifiedType(); 7663 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7664 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7665 } else if (!Selected) 7666 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7667 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7668 else if (Selected->isUserProvided()) { 7669 if (Kind == TSK_CompleteObject) 7670 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7671 << Kind << SubType.getUnqualifiedType() << CSM; 7672 else { 7673 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7674 << Kind << SubType.getUnqualifiedType() << CSM; 7675 S.Diag(Selected->getLocation(), diag::note_declared_at); 7676 } 7677 } else { 7678 if (Kind != TSK_CompleteObject) 7679 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7680 << Kind << SubType.getUnqualifiedType() << CSM; 7681 7682 // Explain why the defaulted or deleted special member isn't trivial. 7683 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7684 Diagnose); 7685 } 7686 } 7687 7688 return false; 7689 } 7690 7691 /// Check whether the members of a class type allow a special member to be 7692 /// trivial. 7693 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7694 Sema::CXXSpecialMember CSM, 7695 bool ConstArg, 7696 Sema::TrivialABIHandling TAH, 7697 bool Diagnose) { 7698 for (const auto *FI : RD->fields()) { 7699 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7700 continue; 7701 7702 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7703 7704 // Pretend anonymous struct or union members are members of this class. 7705 if (FI->isAnonymousStructOrUnion()) { 7706 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7707 CSM, ConstArg, TAH, Diagnose)) 7708 return false; 7709 continue; 7710 } 7711 7712 // C++11 [class.ctor]p5: 7713 // A default constructor is trivial if [...] 7714 // -- no non-static data member of its class has a 7715 // brace-or-equal-initializer 7716 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7717 if (Diagnose) 7718 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7719 return false; 7720 } 7721 7722 // Objective C ARC 4.3.5: 7723 // [...] nontrivally ownership-qualified types are [...] not trivially 7724 // default constructible, copy constructible, move constructible, copy 7725 // assignable, move assignable, or destructible [...] 7726 if (FieldType.hasNonTrivialObjCLifetime()) { 7727 if (Diagnose) 7728 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7729 << RD << FieldType.getObjCLifetime(); 7730 return false; 7731 } 7732 7733 bool ConstRHS = ConstArg && !FI->isMutable(); 7734 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7735 CSM, TSK_Field, TAH, Diagnose)) 7736 return false; 7737 } 7738 7739 return true; 7740 } 7741 7742 /// Diagnose why the specified class does not have a trivial special member of 7743 /// the given kind. 7744 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7745 QualType Ty = Context.getRecordType(RD); 7746 7747 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7748 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7749 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7750 /*Diagnose*/true); 7751 } 7752 7753 /// Determine whether a defaulted or deleted special member function is trivial, 7754 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7755 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7756 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7757 TrivialABIHandling TAH, bool Diagnose) { 7758 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7759 7760 CXXRecordDecl *RD = MD->getParent(); 7761 7762 bool ConstArg = false; 7763 7764 // C++11 [class.copy]p12, p25: [DR1593] 7765 // A [special member] is trivial if [...] its parameter-type-list is 7766 // equivalent to the parameter-type-list of an implicit declaration [...] 7767 switch (CSM) { 7768 case CXXDefaultConstructor: 7769 case CXXDestructor: 7770 // Trivial default constructors and destructors cannot have parameters. 7771 break; 7772 7773 case CXXCopyConstructor: 7774 case CXXCopyAssignment: { 7775 // Trivial copy operations always have const, non-volatile parameter types. 7776 ConstArg = true; 7777 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7778 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7779 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7780 if (Diagnose) 7781 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7782 << Param0->getSourceRange() << Param0->getType() 7783 << Context.getLValueReferenceType( 7784 Context.getRecordType(RD).withConst()); 7785 return false; 7786 } 7787 break; 7788 } 7789 7790 case CXXMoveConstructor: 7791 case CXXMoveAssignment: { 7792 // Trivial move operations always have non-cv-qualified parameters. 7793 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7794 const RValueReferenceType *RT = 7795 Param0->getType()->getAs<RValueReferenceType>(); 7796 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7797 if (Diagnose) 7798 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7799 << Param0->getSourceRange() << Param0->getType() 7800 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7801 return false; 7802 } 7803 break; 7804 } 7805 7806 case CXXInvalid: 7807 llvm_unreachable("not a special member"); 7808 } 7809 7810 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7811 if (Diagnose) 7812 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7813 diag::note_nontrivial_default_arg) 7814 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7815 return false; 7816 } 7817 if (MD->isVariadic()) { 7818 if (Diagnose) 7819 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7820 return false; 7821 } 7822 7823 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7824 // A copy/move [constructor or assignment operator] is trivial if 7825 // -- the [member] selected to copy/move each direct base class subobject 7826 // is trivial 7827 // 7828 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7829 // A [default constructor or destructor] is trivial if 7830 // -- all the direct base classes have trivial [default constructors or 7831 // destructors] 7832 for (const auto &BI : RD->bases()) 7833 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 7834 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7835 return false; 7836 7837 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7838 // A copy/move [constructor or assignment operator] for a class X is 7839 // trivial if 7840 // -- for each non-static data member of X that is of class type (or array 7841 // thereof), the constructor selected to copy/move that member is 7842 // trivial 7843 // 7844 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7845 // A [default constructor or destructor] is trivial if 7846 // -- for all of the non-static data members of its class that are of class 7847 // type (or array thereof), each such class has a trivial [default 7848 // constructor or destructor] 7849 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7850 return false; 7851 7852 // C++11 [class.dtor]p5: 7853 // A destructor is trivial if [...] 7854 // -- the destructor is not virtual 7855 if (CSM == CXXDestructor && MD->isVirtual()) { 7856 if (Diagnose) 7857 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7858 return false; 7859 } 7860 7861 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7862 // A [special member] for class X is trivial if [...] 7863 // -- class X has no virtual functions and no virtual base classes 7864 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7865 if (!Diagnose) 7866 return false; 7867 7868 if (RD->getNumVBases()) { 7869 // Check for virtual bases. We already know that the corresponding 7870 // member in all bases is trivial, so vbases must all be direct. 7871 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7872 assert(BS.isVirtual()); 7873 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 7874 return false; 7875 } 7876 7877 // Must have a virtual method. 7878 for (const auto *MI : RD->methods()) { 7879 if (MI->isVirtual()) { 7880 SourceLocation MLoc = MI->getBeginLoc(); 7881 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7882 return false; 7883 } 7884 } 7885 7886 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7887 } 7888 7889 // Looks like it's trivial! 7890 return true; 7891 } 7892 7893 namespace { 7894 struct FindHiddenVirtualMethod { 7895 Sema *S; 7896 CXXMethodDecl *Method; 7897 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7898 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7899 7900 private: 7901 /// Check whether any most overridden method from MD in Methods 7902 static bool CheckMostOverridenMethods( 7903 const CXXMethodDecl *MD, 7904 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7905 if (MD->size_overridden_methods() == 0) 7906 return Methods.count(MD->getCanonicalDecl()); 7907 for (const CXXMethodDecl *O : MD->overridden_methods()) 7908 if (CheckMostOverridenMethods(O, Methods)) 7909 return true; 7910 return false; 7911 } 7912 7913 public: 7914 /// Member lookup function that determines whether a given C++ 7915 /// method overloads virtual methods in a base class without overriding any, 7916 /// to be used with CXXRecordDecl::lookupInBases(). 7917 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7918 RecordDecl *BaseRecord = 7919 Specifier->getType()->getAs<RecordType>()->getDecl(); 7920 7921 DeclarationName Name = Method->getDeclName(); 7922 assert(Name.getNameKind() == DeclarationName::Identifier); 7923 7924 bool foundSameNameMethod = false; 7925 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7926 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7927 Path.Decls = Path.Decls.slice(1)) { 7928 NamedDecl *D = Path.Decls.front(); 7929 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7930 MD = MD->getCanonicalDecl(); 7931 foundSameNameMethod = true; 7932 // Interested only in hidden virtual methods. 7933 if (!MD->isVirtual()) 7934 continue; 7935 // If the method we are checking overrides a method from its base 7936 // don't warn about the other overloaded methods. Clang deviates from 7937 // GCC by only diagnosing overloads of inherited virtual functions that 7938 // do not override any other virtual functions in the base. GCC's 7939 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7940 // function from a base class. These cases may be better served by a 7941 // warning (not specific to virtual functions) on call sites when the 7942 // call would select a different function from the base class, were it 7943 // visible. 7944 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7945 if (!S->IsOverload(Method, MD, false)) 7946 return true; 7947 // Collect the overload only if its hidden. 7948 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7949 overloadedMethods.push_back(MD); 7950 } 7951 } 7952 7953 if (foundSameNameMethod) 7954 OverloadedMethods.append(overloadedMethods.begin(), 7955 overloadedMethods.end()); 7956 return foundSameNameMethod; 7957 } 7958 }; 7959 } // end anonymous namespace 7960 7961 /// Add the most overriden methods from MD to Methods 7962 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7963 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7964 if (MD->size_overridden_methods() == 0) 7965 Methods.insert(MD->getCanonicalDecl()); 7966 else 7967 for (const CXXMethodDecl *O : MD->overridden_methods()) 7968 AddMostOverridenMethods(O, Methods); 7969 } 7970 7971 /// Check if a method overloads virtual methods in a base class without 7972 /// overriding any. 7973 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7974 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7975 if (!MD->getDeclName().isIdentifier()) 7976 return; 7977 7978 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7979 /*bool RecordPaths=*/false, 7980 /*bool DetectVirtual=*/false); 7981 FindHiddenVirtualMethod FHVM; 7982 FHVM.Method = MD; 7983 FHVM.S = this; 7984 7985 // Keep the base methods that were overridden or introduced in the subclass 7986 // by 'using' in a set. A base method not in this set is hidden. 7987 CXXRecordDecl *DC = MD->getParent(); 7988 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7989 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7990 NamedDecl *ND = *I; 7991 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7992 ND = shad->getTargetDecl(); 7993 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7994 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7995 } 7996 7997 if (DC->lookupInBases(FHVM, Paths)) 7998 OverloadedMethods = FHVM.OverloadedMethods; 7999 } 8000 8001 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 8002 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 8003 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 8004 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 8005 PartialDiagnostic PD = PDiag( 8006 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 8007 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 8008 Diag(overloadedMD->getLocation(), PD); 8009 } 8010 } 8011 8012 /// Diagnose methods which overload virtual methods in a base class 8013 /// without overriding any. 8014 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 8015 if (MD->isInvalidDecl()) 8016 return; 8017 8018 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 8019 return; 8020 8021 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 8022 FindHiddenVirtualMethods(MD, OverloadedMethods); 8023 if (!OverloadedMethods.empty()) { 8024 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 8025 << MD << (OverloadedMethods.size() > 1); 8026 8027 NoteHiddenVirtualMethods(MD, OverloadedMethods); 8028 } 8029 } 8030 8031 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 8032 auto PrintDiagAndRemoveAttr = [&]() { 8033 // No diagnostics if this is a template instantiation. 8034 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 8035 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 8036 diag::ext_cannot_use_trivial_abi) << &RD; 8037 RD.dropAttr<TrivialABIAttr>(); 8038 }; 8039 8040 // Ill-formed if the struct has virtual functions. 8041 if (RD.isPolymorphic()) { 8042 PrintDiagAndRemoveAttr(); 8043 return; 8044 } 8045 8046 for (const auto &B : RD.bases()) { 8047 // Ill-formed if the base class is non-trivial for the purpose of calls or a 8048 // virtual base. 8049 if ((!B.getType()->isDependentType() && 8050 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 8051 B.isVirtual()) { 8052 PrintDiagAndRemoveAttr(); 8053 return; 8054 } 8055 } 8056 8057 for (const auto *FD : RD.fields()) { 8058 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 8059 // non-trivial for the purpose of calls. 8060 QualType FT = FD->getType(); 8061 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 8062 PrintDiagAndRemoveAttr(); 8063 return; 8064 } 8065 8066 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 8067 if (!RT->isDependentType() && 8068 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 8069 PrintDiagAndRemoveAttr(); 8070 return; 8071 } 8072 } 8073 } 8074 8075 void Sema::ActOnFinishCXXMemberSpecification( 8076 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 8077 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 8078 if (!TagDecl) 8079 return; 8080 8081 AdjustDeclIfTemplate(TagDecl); 8082 8083 for (const ParsedAttr &AL : AttrList) { 8084 if (AL.getKind() != ParsedAttr::AT_Visibility) 8085 continue; 8086 AL.setInvalid(); 8087 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) 8088 << AL.getName(); 8089 } 8090 8091 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 8092 // strict aliasing violation! 8093 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 8094 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 8095 8096 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 8097 } 8098 8099 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 8100 /// special functions, such as the default constructor, copy 8101 /// constructor, or destructor, to the given C++ class (C++ 8102 /// [special]p1). This routine can only be executed just before the 8103 /// definition of the class is complete. 8104 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 8105 if (ClassDecl->needsImplicitDefaultConstructor()) { 8106 ++getASTContext().NumImplicitDefaultConstructors; 8107 8108 if (ClassDecl->hasInheritedConstructor()) 8109 DeclareImplicitDefaultConstructor(ClassDecl); 8110 } 8111 8112 if (ClassDecl->needsImplicitCopyConstructor()) { 8113 ++getASTContext().NumImplicitCopyConstructors; 8114 8115 // If the properties or semantics of the copy constructor couldn't be 8116 // determined while the class was being declared, force a declaration 8117 // of it now. 8118 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 8119 ClassDecl->hasInheritedConstructor()) 8120 DeclareImplicitCopyConstructor(ClassDecl); 8121 // For the MS ABI we need to know whether the copy ctor is deleted. A 8122 // prerequisite for deleting the implicit copy ctor is that the class has a 8123 // move ctor or move assignment that is either user-declared or whose 8124 // semantics are inherited from a subobject. FIXME: We should provide a more 8125 // direct way for CodeGen to ask whether the constructor was deleted. 8126 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 8127 (ClassDecl->hasUserDeclaredMoveConstructor() || 8128 ClassDecl->needsOverloadResolutionForMoveConstructor() || 8129 ClassDecl->hasUserDeclaredMoveAssignment() || 8130 ClassDecl->needsOverloadResolutionForMoveAssignment())) 8131 DeclareImplicitCopyConstructor(ClassDecl); 8132 } 8133 8134 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 8135 ++getASTContext().NumImplicitMoveConstructors; 8136 8137 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 8138 ClassDecl->hasInheritedConstructor()) 8139 DeclareImplicitMoveConstructor(ClassDecl); 8140 } 8141 8142 if (ClassDecl->needsImplicitCopyAssignment()) { 8143 ++getASTContext().NumImplicitCopyAssignmentOperators; 8144 8145 // If we have a dynamic class, then the copy assignment operator may be 8146 // virtual, so we have to declare it immediately. This ensures that, e.g., 8147 // it shows up in the right place in the vtable and that we diagnose 8148 // problems with the implicit exception specification. 8149 if (ClassDecl->isDynamicClass() || 8150 ClassDecl->needsOverloadResolutionForCopyAssignment() || 8151 ClassDecl->hasInheritedAssignment()) 8152 DeclareImplicitCopyAssignment(ClassDecl); 8153 } 8154 8155 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 8156 ++getASTContext().NumImplicitMoveAssignmentOperators; 8157 8158 // Likewise for the move assignment operator. 8159 if (ClassDecl->isDynamicClass() || 8160 ClassDecl->needsOverloadResolutionForMoveAssignment() || 8161 ClassDecl->hasInheritedAssignment()) 8162 DeclareImplicitMoveAssignment(ClassDecl); 8163 } 8164 8165 if (ClassDecl->needsImplicitDestructor()) { 8166 ++getASTContext().NumImplicitDestructors; 8167 8168 // If we have a dynamic class, then the destructor may be virtual, so we 8169 // have to declare the destructor immediately. This ensures that, e.g., it 8170 // shows up in the right place in the vtable and that we diagnose problems 8171 // with the implicit exception specification. 8172 if (ClassDecl->isDynamicClass() || 8173 ClassDecl->needsOverloadResolutionForDestructor()) 8174 DeclareImplicitDestructor(ClassDecl); 8175 } 8176 } 8177 8178 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 8179 if (!D) 8180 return 0; 8181 8182 // The order of template parameters is not important here. All names 8183 // get added to the same scope. 8184 SmallVector<TemplateParameterList *, 4> ParameterLists; 8185 8186 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8187 D = TD->getTemplatedDecl(); 8188 8189 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 8190 ParameterLists.push_back(PSD->getTemplateParameters()); 8191 8192 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 8193 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 8194 ParameterLists.push_back(DD->getTemplateParameterList(i)); 8195 8196 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8197 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 8198 ParameterLists.push_back(FTD->getTemplateParameters()); 8199 } 8200 } 8201 8202 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 8203 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 8204 ParameterLists.push_back(TD->getTemplateParameterList(i)); 8205 8206 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 8207 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 8208 ParameterLists.push_back(CTD->getTemplateParameters()); 8209 } 8210 } 8211 8212 unsigned Count = 0; 8213 for (TemplateParameterList *Params : ParameterLists) { 8214 if (Params->size() > 0) 8215 // Ignore explicit specializations; they don't contribute to the template 8216 // depth. 8217 ++Count; 8218 for (NamedDecl *Param : *Params) { 8219 if (Param->getDeclName()) { 8220 S->AddDecl(Param); 8221 IdResolver.AddDecl(Param); 8222 } 8223 } 8224 } 8225 8226 return Count; 8227 } 8228 8229 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8230 if (!RecordD) return; 8231 AdjustDeclIfTemplate(RecordD); 8232 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 8233 PushDeclContext(S, Record); 8234 } 8235 8236 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8237 if (!RecordD) return; 8238 PopDeclContext(); 8239 } 8240 8241 /// This is used to implement the constant expression evaluation part of the 8242 /// attribute enable_if extension. There is nothing in standard C++ which would 8243 /// require reentering parameters. 8244 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 8245 if (!Param) 8246 return; 8247 8248 S->AddDecl(Param); 8249 if (Param->getDeclName()) 8250 IdResolver.AddDecl(Param); 8251 } 8252 8253 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 8254 /// parsing a top-level (non-nested) C++ class, and we are now 8255 /// parsing those parts of the given Method declaration that could 8256 /// not be parsed earlier (C++ [class.mem]p2), such as default 8257 /// arguments. This action should enter the scope of the given 8258 /// Method declaration as if we had just parsed the qualified method 8259 /// name. However, it should not bring the parameters into scope; 8260 /// that will be performed by ActOnDelayedCXXMethodParameter. 8261 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8262 } 8263 8264 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 8265 /// C++ method declaration. We're (re-)introducing the given 8266 /// function parameter into scope for use in parsing later parts of 8267 /// the method declaration. For example, we could see an 8268 /// ActOnParamDefaultArgument event for this parameter. 8269 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 8270 if (!ParamD) 8271 return; 8272 8273 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8274 8275 // If this parameter has an unparsed default argument, clear it out 8276 // to make way for the parsed default argument. 8277 if (Param->hasUnparsedDefaultArg()) 8278 Param->setDefaultArg(nullptr); 8279 8280 S->AddDecl(Param); 8281 if (Param->getDeclName()) 8282 IdResolver.AddDecl(Param); 8283 } 8284 8285 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8286 /// processing the delayed method declaration for Method. The method 8287 /// declaration is now considered finished. There may be a separate 8288 /// ActOnStartOfFunctionDef action later (not necessarily 8289 /// immediately!) for this method, if it was also defined inside the 8290 /// class body. 8291 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8292 if (!MethodD) 8293 return; 8294 8295 AdjustDeclIfTemplate(MethodD); 8296 8297 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8298 8299 // Now that we have our default arguments, check the constructor 8300 // again. It could produce additional diagnostics or affect whether 8301 // the class has implicitly-declared destructors, among other 8302 // things. 8303 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8304 CheckConstructor(Constructor); 8305 8306 // Check the default arguments, which we may have added. 8307 if (!Method->isInvalidDecl()) 8308 CheckCXXDefaultArguments(Method); 8309 } 8310 8311 // Emit the given diagnostic for each non-address-space qualifier. 8312 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 8313 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 8314 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8315 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 8316 bool DiagOccured = false; 8317 FTI.MethodQualifiers->forEachQualifier( 8318 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 8319 SourceLocation SL) { 8320 // This diagnostic should be emitted on any qualifier except an addr 8321 // space qualifier. However, forEachQualifier currently doesn't visit 8322 // addr space qualifiers, so there's no way to write this condition 8323 // right now; we just diagnose on everything. 8324 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 8325 DiagOccured = true; 8326 }); 8327 if (DiagOccured) 8328 D.setInvalidType(); 8329 } 8330 } 8331 8332 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8333 /// the well-formedness of the constructor declarator @p D with type @p 8334 /// R. If there are any errors in the declarator, this routine will 8335 /// emit diagnostics and set the invalid bit to true. In any case, the type 8336 /// will be updated to reflect a well-formed type for the constructor and 8337 /// returned. 8338 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8339 StorageClass &SC) { 8340 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8341 8342 // C++ [class.ctor]p3: 8343 // A constructor shall not be virtual (10.3) or static (9.4). A 8344 // constructor can be invoked for a const, volatile or const 8345 // volatile object. A constructor shall not be declared const, 8346 // volatile, or const volatile (9.3.2). 8347 if (isVirtual) { 8348 if (!D.isInvalidType()) 8349 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8350 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8351 << SourceRange(D.getIdentifierLoc()); 8352 D.setInvalidType(); 8353 } 8354 if (SC == SC_Static) { 8355 if (!D.isInvalidType()) 8356 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8357 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8358 << SourceRange(D.getIdentifierLoc()); 8359 D.setInvalidType(); 8360 SC = SC_None; 8361 } 8362 8363 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8364 diagnoseIgnoredQualifiers( 8365 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8366 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8367 D.getDeclSpec().getRestrictSpecLoc(), 8368 D.getDeclSpec().getAtomicSpecLoc()); 8369 D.setInvalidType(); 8370 } 8371 8372 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 8373 8374 // C++0x [class.ctor]p4: 8375 // A constructor shall not be declared with a ref-qualifier. 8376 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8377 if (FTI.hasRefQualifier()) { 8378 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8379 << FTI.RefQualifierIsLValueRef 8380 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8381 D.setInvalidType(); 8382 } 8383 8384 // Rebuild the function type "R" without any type qualifiers (in 8385 // case any of the errors above fired) and with "void" as the 8386 // return type, since constructors don't have return types. 8387 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8388 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8389 return R; 8390 8391 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8392 EPI.TypeQuals = Qualifiers(); 8393 EPI.RefQualifier = RQ_None; 8394 8395 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8396 } 8397 8398 /// CheckConstructor - Checks a fully-formed constructor for 8399 /// well-formedness, issuing any diagnostics required. Returns true if 8400 /// the constructor declarator is invalid. 8401 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8402 CXXRecordDecl *ClassDecl 8403 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8404 if (!ClassDecl) 8405 return Constructor->setInvalidDecl(); 8406 8407 // C++ [class.copy]p3: 8408 // A declaration of a constructor for a class X is ill-formed if 8409 // its first parameter is of type (optionally cv-qualified) X and 8410 // either there are no other parameters or else all other 8411 // parameters have default arguments. 8412 if (!Constructor->isInvalidDecl() && 8413 ((Constructor->getNumParams() == 1) || 8414 (Constructor->getNumParams() > 1 && 8415 Constructor->getParamDecl(1)->hasDefaultArg())) && 8416 Constructor->getTemplateSpecializationKind() 8417 != TSK_ImplicitInstantiation) { 8418 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8419 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8420 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8421 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8422 const char *ConstRef 8423 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8424 : " const &"; 8425 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8426 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8427 8428 // FIXME: Rather that making the constructor invalid, we should endeavor 8429 // to fix the type. 8430 Constructor->setInvalidDecl(); 8431 } 8432 } 8433 } 8434 8435 /// CheckDestructor - Checks a fully-formed destructor definition for 8436 /// well-formedness, issuing any diagnostics required. Returns true 8437 /// on error. 8438 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8439 CXXRecordDecl *RD = Destructor->getParent(); 8440 8441 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8442 SourceLocation Loc; 8443 8444 if (!Destructor->isImplicit()) 8445 Loc = Destructor->getLocation(); 8446 else 8447 Loc = RD->getLocation(); 8448 8449 // If we have a virtual destructor, look up the deallocation function 8450 if (FunctionDecl *OperatorDelete = 8451 FindDeallocationFunctionForDestructor(Loc, RD)) { 8452 Expr *ThisArg = nullptr; 8453 8454 // If the notional 'delete this' expression requires a non-trivial 8455 // conversion from 'this' to the type of a destroying operator delete's 8456 // first parameter, perform that conversion now. 8457 if (OperatorDelete->isDestroyingOperatorDelete()) { 8458 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8459 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8460 // C++ [class.dtor]p13: 8461 // ... as if for the expression 'delete this' appearing in a 8462 // non-virtual destructor of the destructor's class. 8463 ContextRAII SwitchContext(*this, Destructor); 8464 ExprResult This = 8465 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8466 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8467 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8468 if (This.isInvalid()) { 8469 // FIXME: Register this as a context note so that it comes out 8470 // in the right order. 8471 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8472 return true; 8473 } 8474 ThisArg = This.get(); 8475 } 8476 } 8477 8478 DiagnoseUseOfDecl(OperatorDelete, Loc); 8479 MarkFunctionReferenced(Loc, OperatorDelete); 8480 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8481 } 8482 } 8483 8484 return false; 8485 } 8486 8487 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8488 /// the well-formednes of the destructor declarator @p D with type @p 8489 /// R. If there are any errors in the declarator, this routine will 8490 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8491 /// will be updated to reflect a well-formed type for the destructor and 8492 /// returned. 8493 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8494 StorageClass& SC) { 8495 // C++ [class.dtor]p1: 8496 // [...] A typedef-name that names a class is a class-name 8497 // (7.1.3); however, a typedef-name that names a class shall not 8498 // be used as the identifier in the declarator for a destructor 8499 // declaration. 8500 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8501 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8502 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8503 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8504 else if (const TemplateSpecializationType *TST = 8505 DeclaratorType->getAs<TemplateSpecializationType>()) 8506 if (TST->isTypeAlias()) 8507 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8508 << DeclaratorType << 1; 8509 8510 // C++ [class.dtor]p2: 8511 // A destructor is used to destroy objects of its class type. A 8512 // destructor takes no parameters, and no return type can be 8513 // specified for it (not even void). The address of a destructor 8514 // shall not be taken. A destructor shall not be static. A 8515 // destructor can be invoked for a const, volatile or const 8516 // volatile object. A destructor shall not be declared const, 8517 // volatile or const volatile (9.3.2). 8518 if (SC == SC_Static) { 8519 if (!D.isInvalidType()) 8520 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8521 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8522 << SourceRange(D.getIdentifierLoc()) 8523 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8524 8525 SC = SC_None; 8526 } 8527 if (!D.isInvalidType()) { 8528 // Destructors don't have return types, but the parser will 8529 // happily parse something like: 8530 // 8531 // class X { 8532 // float ~X(); 8533 // }; 8534 // 8535 // The return type will be eliminated later. 8536 if (D.getDeclSpec().hasTypeSpecifier()) 8537 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8538 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8539 << SourceRange(D.getIdentifierLoc()); 8540 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8541 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8542 SourceLocation(), 8543 D.getDeclSpec().getConstSpecLoc(), 8544 D.getDeclSpec().getVolatileSpecLoc(), 8545 D.getDeclSpec().getRestrictSpecLoc(), 8546 D.getDeclSpec().getAtomicSpecLoc()); 8547 D.setInvalidType(); 8548 } 8549 } 8550 8551 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 8552 8553 // C++0x [class.dtor]p2: 8554 // A destructor shall not be declared with a ref-qualifier. 8555 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8556 if (FTI.hasRefQualifier()) { 8557 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8558 << FTI.RefQualifierIsLValueRef 8559 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8560 D.setInvalidType(); 8561 } 8562 8563 // Make sure we don't have any parameters. 8564 if (FTIHasNonVoidParameters(FTI)) { 8565 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8566 8567 // Delete the parameters. 8568 FTI.freeParams(); 8569 D.setInvalidType(); 8570 } 8571 8572 // Make sure the destructor isn't variadic. 8573 if (FTI.isVariadic) { 8574 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8575 D.setInvalidType(); 8576 } 8577 8578 // Rebuild the function type "R" without any type qualifiers or 8579 // parameters (in case any of the errors above fired) and with 8580 // "void" as the return type, since destructors don't have return 8581 // types. 8582 if (!D.isInvalidType()) 8583 return R; 8584 8585 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8586 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8587 EPI.Variadic = false; 8588 EPI.TypeQuals = Qualifiers(); 8589 EPI.RefQualifier = RQ_None; 8590 return Context.getFunctionType(Context.VoidTy, None, EPI); 8591 } 8592 8593 static void extendLeft(SourceRange &R, SourceRange Before) { 8594 if (Before.isInvalid()) 8595 return; 8596 R.setBegin(Before.getBegin()); 8597 if (R.getEnd().isInvalid()) 8598 R.setEnd(Before.getEnd()); 8599 } 8600 8601 static void extendRight(SourceRange &R, SourceRange After) { 8602 if (After.isInvalid()) 8603 return; 8604 if (R.getBegin().isInvalid()) 8605 R.setBegin(After.getBegin()); 8606 R.setEnd(After.getEnd()); 8607 } 8608 8609 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8610 /// well-formednes of the conversion function declarator @p D with 8611 /// type @p R. If there are any errors in the declarator, this routine 8612 /// will emit diagnostics and return true. Otherwise, it will return 8613 /// false. Either way, the type @p R will be updated to reflect a 8614 /// well-formed type for the conversion operator. 8615 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8616 StorageClass& SC) { 8617 // C++ [class.conv.fct]p1: 8618 // Neither parameter types nor return type can be specified. The 8619 // type of a conversion function (8.3.5) is "function taking no 8620 // parameter returning conversion-type-id." 8621 if (SC == SC_Static) { 8622 if (!D.isInvalidType()) 8623 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8624 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8625 << D.getName().getSourceRange(); 8626 D.setInvalidType(); 8627 SC = SC_None; 8628 } 8629 8630 TypeSourceInfo *ConvTSI = nullptr; 8631 QualType ConvType = 8632 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8633 8634 const DeclSpec &DS = D.getDeclSpec(); 8635 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8636 // Conversion functions don't have return types, but the parser will 8637 // happily parse something like: 8638 // 8639 // class X { 8640 // float operator bool(); 8641 // }; 8642 // 8643 // The return type will be changed later anyway. 8644 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8645 << SourceRange(DS.getTypeSpecTypeLoc()) 8646 << SourceRange(D.getIdentifierLoc()); 8647 D.setInvalidType(); 8648 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8649 // It's also plausible that the user writes type qualifiers in the wrong 8650 // place, such as: 8651 // struct S { const operator int(); }; 8652 // FIXME: we could provide a fixit to move the qualifiers onto the 8653 // conversion type. 8654 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8655 << SourceRange(D.getIdentifierLoc()) << 0; 8656 D.setInvalidType(); 8657 } 8658 8659 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8660 8661 // Make sure we don't have any parameters. 8662 if (Proto->getNumParams() > 0) { 8663 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8664 8665 // Delete the parameters. 8666 D.getFunctionTypeInfo().freeParams(); 8667 D.setInvalidType(); 8668 } else if (Proto->isVariadic()) { 8669 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8670 D.setInvalidType(); 8671 } 8672 8673 // Diagnose "&operator bool()" and other such nonsense. This 8674 // is actually a gcc extension which we don't support. 8675 if (Proto->getReturnType() != ConvType) { 8676 bool NeedsTypedef = false; 8677 SourceRange Before, After; 8678 8679 // Walk the chunks and extract information on them for our diagnostic. 8680 bool PastFunctionChunk = false; 8681 for (auto &Chunk : D.type_objects()) { 8682 switch (Chunk.Kind) { 8683 case DeclaratorChunk::Function: 8684 if (!PastFunctionChunk) { 8685 if (Chunk.Fun.HasTrailingReturnType) { 8686 TypeSourceInfo *TRT = nullptr; 8687 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8688 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8689 } 8690 PastFunctionChunk = true; 8691 break; 8692 } 8693 LLVM_FALLTHROUGH; 8694 case DeclaratorChunk::Array: 8695 NeedsTypedef = true; 8696 extendRight(After, Chunk.getSourceRange()); 8697 break; 8698 8699 case DeclaratorChunk::Pointer: 8700 case DeclaratorChunk::BlockPointer: 8701 case DeclaratorChunk::Reference: 8702 case DeclaratorChunk::MemberPointer: 8703 case DeclaratorChunk::Pipe: 8704 extendLeft(Before, Chunk.getSourceRange()); 8705 break; 8706 8707 case DeclaratorChunk::Paren: 8708 extendLeft(Before, Chunk.Loc); 8709 extendRight(After, Chunk.EndLoc); 8710 break; 8711 } 8712 } 8713 8714 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8715 After.isValid() ? After.getBegin() : 8716 D.getIdentifierLoc(); 8717 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8718 DB << Before << After; 8719 8720 if (!NeedsTypedef) { 8721 DB << /*don't need a typedef*/0; 8722 8723 // If we can provide a correct fix-it hint, do so. 8724 if (After.isInvalid() && ConvTSI) { 8725 SourceLocation InsertLoc = 8726 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 8727 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8728 << FixItHint::CreateInsertionFromRange( 8729 InsertLoc, CharSourceRange::getTokenRange(Before)) 8730 << FixItHint::CreateRemoval(Before); 8731 } 8732 } else if (!Proto->getReturnType()->isDependentType()) { 8733 DB << /*typedef*/1 << Proto->getReturnType(); 8734 } else if (getLangOpts().CPlusPlus11) { 8735 DB << /*alias template*/2 << Proto->getReturnType(); 8736 } else { 8737 DB << /*might not be fixable*/3; 8738 } 8739 8740 // Recover by incorporating the other type chunks into the result type. 8741 // Note, this does *not* change the name of the function. This is compatible 8742 // with the GCC extension: 8743 // struct S { &operator int(); } s; 8744 // int &r = s.operator int(); // ok in GCC 8745 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8746 ConvType = Proto->getReturnType(); 8747 } 8748 8749 // C++ [class.conv.fct]p4: 8750 // The conversion-type-id shall not represent a function type nor 8751 // an array type. 8752 if (ConvType->isArrayType()) { 8753 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8754 ConvType = Context.getPointerType(ConvType); 8755 D.setInvalidType(); 8756 } else if (ConvType->isFunctionType()) { 8757 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8758 ConvType = Context.getPointerType(ConvType); 8759 D.setInvalidType(); 8760 } 8761 8762 // Rebuild the function type "R" without any parameters (in case any 8763 // of the errors above fired) and with the conversion type as the 8764 // return type. 8765 if (D.isInvalidType()) 8766 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8767 8768 // C++0x explicit conversion operators. 8769 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) 8770 Diag(DS.getExplicitSpecLoc(), 8771 getLangOpts().CPlusPlus11 8772 ? diag::warn_cxx98_compat_explicit_conversion_functions 8773 : diag::ext_explicit_conversion_functions) 8774 << SourceRange(DS.getExplicitSpecRange()); 8775 } 8776 8777 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8778 /// the declaration of the given C++ conversion function. This routine 8779 /// is responsible for recording the conversion function in the C++ 8780 /// class, if possible. 8781 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8782 assert(Conversion && "Expected to receive a conversion function declaration"); 8783 8784 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8785 8786 // Make sure we aren't redeclaring the conversion function. 8787 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8788 8789 // C++ [class.conv.fct]p1: 8790 // [...] A conversion function is never used to convert a 8791 // (possibly cv-qualified) object to the (possibly cv-qualified) 8792 // same object type (or a reference to it), to a (possibly 8793 // cv-qualified) base class of that type (or a reference to it), 8794 // or to (possibly cv-qualified) void. 8795 // FIXME: Suppress this warning if the conversion function ends up being a 8796 // virtual function that overrides a virtual function in a base class. 8797 QualType ClassType 8798 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8799 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8800 ConvType = ConvTypeRef->getPointeeType(); 8801 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8802 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8803 /* Suppress diagnostics for instantiations. */; 8804 else if (ConvType->isRecordType()) { 8805 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8806 if (ConvType == ClassType) 8807 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8808 << ClassType; 8809 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8810 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8811 << ClassType << ConvType; 8812 } else if (ConvType->isVoidType()) { 8813 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8814 << ClassType << ConvType; 8815 } 8816 8817 if (FunctionTemplateDecl *ConversionTemplate 8818 = Conversion->getDescribedFunctionTemplate()) 8819 return ConversionTemplate; 8820 8821 return Conversion; 8822 } 8823 8824 namespace { 8825 /// Utility class to accumulate and print a diagnostic listing the invalid 8826 /// specifier(s) on a declaration. 8827 struct BadSpecifierDiagnoser { 8828 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8829 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8830 ~BadSpecifierDiagnoser() { 8831 Diagnostic << Specifiers; 8832 } 8833 8834 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8835 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8836 } 8837 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8838 return check(SpecLoc, 8839 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8840 } 8841 void check(SourceLocation SpecLoc, const char *Spec) { 8842 if (SpecLoc.isInvalid()) return; 8843 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8844 if (!Specifiers.empty()) Specifiers += " "; 8845 Specifiers += Spec; 8846 } 8847 8848 Sema &S; 8849 Sema::SemaDiagnosticBuilder Diagnostic; 8850 std::string Specifiers; 8851 }; 8852 } 8853 8854 /// Check the validity of a declarator that we parsed for a deduction-guide. 8855 /// These aren't actually declarators in the grammar, so we need to check that 8856 /// the user didn't specify any pieces that are not part of the deduction-guide 8857 /// grammar. 8858 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8859 StorageClass &SC) { 8860 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8861 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8862 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8863 8864 // C++ [temp.deduct.guide]p3: 8865 // A deduction-gide shall be declared in the same scope as the 8866 // corresponding class template. 8867 if (!CurContext->getRedeclContext()->Equals( 8868 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8869 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8870 << GuidedTemplateDecl; 8871 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8872 } 8873 8874 auto &DS = D.getMutableDeclSpec(); 8875 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8876 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8877 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8878 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 8879 BadSpecifierDiagnoser Diagnoser( 8880 *this, D.getIdentifierLoc(), 8881 diag::err_deduction_guide_invalid_specifier); 8882 8883 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8884 DS.ClearStorageClassSpecs(); 8885 SC = SC_None; 8886 8887 // 'explicit' is permitted. 8888 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8889 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8890 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8891 DS.ClearConstexprSpec(); 8892 8893 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8894 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8895 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8896 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8897 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8898 DS.ClearTypeQualifiers(); 8899 8900 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8901 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8902 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8903 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8904 DS.ClearTypeSpecType(); 8905 } 8906 8907 if (D.isInvalidType()) 8908 return; 8909 8910 // Check the declarator is simple enough. 8911 bool FoundFunction = false; 8912 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8913 if (Chunk.Kind == DeclaratorChunk::Paren) 8914 continue; 8915 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8916 Diag(D.getDeclSpec().getBeginLoc(), 8917 diag::err_deduction_guide_with_complex_decl) 8918 << D.getSourceRange(); 8919 break; 8920 } 8921 if (!Chunk.Fun.hasTrailingReturnType()) { 8922 Diag(D.getName().getBeginLoc(), 8923 diag::err_deduction_guide_no_trailing_return_type); 8924 break; 8925 } 8926 8927 // Check that the return type is written as a specialization of 8928 // the template specified as the deduction-guide's name. 8929 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8930 TypeSourceInfo *TSI = nullptr; 8931 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8932 assert(TSI && "deduction guide has valid type but invalid return type?"); 8933 bool AcceptableReturnType = false; 8934 bool MightInstantiateToSpecialization = false; 8935 if (auto RetTST = 8936 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8937 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8938 bool TemplateMatches = 8939 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8940 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8941 AcceptableReturnType = true; 8942 else { 8943 // This could still instantiate to the right type, unless we know it 8944 // names the wrong class template. 8945 auto *TD = SpecifiedName.getAsTemplateDecl(); 8946 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8947 !TemplateMatches); 8948 } 8949 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8950 MightInstantiateToSpecialization = true; 8951 } 8952 8953 if (!AcceptableReturnType) { 8954 Diag(TSI->getTypeLoc().getBeginLoc(), 8955 diag::err_deduction_guide_bad_trailing_return_type) 8956 << GuidedTemplate << TSI->getType() 8957 << MightInstantiateToSpecialization 8958 << TSI->getTypeLoc().getSourceRange(); 8959 } 8960 8961 // Keep going to check that we don't have any inner declarator pieces (we 8962 // could still have a function returning a pointer to a function). 8963 FoundFunction = true; 8964 } 8965 8966 if (D.isFunctionDefinition()) 8967 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8968 } 8969 8970 //===----------------------------------------------------------------------===// 8971 // Namespace Handling 8972 //===----------------------------------------------------------------------===// 8973 8974 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8975 /// reopened. 8976 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8977 SourceLocation Loc, 8978 IdentifierInfo *II, bool *IsInline, 8979 NamespaceDecl *PrevNS) { 8980 assert(*IsInline != PrevNS->isInline()); 8981 8982 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8983 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8984 // inline namespaces, with the intention of bringing names into namespace std. 8985 // 8986 // We support this just well enough to get that case working; this is not 8987 // sufficient to support reopening namespaces as inline in general. 8988 if (*IsInline && II && II->getName().startswith("__atomic") && 8989 S.getSourceManager().isInSystemHeader(Loc)) { 8990 // Mark all prior declarations of the namespace as inline. 8991 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8992 NS = NS->getPreviousDecl()) 8993 NS->setInline(*IsInline); 8994 // Patch up the lookup table for the containing namespace. This isn't really 8995 // correct, but it's good enough for this particular case. 8996 for (auto *I : PrevNS->decls()) 8997 if (auto *ND = dyn_cast<NamedDecl>(I)) 8998 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8999 return; 9000 } 9001 9002 if (PrevNS->isInline()) 9003 // The user probably just forgot the 'inline', so suggest that it 9004 // be added back. 9005 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 9006 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 9007 else 9008 S.Diag(Loc, diag::err_inline_namespace_mismatch); 9009 9010 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 9011 *IsInline = PrevNS->isInline(); 9012 } 9013 9014 /// ActOnStartNamespaceDef - This is called at the start of a namespace 9015 /// definition. 9016 Decl *Sema::ActOnStartNamespaceDef( 9017 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 9018 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 9019 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 9020 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 9021 // For anonymous namespace, take the location of the left brace. 9022 SourceLocation Loc = II ? IdentLoc : LBrace; 9023 bool IsInline = InlineLoc.isValid(); 9024 bool IsInvalid = false; 9025 bool IsStd = false; 9026 bool AddToKnown = false; 9027 Scope *DeclRegionScope = NamespcScope->getParent(); 9028 9029 NamespaceDecl *PrevNS = nullptr; 9030 if (II) { 9031 // C++ [namespace.def]p2: 9032 // The identifier in an original-namespace-definition shall not 9033 // have been previously defined in the declarative region in 9034 // which the original-namespace-definition appears. The 9035 // identifier in an original-namespace-definition is the name of 9036 // the namespace. Subsequently in that declarative region, it is 9037 // treated as an original-namespace-name. 9038 // 9039 // Since namespace names are unique in their scope, and we don't 9040 // look through using directives, just look for any ordinary names 9041 // as if by qualified name lookup. 9042 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 9043 ForExternalRedeclaration); 9044 LookupQualifiedName(R, CurContext->getRedeclContext()); 9045 NamedDecl *PrevDecl = 9046 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 9047 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 9048 9049 if (PrevNS) { 9050 // This is an extended namespace definition. 9051 if (IsInline != PrevNS->isInline()) 9052 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 9053 &IsInline, PrevNS); 9054 } else if (PrevDecl) { 9055 // This is an invalid name redefinition. 9056 Diag(Loc, diag::err_redefinition_different_kind) 9057 << II; 9058 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9059 IsInvalid = true; 9060 // Continue on to push Namespc as current DeclContext and return it. 9061 } else if (II->isStr("std") && 9062 CurContext->getRedeclContext()->isTranslationUnit()) { 9063 // This is the first "real" definition of the namespace "std", so update 9064 // our cache of the "std" namespace to point at this definition. 9065 PrevNS = getStdNamespace(); 9066 IsStd = true; 9067 AddToKnown = !IsInline; 9068 } else { 9069 // We've seen this namespace for the first time. 9070 AddToKnown = !IsInline; 9071 } 9072 } else { 9073 // Anonymous namespaces. 9074 9075 // Determine whether the parent already has an anonymous namespace. 9076 DeclContext *Parent = CurContext->getRedeclContext(); 9077 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 9078 PrevNS = TU->getAnonymousNamespace(); 9079 } else { 9080 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 9081 PrevNS = ND->getAnonymousNamespace(); 9082 } 9083 9084 if (PrevNS && IsInline != PrevNS->isInline()) 9085 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 9086 &IsInline, PrevNS); 9087 } 9088 9089 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 9090 StartLoc, Loc, II, PrevNS); 9091 if (IsInvalid) 9092 Namespc->setInvalidDecl(); 9093 9094 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 9095 AddPragmaAttributes(DeclRegionScope, Namespc); 9096 9097 // FIXME: Should we be merging attributes? 9098 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 9099 PushNamespaceVisibilityAttr(Attr, Loc); 9100 9101 if (IsStd) 9102 StdNamespace = Namespc; 9103 if (AddToKnown) 9104 KnownNamespaces[Namespc] = false; 9105 9106 if (II) { 9107 PushOnScopeChains(Namespc, DeclRegionScope); 9108 } else { 9109 // Link the anonymous namespace into its parent. 9110 DeclContext *Parent = CurContext->getRedeclContext(); 9111 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 9112 TU->setAnonymousNamespace(Namespc); 9113 } else { 9114 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 9115 } 9116 9117 CurContext->addDecl(Namespc); 9118 9119 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 9120 // behaves as if it were replaced by 9121 // namespace unique { /* empty body */ } 9122 // using namespace unique; 9123 // namespace unique { namespace-body } 9124 // where all occurrences of 'unique' in a translation unit are 9125 // replaced by the same identifier and this identifier differs 9126 // from all other identifiers in the entire program. 9127 9128 // We just create the namespace with an empty name and then add an 9129 // implicit using declaration, just like the standard suggests. 9130 // 9131 // CodeGen enforces the "universally unique" aspect by giving all 9132 // declarations semantically contained within an anonymous 9133 // namespace internal linkage. 9134 9135 if (!PrevNS) { 9136 UD = UsingDirectiveDecl::Create(Context, Parent, 9137 /* 'using' */ LBrace, 9138 /* 'namespace' */ SourceLocation(), 9139 /* qualifier */ NestedNameSpecifierLoc(), 9140 /* identifier */ SourceLocation(), 9141 Namespc, 9142 /* Ancestor */ Parent); 9143 UD->setImplicit(); 9144 Parent->addDecl(UD); 9145 } 9146 } 9147 9148 ActOnDocumentableDecl(Namespc); 9149 9150 // Although we could have an invalid decl (i.e. the namespace name is a 9151 // redefinition), push it as current DeclContext and try to continue parsing. 9152 // FIXME: We should be able to push Namespc here, so that the each DeclContext 9153 // for the namespace has the declarations that showed up in that particular 9154 // namespace definition. 9155 PushDeclContext(NamespcScope, Namespc); 9156 return Namespc; 9157 } 9158 9159 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 9160 /// is a namespace alias, returns the namespace it points to. 9161 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 9162 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 9163 return AD->getNamespace(); 9164 return dyn_cast_or_null<NamespaceDecl>(D); 9165 } 9166 9167 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 9168 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 9169 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 9170 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 9171 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 9172 Namespc->setRBraceLoc(RBrace); 9173 PopDeclContext(); 9174 if (Namespc->hasAttr<VisibilityAttr>()) 9175 PopPragmaVisibility(true, RBrace); 9176 // If this namespace contains an export-declaration, export it now. 9177 if (DeferredExportedNamespaces.erase(Namespc)) 9178 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 9179 } 9180 9181 CXXRecordDecl *Sema::getStdBadAlloc() const { 9182 return cast_or_null<CXXRecordDecl>( 9183 StdBadAlloc.get(Context.getExternalSource())); 9184 } 9185 9186 EnumDecl *Sema::getStdAlignValT() const { 9187 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 9188 } 9189 9190 NamespaceDecl *Sema::getStdNamespace() const { 9191 return cast_or_null<NamespaceDecl>( 9192 StdNamespace.get(Context.getExternalSource())); 9193 } 9194 9195 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 9196 if (!StdExperimentalNamespaceCache) { 9197 if (auto Std = getStdNamespace()) { 9198 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 9199 SourceLocation(), LookupNamespaceName); 9200 if (!LookupQualifiedName(Result, Std) || 9201 !(StdExperimentalNamespaceCache = 9202 Result.getAsSingle<NamespaceDecl>())) 9203 Result.suppressDiagnostics(); 9204 } 9205 } 9206 return StdExperimentalNamespaceCache; 9207 } 9208 9209 namespace { 9210 9211 enum UnsupportedSTLSelect { 9212 USS_InvalidMember, 9213 USS_MissingMember, 9214 USS_NonTrivial, 9215 USS_Other 9216 }; 9217 9218 struct InvalidSTLDiagnoser { 9219 Sema &S; 9220 SourceLocation Loc; 9221 QualType TyForDiags; 9222 9223 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 9224 const VarDecl *VD = nullptr) { 9225 { 9226 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 9227 << TyForDiags << ((int)Sel); 9228 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 9229 assert(!Name.empty()); 9230 D << Name; 9231 } 9232 } 9233 if (Sel == USS_InvalidMember) { 9234 S.Diag(VD->getLocation(), diag::note_var_declared_here) 9235 << VD << VD->getSourceRange(); 9236 } 9237 return QualType(); 9238 } 9239 }; 9240 } // namespace 9241 9242 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 9243 SourceLocation Loc) { 9244 assert(getLangOpts().CPlusPlus && 9245 "Looking for comparison category type outside of C++."); 9246 9247 // Check if we've already successfully checked the comparison category type 9248 // before. If so, skip checking it again. 9249 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 9250 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 9251 return Info->getType(); 9252 9253 // If lookup failed 9254 if (!Info) { 9255 std::string NameForDiags = "std::"; 9256 NameForDiags += ComparisonCategories::getCategoryString(Kind); 9257 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 9258 << NameForDiags; 9259 return QualType(); 9260 } 9261 9262 assert(Info->Kind == Kind); 9263 assert(Info->Record); 9264 9265 // Update the Record decl in case we encountered a forward declaration on our 9266 // first pass. FIXME: This is a bit of a hack. 9267 if (Info->Record->hasDefinition()) 9268 Info->Record = Info->Record->getDefinition(); 9269 9270 // Use an elaborated type for diagnostics which has a name containing the 9271 // prepended 'std' namespace but not any inline namespace names. 9272 QualType TyForDiags = [&]() { 9273 auto *NNS = 9274 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9275 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9276 }(); 9277 9278 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9279 return QualType(); 9280 9281 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9282 9283 if (!Info->Record->isTriviallyCopyable()) 9284 return UnsupportedSTLError(USS_NonTrivial); 9285 9286 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9287 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9288 // Tolerate empty base classes. 9289 if (Base->isEmpty()) 9290 continue; 9291 // Reject STL implementations which have at least one non-empty base. 9292 return UnsupportedSTLError(); 9293 } 9294 9295 // Check that the STL has implemented the types using a single integer field. 9296 // This expectation allows better codegen for builtin operators. We require: 9297 // (1) The class has exactly one field. 9298 // (2) The field is an integral or enumeration type. 9299 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9300 if (std::distance(FIt, FEnd) != 1 || 9301 !FIt->getType()->isIntegralOrEnumerationType()) { 9302 return UnsupportedSTLError(); 9303 } 9304 9305 // Build each of the require values and store them in Info. 9306 for (ComparisonCategoryResult CCR : 9307 ComparisonCategories::getPossibleResultsForType(Kind)) { 9308 StringRef MemName = ComparisonCategories::getResultString(CCR); 9309 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9310 9311 if (!ValInfo) 9312 return UnsupportedSTLError(USS_MissingMember, MemName); 9313 9314 VarDecl *VD = ValInfo->VD; 9315 assert(VD && "should not be null!"); 9316 9317 // Attempt to diagnose reasons why the STL definition of this type 9318 // might be foobar, including it failing to be a constant expression. 9319 // TODO Handle more ways the lookup or result can be invalid. 9320 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9321 !VD->checkInitIsICE()) 9322 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9323 9324 // Attempt to evaluate the var decl as a constant expression and extract 9325 // the value of its first field as a ICE. If this fails, the STL 9326 // implementation is not supported. 9327 if (!ValInfo->hasValidIntValue()) 9328 return UnsupportedSTLError(); 9329 9330 MarkVariableReferenced(Loc, VD); 9331 } 9332 9333 // We've successfully built the required types and expressions. Update 9334 // the cache and return the newly cached value. 9335 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9336 return Info->getType(); 9337 } 9338 9339 /// Retrieve the special "std" namespace, which may require us to 9340 /// implicitly define the namespace. 9341 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9342 if (!StdNamespace) { 9343 // The "std" namespace has not yet been defined, so build one implicitly. 9344 StdNamespace = NamespaceDecl::Create(Context, 9345 Context.getTranslationUnitDecl(), 9346 /*Inline=*/false, 9347 SourceLocation(), SourceLocation(), 9348 &PP.getIdentifierTable().get("std"), 9349 /*PrevDecl=*/nullptr); 9350 getStdNamespace()->setImplicit(true); 9351 } 9352 9353 return getStdNamespace(); 9354 } 9355 9356 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9357 assert(getLangOpts().CPlusPlus && 9358 "Looking for std::initializer_list outside of C++."); 9359 9360 // We're looking for implicit instantiations of 9361 // template <typename E> class std::initializer_list. 9362 9363 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9364 return false; 9365 9366 ClassTemplateDecl *Template = nullptr; 9367 const TemplateArgument *Arguments = nullptr; 9368 9369 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9370 9371 ClassTemplateSpecializationDecl *Specialization = 9372 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9373 if (!Specialization) 9374 return false; 9375 9376 Template = Specialization->getSpecializedTemplate(); 9377 Arguments = Specialization->getTemplateArgs().data(); 9378 } else if (const TemplateSpecializationType *TST = 9379 Ty->getAs<TemplateSpecializationType>()) { 9380 Template = dyn_cast_or_null<ClassTemplateDecl>( 9381 TST->getTemplateName().getAsTemplateDecl()); 9382 Arguments = TST->getArgs(); 9383 } 9384 if (!Template) 9385 return false; 9386 9387 if (!StdInitializerList) { 9388 // Haven't recognized std::initializer_list yet, maybe this is it. 9389 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9390 if (TemplateClass->getIdentifier() != 9391 &PP.getIdentifierTable().get("initializer_list") || 9392 !getStdNamespace()->InEnclosingNamespaceSetOf( 9393 TemplateClass->getDeclContext())) 9394 return false; 9395 // This is a template called std::initializer_list, but is it the right 9396 // template? 9397 TemplateParameterList *Params = Template->getTemplateParameters(); 9398 if (Params->getMinRequiredArguments() != 1) 9399 return false; 9400 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9401 return false; 9402 9403 // It's the right template. 9404 StdInitializerList = Template; 9405 } 9406 9407 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9408 return false; 9409 9410 // This is an instance of std::initializer_list. Find the argument type. 9411 if (Element) 9412 *Element = Arguments[0].getAsType(); 9413 return true; 9414 } 9415 9416 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9417 NamespaceDecl *Std = S.getStdNamespace(); 9418 if (!Std) { 9419 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9420 return nullptr; 9421 } 9422 9423 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9424 Loc, Sema::LookupOrdinaryName); 9425 if (!S.LookupQualifiedName(Result, Std)) { 9426 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9427 return nullptr; 9428 } 9429 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9430 if (!Template) { 9431 Result.suppressDiagnostics(); 9432 // We found something weird. Complain about the first thing we found. 9433 NamedDecl *Found = *Result.begin(); 9434 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9435 return nullptr; 9436 } 9437 9438 // We found some template called std::initializer_list. Now verify that it's 9439 // correct. 9440 TemplateParameterList *Params = Template->getTemplateParameters(); 9441 if (Params->getMinRequiredArguments() != 1 || 9442 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9443 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9444 return nullptr; 9445 } 9446 9447 return Template; 9448 } 9449 9450 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9451 if (!StdInitializerList) { 9452 StdInitializerList = LookupStdInitializerList(*this, Loc); 9453 if (!StdInitializerList) 9454 return QualType(); 9455 } 9456 9457 TemplateArgumentListInfo Args(Loc, Loc); 9458 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9459 Context.getTrivialTypeSourceInfo(Element, 9460 Loc))); 9461 return Context.getCanonicalType( 9462 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9463 } 9464 9465 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9466 // C++ [dcl.init.list]p2: 9467 // A constructor is an initializer-list constructor if its first parameter 9468 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9469 // std::initializer_list<E> for some type E, and either there are no other 9470 // parameters or else all other parameters have default arguments. 9471 if (Ctor->getNumParams() < 1 || 9472 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9473 return false; 9474 9475 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9476 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9477 ArgType = RT->getPointeeType().getUnqualifiedType(); 9478 9479 return isStdInitializerList(ArgType, nullptr); 9480 } 9481 9482 /// Determine whether a using statement is in a context where it will be 9483 /// apply in all contexts. 9484 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9485 switch (CurContext->getDeclKind()) { 9486 case Decl::TranslationUnit: 9487 return true; 9488 case Decl::LinkageSpec: 9489 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9490 default: 9491 return false; 9492 } 9493 } 9494 9495 namespace { 9496 9497 // Callback to only accept typo corrections that are namespaces. 9498 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 9499 public: 9500 bool ValidateCandidate(const TypoCorrection &candidate) override { 9501 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9502 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9503 return false; 9504 } 9505 9506 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9507 return std::make_unique<NamespaceValidatorCCC>(*this); 9508 } 9509 }; 9510 9511 } 9512 9513 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9514 CXXScopeSpec &SS, 9515 SourceLocation IdentLoc, 9516 IdentifierInfo *Ident) { 9517 R.clear(); 9518 NamespaceValidatorCCC CCC{}; 9519 if (TypoCorrection Corrected = 9520 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 9521 Sema::CTK_ErrorRecovery)) { 9522 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9523 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9524 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9525 Ident->getName().equals(CorrectedStr); 9526 S.diagnoseTypo(Corrected, 9527 S.PDiag(diag::err_using_directive_member_suggest) 9528 << Ident << DC << DroppedSpecifier << SS.getRange(), 9529 S.PDiag(diag::note_namespace_defined_here)); 9530 } else { 9531 S.diagnoseTypo(Corrected, 9532 S.PDiag(diag::err_using_directive_suggest) << Ident, 9533 S.PDiag(diag::note_namespace_defined_here)); 9534 } 9535 R.addDecl(Corrected.getFoundDecl()); 9536 return true; 9537 } 9538 return false; 9539 } 9540 9541 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9542 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9543 SourceLocation IdentLoc, 9544 IdentifierInfo *NamespcName, 9545 const ParsedAttributesView &AttrList) { 9546 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9547 assert(NamespcName && "Invalid NamespcName."); 9548 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9549 9550 // This can only happen along a recovery path. 9551 while (S->isTemplateParamScope()) 9552 S = S->getParent(); 9553 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9554 9555 UsingDirectiveDecl *UDir = nullptr; 9556 NestedNameSpecifier *Qualifier = nullptr; 9557 if (SS.isSet()) 9558 Qualifier = SS.getScopeRep(); 9559 9560 // Lookup namespace name. 9561 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9562 LookupParsedName(R, S, &SS); 9563 if (R.isAmbiguous()) 9564 return nullptr; 9565 9566 if (R.empty()) { 9567 R.clear(); 9568 // Allow "using namespace std;" or "using namespace ::std;" even if 9569 // "std" hasn't been defined yet, for GCC compatibility. 9570 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9571 NamespcName->isStr("std")) { 9572 Diag(IdentLoc, diag::ext_using_undefined_std); 9573 R.addDecl(getOrCreateStdNamespace()); 9574 R.resolveKind(); 9575 } 9576 // Otherwise, attempt typo correction. 9577 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9578 } 9579 9580 if (!R.empty()) { 9581 NamedDecl *Named = R.getRepresentativeDecl(); 9582 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9583 assert(NS && "expected namespace decl"); 9584 9585 // The use of a nested name specifier may trigger deprecation warnings. 9586 DiagnoseUseOfDecl(Named, IdentLoc); 9587 9588 // C++ [namespace.udir]p1: 9589 // A using-directive specifies that the names in the nominated 9590 // namespace can be used in the scope in which the 9591 // using-directive appears after the using-directive. During 9592 // unqualified name lookup (3.4.1), the names appear as if they 9593 // were declared in the nearest enclosing namespace which 9594 // contains both the using-directive and the nominated 9595 // namespace. [Note: in this context, "contains" means "contains 9596 // directly or indirectly". ] 9597 9598 // Find enclosing context containing both using-directive and 9599 // nominated namespace. 9600 DeclContext *CommonAncestor = NS; 9601 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9602 CommonAncestor = CommonAncestor->getParent(); 9603 9604 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9605 SS.getWithLocInContext(Context), 9606 IdentLoc, Named, CommonAncestor); 9607 9608 if (IsUsingDirectiveInToplevelContext(CurContext) && 9609 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9610 Diag(IdentLoc, diag::warn_using_directive_in_header); 9611 } 9612 9613 PushUsingDirective(S, UDir); 9614 } else { 9615 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9616 } 9617 9618 if (UDir) 9619 ProcessDeclAttributeList(S, UDir, AttrList); 9620 9621 return UDir; 9622 } 9623 9624 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9625 // If the scope has an associated entity and the using directive is at 9626 // namespace or translation unit scope, add the UsingDirectiveDecl into 9627 // its lookup structure so qualified name lookup can find it. 9628 DeclContext *Ctx = S->getEntity(); 9629 if (Ctx && !Ctx->isFunctionOrMethod()) 9630 Ctx->addDecl(UDir); 9631 else 9632 // Otherwise, it is at block scope. The using-directives will affect lookup 9633 // only to the end of the scope. 9634 S->PushUsingDirective(UDir); 9635 } 9636 9637 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9638 SourceLocation UsingLoc, 9639 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9640 UnqualifiedId &Name, 9641 SourceLocation EllipsisLoc, 9642 const ParsedAttributesView &AttrList) { 9643 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9644 9645 if (SS.isEmpty()) { 9646 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 9647 return nullptr; 9648 } 9649 9650 switch (Name.getKind()) { 9651 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9652 case UnqualifiedIdKind::IK_Identifier: 9653 case UnqualifiedIdKind::IK_OperatorFunctionId: 9654 case UnqualifiedIdKind::IK_LiteralOperatorId: 9655 case UnqualifiedIdKind::IK_ConversionFunctionId: 9656 break; 9657 9658 case UnqualifiedIdKind::IK_ConstructorName: 9659 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9660 // C++11 inheriting constructors. 9661 Diag(Name.getBeginLoc(), 9662 getLangOpts().CPlusPlus11 9663 ? diag::warn_cxx98_compat_using_decl_constructor 9664 : diag::err_using_decl_constructor) 9665 << SS.getRange(); 9666 9667 if (getLangOpts().CPlusPlus11) break; 9668 9669 return nullptr; 9670 9671 case UnqualifiedIdKind::IK_DestructorName: 9672 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 9673 return nullptr; 9674 9675 case UnqualifiedIdKind::IK_TemplateId: 9676 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 9677 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9678 return nullptr; 9679 9680 case UnqualifiedIdKind::IK_DeductionGuideName: 9681 llvm_unreachable("cannot parse qualified deduction guide name"); 9682 } 9683 9684 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9685 DeclarationName TargetName = TargetNameInfo.getName(); 9686 if (!TargetName) 9687 return nullptr; 9688 9689 // Warn about access declarations. 9690 if (UsingLoc.isInvalid()) { 9691 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 9692 ? diag::err_access_decl 9693 : diag::warn_access_decl_deprecated) 9694 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9695 } 9696 9697 if (EllipsisLoc.isInvalid()) { 9698 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9699 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9700 return nullptr; 9701 } else { 9702 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9703 !TargetNameInfo.containsUnexpandedParameterPack()) { 9704 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9705 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9706 EllipsisLoc = SourceLocation(); 9707 } 9708 } 9709 9710 NamedDecl *UD = 9711 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9712 SS, TargetNameInfo, EllipsisLoc, AttrList, 9713 /*IsInstantiation*/false); 9714 if (UD) 9715 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9716 9717 return UD; 9718 } 9719 9720 /// Determine whether a using declaration considers the given 9721 /// declarations as "equivalent", e.g., if they are redeclarations of 9722 /// the same entity or are both typedefs of the same type. 9723 static bool 9724 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9725 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9726 return true; 9727 9728 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9729 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9730 return Context.hasSameType(TD1->getUnderlyingType(), 9731 TD2->getUnderlyingType()); 9732 9733 return false; 9734 } 9735 9736 9737 /// Determines whether to create a using shadow decl for a particular 9738 /// decl, given the set of decls existing prior to this using lookup. 9739 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9740 const LookupResult &Previous, 9741 UsingShadowDecl *&PrevShadow) { 9742 // Diagnose finding a decl which is not from a base class of the 9743 // current class. We do this now because there are cases where this 9744 // function will silently decide not to build a shadow decl, which 9745 // will pre-empt further diagnostics. 9746 // 9747 // We don't need to do this in C++11 because we do the check once on 9748 // the qualifier. 9749 // 9750 // FIXME: diagnose the following if we care enough: 9751 // struct A { int foo; }; 9752 // struct B : A { using A::foo; }; 9753 // template <class T> struct C : A {}; 9754 // template <class T> struct D : C<T> { using B::foo; } // <--- 9755 // This is invalid (during instantiation) in C++03 because B::foo 9756 // resolves to the using decl in B, which is not a base class of D<T>. 9757 // We can't diagnose it immediately because C<T> is an unknown 9758 // specialization. The UsingShadowDecl in D<T> then points directly 9759 // to A::foo, which will look well-formed when we instantiate. 9760 // The right solution is to not collapse the shadow-decl chain. 9761 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9762 DeclContext *OrigDC = Orig->getDeclContext(); 9763 9764 // Handle enums and anonymous structs. 9765 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9766 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9767 while (OrigRec->isAnonymousStructOrUnion()) 9768 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9769 9770 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9771 if (OrigDC == CurContext) { 9772 Diag(Using->getLocation(), 9773 diag::err_using_decl_nested_name_specifier_is_current_class) 9774 << Using->getQualifierLoc().getSourceRange(); 9775 Diag(Orig->getLocation(), diag::note_using_decl_target); 9776 Using->setInvalidDecl(); 9777 return true; 9778 } 9779 9780 Diag(Using->getQualifierLoc().getBeginLoc(), 9781 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9782 << Using->getQualifier() 9783 << cast<CXXRecordDecl>(CurContext) 9784 << Using->getQualifierLoc().getSourceRange(); 9785 Diag(Orig->getLocation(), diag::note_using_decl_target); 9786 Using->setInvalidDecl(); 9787 return true; 9788 } 9789 } 9790 9791 if (Previous.empty()) return false; 9792 9793 NamedDecl *Target = Orig; 9794 if (isa<UsingShadowDecl>(Target)) 9795 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9796 9797 // If the target happens to be one of the previous declarations, we 9798 // don't have a conflict. 9799 // 9800 // FIXME: but we might be increasing its access, in which case we 9801 // should redeclare it. 9802 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9803 bool FoundEquivalentDecl = false; 9804 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9805 I != E; ++I) { 9806 NamedDecl *D = (*I)->getUnderlyingDecl(); 9807 // We can have UsingDecls in our Previous results because we use the same 9808 // LookupResult for checking whether the UsingDecl itself is a valid 9809 // redeclaration. 9810 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9811 continue; 9812 9813 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9814 // C++ [class.mem]p19: 9815 // If T is the name of a class, then [every named member other than 9816 // a non-static data member] shall have a name different from T 9817 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9818 !isa<IndirectFieldDecl>(Target) && 9819 !isa<UnresolvedUsingValueDecl>(Target) && 9820 DiagnoseClassNameShadow( 9821 CurContext, 9822 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9823 return true; 9824 } 9825 9826 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9827 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9828 PrevShadow = Shadow; 9829 FoundEquivalentDecl = true; 9830 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9831 // We don't conflict with an existing using shadow decl of an equivalent 9832 // declaration, but we're not a redeclaration of it. 9833 FoundEquivalentDecl = true; 9834 } 9835 9836 if (isVisible(D)) 9837 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9838 } 9839 9840 if (FoundEquivalentDecl) 9841 return false; 9842 9843 if (FunctionDecl *FD = Target->getAsFunction()) { 9844 NamedDecl *OldDecl = nullptr; 9845 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9846 /*IsForUsingDecl*/ true)) { 9847 case Ovl_Overload: 9848 return false; 9849 9850 case Ovl_NonFunction: 9851 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9852 break; 9853 9854 // We found a decl with the exact signature. 9855 case Ovl_Match: 9856 // If we're in a record, we want to hide the target, so we 9857 // return true (without a diagnostic) to tell the caller not to 9858 // build a shadow decl. 9859 if (CurContext->isRecord()) 9860 return true; 9861 9862 // If we're not in a record, this is an error. 9863 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9864 break; 9865 } 9866 9867 Diag(Target->getLocation(), diag::note_using_decl_target); 9868 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9869 Using->setInvalidDecl(); 9870 return true; 9871 } 9872 9873 // Target is not a function. 9874 9875 if (isa<TagDecl>(Target)) { 9876 // No conflict between a tag and a non-tag. 9877 if (!Tag) return false; 9878 9879 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9880 Diag(Target->getLocation(), diag::note_using_decl_target); 9881 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9882 Using->setInvalidDecl(); 9883 return true; 9884 } 9885 9886 // No conflict between a tag and a non-tag. 9887 if (!NonTag) return false; 9888 9889 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9890 Diag(Target->getLocation(), diag::note_using_decl_target); 9891 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9892 Using->setInvalidDecl(); 9893 return true; 9894 } 9895 9896 /// Determine whether a direct base class is a virtual base class. 9897 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9898 if (!Derived->getNumVBases()) 9899 return false; 9900 for (auto &B : Derived->bases()) 9901 if (B.getType()->getAsCXXRecordDecl() == Base) 9902 return B.isVirtual(); 9903 llvm_unreachable("not a direct base class"); 9904 } 9905 9906 /// Builds a shadow declaration corresponding to a 'using' declaration. 9907 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9908 UsingDecl *UD, 9909 NamedDecl *Orig, 9910 UsingShadowDecl *PrevDecl) { 9911 // If we resolved to another shadow declaration, just coalesce them. 9912 NamedDecl *Target = Orig; 9913 if (isa<UsingShadowDecl>(Target)) { 9914 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9915 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9916 } 9917 9918 NamedDecl *NonTemplateTarget = Target; 9919 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9920 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9921 9922 UsingShadowDecl *Shadow; 9923 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 9924 bool IsVirtualBase = 9925 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9926 UD->getQualifier()->getAsRecordDecl()); 9927 Shadow = ConstructorUsingShadowDecl::Create( 9928 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9929 } else { 9930 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9931 Target); 9932 } 9933 UD->addShadowDecl(Shadow); 9934 9935 Shadow->setAccess(UD->getAccess()); 9936 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9937 Shadow->setInvalidDecl(); 9938 9939 Shadow->setPreviousDecl(PrevDecl); 9940 9941 if (S) 9942 PushOnScopeChains(Shadow, S); 9943 else 9944 CurContext->addDecl(Shadow); 9945 9946 9947 return Shadow; 9948 } 9949 9950 /// Hides a using shadow declaration. This is required by the current 9951 /// using-decl implementation when a resolvable using declaration in a 9952 /// class is followed by a declaration which would hide or override 9953 /// one or more of the using decl's targets; for example: 9954 /// 9955 /// struct Base { void foo(int); }; 9956 /// struct Derived : Base { 9957 /// using Base::foo; 9958 /// void foo(int); 9959 /// }; 9960 /// 9961 /// The governing language is C++03 [namespace.udecl]p12: 9962 /// 9963 /// When a using-declaration brings names from a base class into a 9964 /// derived class scope, member functions in the derived class 9965 /// override and/or hide member functions with the same name and 9966 /// parameter types in a base class (rather than conflicting). 9967 /// 9968 /// There are two ways to implement this: 9969 /// (1) optimistically create shadow decls when they're not hidden 9970 /// by existing declarations, or 9971 /// (2) don't create any shadow decls (or at least don't make them 9972 /// visible) until we've fully parsed/instantiated the class. 9973 /// The problem with (1) is that we might have to retroactively remove 9974 /// a shadow decl, which requires several O(n) operations because the 9975 /// decl structures are (very reasonably) not designed for removal. 9976 /// (2) avoids this but is very fiddly and phase-dependent. 9977 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9978 if (Shadow->getDeclName().getNameKind() == 9979 DeclarationName::CXXConversionFunctionName) 9980 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9981 9982 // Remove it from the DeclContext... 9983 Shadow->getDeclContext()->removeDecl(Shadow); 9984 9985 // ...and the scope, if applicable... 9986 if (S) { 9987 S->RemoveDecl(Shadow); 9988 IdResolver.RemoveDecl(Shadow); 9989 } 9990 9991 // ...and the using decl. 9992 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9993 9994 // TODO: complain somehow if Shadow was used. It shouldn't 9995 // be possible for this to happen, because...? 9996 } 9997 9998 /// Find the base specifier for a base class with the given type. 9999 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 10000 QualType DesiredBase, 10001 bool &AnyDependentBases) { 10002 // Check whether the named type is a direct base class. 10003 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 10004 .getUnqualifiedType(); 10005 for (auto &Base : Derived->bases()) { 10006 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 10007 if (CanonicalDesiredBase == BaseType) 10008 return &Base; 10009 if (BaseType->isDependentType()) 10010 AnyDependentBases = true; 10011 } 10012 return nullptr; 10013 } 10014 10015 namespace { 10016 class UsingValidatorCCC final : public CorrectionCandidateCallback { 10017 public: 10018 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 10019 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 10020 : HasTypenameKeyword(HasTypenameKeyword), 10021 IsInstantiation(IsInstantiation), OldNNS(NNS), 10022 RequireMemberOf(RequireMemberOf) {} 10023 10024 bool ValidateCandidate(const TypoCorrection &Candidate) override { 10025 NamedDecl *ND = Candidate.getCorrectionDecl(); 10026 10027 // Keywords are not valid here. 10028 if (!ND || isa<NamespaceDecl>(ND)) 10029 return false; 10030 10031 // Completely unqualified names are invalid for a 'using' declaration. 10032 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 10033 return false; 10034 10035 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 10036 // reject. 10037 10038 if (RequireMemberOf) { 10039 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 10040 if (FoundRecord && FoundRecord->isInjectedClassName()) { 10041 // No-one ever wants a using-declaration to name an injected-class-name 10042 // of a base class, unless they're declaring an inheriting constructor. 10043 ASTContext &Ctx = ND->getASTContext(); 10044 if (!Ctx.getLangOpts().CPlusPlus11) 10045 return false; 10046 QualType FoundType = Ctx.getRecordType(FoundRecord); 10047 10048 // Check that the injected-class-name is named as a member of its own 10049 // type; we don't want to suggest 'using Derived::Base;', since that 10050 // means something else. 10051 NestedNameSpecifier *Specifier = 10052 Candidate.WillReplaceSpecifier() 10053 ? Candidate.getCorrectionSpecifier() 10054 : OldNNS; 10055 if (!Specifier->getAsType() || 10056 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 10057 return false; 10058 10059 // Check that this inheriting constructor declaration actually names a 10060 // direct base class of the current class. 10061 bool AnyDependentBases = false; 10062 if (!findDirectBaseWithType(RequireMemberOf, 10063 Ctx.getRecordType(FoundRecord), 10064 AnyDependentBases) && 10065 !AnyDependentBases) 10066 return false; 10067 } else { 10068 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 10069 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 10070 return false; 10071 10072 // FIXME: Check that the base class member is accessible? 10073 } 10074 } else { 10075 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 10076 if (FoundRecord && FoundRecord->isInjectedClassName()) 10077 return false; 10078 } 10079 10080 if (isa<TypeDecl>(ND)) 10081 return HasTypenameKeyword || !IsInstantiation; 10082 10083 return !HasTypenameKeyword; 10084 } 10085 10086 std::unique_ptr<CorrectionCandidateCallback> clone() override { 10087 return std::make_unique<UsingValidatorCCC>(*this); 10088 } 10089 10090 private: 10091 bool HasTypenameKeyword; 10092 bool IsInstantiation; 10093 NestedNameSpecifier *OldNNS; 10094 CXXRecordDecl *RequireMemberOf; 10095 }; 10096 } // end anonymous namespace 10097 10098 /// Builds a using declaration. 10099 /// 10100 /// \param IsInstantiation - Whether this call arises from an 10101 /// instantiation of an unresolved using declaration. We treat 10102 /// the lookup differently for these declarations. 10103 NamedDecl *Sema::BuildUsingDeclaration( 10104 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 10105 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 10106 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 10107 const ParsedAttributesView &AttrList, bool IsInstantiation) { 10108 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 10109 SourceLocation IdentLoc = NameInfo.getLoc(); 10110 assert(IdentLoc.isValid() && "Invalid TargetName location."); 10111 10112 // FIXME: We ignore attributes for now. 10113 10114 // For an inheriting constructor declaration, the name of the using 10115 // declaration is the name of a constructor in this class, not in the 10116 // base class. 10117 DeclarationNameInfo UsingName = NameInfo; 10118 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 10119 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 10120 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10121 Context.getCanonicalType(Context.getRecordType(RD)))); 10122 10123 // Do the redeclaration lookup in the current scope. 10124 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 10125 ForVisibleRedeclaration); 10126 Previous.setHideTags(false); 10127 if (S) { 10128 LookupName(Previous, S); 10129 10130 // It is really dumb that we have to do this. 10131 LookupResult::Filter F = Previous.makeFilter(); 10132 while (F.hasNext()) { 10133 NamedDecl *D = F.next(); 10134 if (!isDeclInScope(D, CurContext, S)) 10135 F.erase(); 10136 // If we found a local extern declaration that's not ordinarily visible, 10137 // and this declaration is being added to a non-block scope, ignore it. 10138 // We're only checking for scope conflicts here, not also for violations 10139 // of the linkage rules. 10140 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 10141 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 10142 F.erase(); 10143 } 10144 F.done(); 10145 } else { 10146 assert(IsInstantiation && "no scope in non-instantiation"); 10147 if (CurContext->isRecord()) 10148 LookupQualifiedName(Previous, CurContext); 10149 else { 10150 // No redeclaration check is needed here; in non-member contexts we 10151 // diagnosed all possible conflicts with other using-declarations when 10152 // building the template: 10153 // 10154 // For a dependent non-type using declaration, the only valid case is 10155 // if we instantiate to a single enumerator. We check for conflicts 10156 // between shadow declarations we introduce, and we check in the template 10157 // definition for conflicts between a non-type using declaration and any 10158 // other declaration, which together covers all cases. 10159 // 10160 // A dependent typename using declaration will never successfully 10161 // instantiate, since it will always name a class member, so we reject 10162 // that in the template definition. 10163 } 10164 } 10165 10166 // Check for invalid redeclarations. 10167 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 10168 SS, IdentLoc, Previous)) 10169 return nullptr; 10170 10171 // Check for bad qualifiers. 10172 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 10173 IdentLoc)) 10174 return nullptr; 10175 10176 DeclContext *LookupContext = computeDeclContext(SS); 10177 NamedDecl *D; 10178 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10179 if (!LookupContext || EllipsisLoc.isValid()) { 10180 if (HasTypenameKeyword) { 10181 // FIXME: not all declaration name kinds are legal here 10182 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 10183 UsingLoc, TypenameLoc, 10184 QualifierLoc, 10185 IdentLoc, NameInfo.getName(), 10186 EllipsisLoc); 10187 } else { 10188 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 10189 QualifierLoc, NameInfo, EllipsisLoc); 10190 } 10191 D->setAccess(AS); 10192 CurContext->addDecl(D); 10193 return D; 10194 } 10195 10196 auto Build = [&](bool Invalid) { 10197 UsingDecl *UD = 10198 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 10199 UsingName, HasTypenameKeyword); 10200 UD->setAccess(AS); 10201 CurContext->addDecl(UD); 10202 UD->setInvalidDecl(Invalid); 10203 return UD; 10204 }; 10205 auto BuildInvalid = [&]{ return Build(true); }; 10206 auto BuildValid = [&]{ return Build(false); }; 10207 10208 if (RequireCompleteDeclContext(SS, LookupContext)) 10209 return BuildInvalid(); 10210 10211 // Look up the target name. 10212 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10213 10214 // Unlike most lookups, we don't always want to hide tag 10215 // declarations: tag names are visible through the using declaration 10216 // even if hidden by ordinary names, *except* in a dependent context 10217 // where it's important for the sanity of two-phase lookup. 10218 if (!IsInstantiation) 10219 R.setHideTags(false); 10220 10221 // For the purposes of this lookup, we have a base object type 10222 // equal to that of the current context. 10223 if (CurContext->isRecord()) { 10224 R.setBaseObjectType( 10225 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 10226 } 10227 10228 LookupQualifiedName(R, LookupContext); 10229 10230 // Try to correct typos if possible. If constructor name lookup finds no 10231 // results, that means the named class has no explicit constructors, and we 10232 // suppressed declaring implicit ones (probably because it's dependent or 10233 // invalid). 10234 if (R.empty() && 10235 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 10236 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 10237 // it will believe that glibc provides a ::gets in cases where it does not, 10238 // and will try to pull it into namespace std with a using-declaration. 10239 // Just ignore the using-declaration in that case. 10240 auto *II = NameInfo.getName().getAsIdentifierInfo(); 10241 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 10242 CurContext->isStdNamespace() && 10243 isa<TranslationUnitDecl>(LookupContext) && 10244 getSourceManager().isInSystemHeader(UsingLoc)) 10245 return nullptr; 10246 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 10247 dyn_cast<CXXRecordDecl>(CurContext)); 10248 if (TypoCorrection Corrected = 10249 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 10250 CTK_ErrorRecovery)) { 10251 // We reject candidates where DroppedSpecifier == true, hence the 10252 // literal '0' below. 10253 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 10254 << NameInfo.getName() << LookupContext << 0 10255 << SS.getRange()); 10256 10257 // If we picked a correction with no attached Decl we can't do anything 10258 // useful with it, bail out. 10259 NamedDecl *ND = Corrected.getCorrectionDecl(); 10260 if (!ND) 10261 return BuildInvalid(); 10262 10263 // If we corrected to an inheriting constructor, handle it as one. 10264 auto *RD = dyn_cast<CXXRecordDecl>(ND); 10265 if (RD && RD->isInjectedClassName()) { 10266 // The parent of the injected class name is the class itself. 10267 RD = cast<CXXRecordDecl>(RD->getParent()); 10268 10269 // Fix up the information we'll use to build the using declaration. 10270 if (Corrected.WillReplaceSpecifier()) { 10271 NestedNameSpecifierLocBuilder Builder; 10272 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 10273 QualifierLoc.getSourceRange()); 10274 QualifierLoc = Builder.getWithLocInContext(Context); 10275 } 10276 10277 // In this case, the name we introduce is the name of a derived class 10278 // constructor. 10279 auto *CurClass = cast<CXXRecordDecl>(CurContext); 10280 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10281 Context.getCanonicalType(Context.getRecordType(CurClass)))); 10282 UsingName.setNamedTypeInfo(nullptr); 10283 for (auto *Ctor : LookupConstructors(RD)) 10284 R.addDecl(Ctor); 10285 R.resolveKind(); 10286 } else { 10287 // FIXME: Pick up all the declarations if we found an overloaded 10288 // function. 10289 UsingName.setName(ND->getDeclName()); 10290 R.addDecl(ND); 10291 } 10292 } else { 10293 Diag(IdentLoc, diag::err_no_member) 10294 << NameInfo.getName() << LookupContext << SS.getRange(); 10295 return BuildInvalid(); 10296 } 10297 } 10298 10299 if (R.isAmbiguous()) 10300 return BuildInvalid(); 10301 10302 if (HasTypenameKeyword) { 10303 // If we asked for a typename and got a non-type decl, error out. 10304 if (!R.getAsSingle<TypeDecl>()) { 10305 Diag(IdentLoc, diag::err_using_typename_non_type); 10306 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10307 Diag((*I)->getUnderlyingDecl()->getLocation(), 10308 diag::note_using_decl_target); 10309 return BuildInvalid(); 10310 } 10311 } else { 10312 // If we asked for a non-typename and we got a type, error out, 10313 // but only if this is an instantiation of an unresolved using 10314 // decl. Otherwise just silently find the type name. 10315 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10316 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10317 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10318 return BuildInvalid(); 10319 } 10320 } 10321 10322 // C++14 [namespace.udecl]p6: 10323 // A using-declaration shall not name a namespace. 10324 if (R.getAsSingle<NamespaceDecl>()) { 10325 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10326 << SS.getRange(); 10327 return BuildInvalid(); 10328 } 10329 10330 // C++14 [namespace.udecl]p7: 10331 // A using-declaration shall not name a scoped enumerator. 10332 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10333 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10334 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10335 << SS.getRange(); 10336 return BuildInvalid(); 10337 } 10338 } 10339 10340 UsingDecl *UD = BuildValid(); 10341 10342 // Some additional rules apply to inheriting constructors. 10343 if (UsingName.getName().getNameKind() == 10344 DeclarationName::CXXConstructorName) { 10345 // Suppress access diagnostics; the access check is instead performed at the 10346 // point of use for an inheriting constructor. 10347 R.suppressDiagnostics(); 10348 if (CheckInheritingConstructorUsingDecl(UD)) 10349 return UD; 10350 } 10351 10352 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10353 UsingShadowDecl *PrevDecl = nullptr; 10354 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10355 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10356 } 10357 10358 return UD; 10359 } 10360 10361 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10362 ArrayRef<NamedDecl *> Expansions) { 10363 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10364 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10365 isa<UsingPackDecl>(InstantiatedFrom)); 10366 10367 auto *UPD = 10368 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10369 UPD->setAccess(InstantiatedFrom->getAccess()); 10370 CurContext->addDecl(UPD); 10371 return UPD; 10372 } 10373 10374 /// Additional checks for a using declaration referring to a constructor name. 10375 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10376 assert(!UD->hasTypename() && "expecting a constructor name"); 10377 10378 const Type *SourceType = UD->getQualifier()->getAsType(); 10379 assert(SourceType && 10380 "Using decl naming constructor doesn't have type in scope spec."); 10381 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10382 10383 // Check whether the named type is a direct base class. 10384 bool AnyDependentBases = false; 10385 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10386 AnyDependentBases); 10387 if (!Base && !AnyDependentBases) { 10388 Diag(UD->getUsingLoc(), 10389 diag::err_using_decl_constructor_not_in_direct_base) 10390 << UD->getNameInfo().getSourceRange() 10391 << QualType(SourceType, 0) << TargetClass; 10392 UD->setInvalidDecl(); 10393 return true; 10394 } 10395 10396 if (Base) 10397 Base->setInheritConstructors(); 10398 10399 return false; 10400 } 10401 10402 /// Checks that the given using declaration is not an invalid 10403 /// redeclaration. Note that this is checking only for the using decl 10404 /// itself, not for any ill-formedness among the UsingShadowDecls. 10405 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10406 bool HasTypenameKeyword, 10407 const CXXScopeSpec &SS, 10408 SourceLocation NameLoc, 10409 const LookupResult &Prev) { 10410 NestedNameSpecifier *Qual = SS.getScopeRep(); 10411 10412 // C++03 [namespace.udecl]p8: 10413 // C++0x [namespace.udecl]p10: 10414 // A using-declaration is a declaration and can therefore be used 10415 // repeatedly where (and only where) multiple declarations are 10416 // allowed. 10417 // 10418 // That's in non-member contexts. 10419 if (!CurContext->getRedeclContext()->isRecord()) { 10420 // A dependent qualifier outside a class can only ever resolve to an 10421 // enumeration type. Therefore it conflicts with any other non-type 10422 // declaration in the same scope. 10423 // FIXME: How should we check for dependent type-type conflicts at block 10424 // scope? 10425 if (Qual->isDependent() && !HasTypenameKeyword) { 10426 for (auto *D : Prev) { 10427 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10428 bool OldCouldBeEnumerator = 10429 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10430 Diag(NameLoc, 10431 OldCouldBeEnumerator ? diag::err_redefinition 10432 : diag::err_redefinition_different_kind) 10433 << Prev.getLookupName(); 10434 Diag(D->getLocation(), diag::note_previous_definition); 10435 return true; 10436 } 10437 } 10438 } 10439 return false; 10440 } 10441 10442 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10443 NamedDecl *D = *I; 10444 10445 bool DTypename; 10446 NestedNameSpecifier *DQual; 10447 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10448 DTypename = UD->hasTypename(); 10449 DQual = UD->getQualifier(); 10450 } else if (UnresolvedUsingValueDecl *UD 10451 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10452 DTypename = false; 10453 DQual = UD->getQualifier(); 10454 } else if (UnresolvedUsingTypenameDecl *UD 10455 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10456 DTypename = true; 10457 DQual = UD->getQualifier(); 10458 } else continue; 10459 10460 // using decls differ if one says 'typename' and the other doesn't. 10461 // FIXME: non-dependent using decls? 10462 if (HasTypenameKeyword != DTypename) continue; 10463 10464 // using decls differ if they name different scopes (but note that 10465 // template instantiation can cause this check to trigger when it 10466 // didn't before instantiation). 10467 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10468 Context.getCanonicalNestedNameSpecifier(DQual)) 10469 continue; 10470 10471 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10472 Diag(D->getLocation(), diag::note_using_decl) << 1; 10473 return true; 10474 } 10475 10476 return false; 10477 } 10478 10479 10480 /// Checks that the given nested-name qualifier used in a using decl 10481 /// in the current context is appropriately related to the current 10482 /// scope. If an error is found, diagnoses it and returns true. 10483 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10484 bool HasTypename, 10485 const CXXScopeSpec &SS, 10486 const DeclarationNameInfo &NameInfo, 10487 SourceLocation NameLoc) { 10488 DeclContext *NamedContext = computeDeclContext(SS); 10489 10490 if (!CurContext->isRecord()) { 10491 // C++03 [namespace.udecl]p3: 10492 // C++0x [namespace.udecl]p8: 10493 // A using-declaration for a class member shall be a member-declaration. 10494 10495 // If we weren't able to compute a valid scope, it might validly be a 10496 // dependent class scope or a dependent enumeration unscoped scope. If 10497 // we have a 'typename' keyword, the scope must resolve to a class type. 10498 if ((HasTypename && !NamedContext) || 10499 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10500 auto *RD = NamedContext 10501 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10502 : nullptr; 10503 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10504 RD = nullptr; 10505 10506 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10507 << SS.getRange(); 10508 10509 // If we have a complete, non-dependent source type, try to suggest a 10510 // way to get the same effect. 10511 if (!RD) 10512 return true; 10513 10514 // Find what this using-declaration was referring to. 10515 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10516 R.setHideTags(false); 10517 R.suppressDiagnostics(); 10518 LookupQualifiedName(R, RD); 10519 10520 if (R.getAsSingle<TypeDecl>()) { 10521 if (getLangOpts().CPlusPlus11) { 10522 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10523 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10524 << 0 // alias declaration 10525 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10526 NameInfo.getName().getAsString() + 10527 " = "); 10528 } else { 10529 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10530 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 10531 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10532 << 1 // typedef declaration 10533 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10534 << FixItHint::CreateInsertion( 10535 InsertLoc, " " + NameInfo.getName().getAsString()); 10536 } 10537 } else if (R.getAsSingle<VarDecl>()) { 10538 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10539 // repeating the type of the static data member here. 10540 FixItHint FixIt; 10541 if (getLangOpts().CPlusPlus11) { 10542 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10543 FixIt = FixItHint::CreateReplacement( 10544 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10545 } 10546 10547 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10548 << 2 // reference declaration 10549 << FixIt; 10550 } else if (R.getAsSingle<EnumConstantDecl>()) { 10551 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10552 // repeating the type of the enumeration here, and we can't do so if 10553 // the type is anonymous. 10554 FixItHint FixIt; 10555 if (getLangOpts().CPlusPlus11) { 10556 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10557 FixIt = FixItHint::CreateReplacement( 10558 UsingLoc, 10559 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10560 } 10561 10562 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10563 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10564 << FixIt; 10565 } 10566 return true; 10567 } 10568 10569 // Otherwise, this might be valid. 10570 return false; 10571 } 10572 10573 // The current scope is a record. 10574 10575 // If the named context is dependent, we can't decide much. 10576 if (!NamedContext) { 10577 // FIXME: in C++0x, we can diagnose if we can prove that the 10578 // nested-name-specifier does not refer to a base class, which is 10579 // still possible in some cases. 10580 10581 // Otherwise we have to conservatively report that things might be 10582 // okay. 10583 return false; 10584 } 10585 10586 if (!NamedContext->isRecord()) { 10587 // Ideally this would point at the last name in the specifier, 10588 // but we don't have that level of source info. 10589 Diag(SS.getRange().getBegin(), 10590 diag::err_using_decl_nested_name_specifier_is_not_class) 10591 << SS.getScopeRep() << SS.getRange(); 10592 return true; 10593 } 10594 10595 if (!NamedContext->isDependentContext() && 10596 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10597 return true; 10598 10599 if (getLangOpts().CPlusPlus11) { 10600 // C++11 [namespace.udecl]p3: 10601 // In a using-declaration used as a member-declaration, the 10602 // nested-name-specifier shall name a base class of the class 10603 // being defined. 10604 10605 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10606 cast<CXXRecordDecl>(NamedContext))) { 10607 if (CurContext == NamedContext) { 10608 Diag(NameLoc, 10609 diag::err_using_decl_nested_name_specifier_is_current_class) 10610 << SS.getRange(); 10611 return true; 10612 } 10613 10614 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10615 Diag(SS.getRange().getBegin(), 10616 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10617 << SS.getScopeRep() 10618 << cast<CXXRecordDecl>(CurContext) 10619 << SS.getRange(); 10620 } 10621 return true; 10622 } 10623 10624 return false; 10625 } 10626 10627 // C++03 [namespace.udecl]p4: 10628 // A using-declaration used as a member-declaration shall refer 10629 // to a member of a base class of the class being defined [etc.]. 10630 10631 // Salient point: SS doesn't have to name a base class as long as 10632 // lookup only finds members from base classes. Therefore we can 10633 // diagnose here only if we can prove that that can't happen, 10634 // i.e. if the class hierarchies provably don't intersect. 10635 10636 // TODO: it would be nice if "definitely valid" results were cached 10637 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10638 // need to be repeated. 10639 10640 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10641 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10642 Bases.insert(Base); 10643 return true; 10644 }; 10645 10646 // Collect all bases. Return false if we find a dependent base. 10647 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10648 return false; 10649 10650 // Returns true if the base is dependent or is one of the accumulated base 10651 // classes. 10652 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10653 return !Bases.count(Base); 10654 }; 10655 10656 // Return false if the class has a dependent base or if it or one 10657 // of its bases is present in the base set of the current context. 10658 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10659 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10660 return false; 10661 10662 Diag(SS.getRange().getBegin(), 10663 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10664 << SS.getScopeRep() 10665 << cast<CXXRecordDecl>(CurContext) 10666 << SS.getRange(); 10667 10668 return true; 10669 } 10670 10671 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10672 MultiTemplateParamsArg TemplateParamLists, 10673 SourceLocation UsingLoc, UnqualifiedId &Name, 10674 const ParsedAttributesView &AttrList, 10675 TypeResult Type, Decl *DeclFromDeclSpec) { 10676 // Skip up to the relevant declaration scope. 10677 while (S->isTemplateParamScope()) 10678 S = S->getParent(); 10679 assert((S->getFlags() & Scope::DeclScope) && 10680 "got alias-declaration outside of declaration scope"); 10681 10682 if (Type.isInvalid()) 10683 return nullptr; 10684 10685 bool Invalid = false; 10686 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10687 TypeSourceInfo *TInfo = nullptr; 10688 GetTypeFromParser(Type.get(), &TInfo); 10689 10690 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10691 return nullptr; 10692 10693 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10694 UPPC_DeclarationType)) { 10695 Invalid = true; 10696 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10697 TInfo->getTypeLoc().getBeginLoc()); 10698 } 10699 10700 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10701 TemplateParamLists.size() 10702 ? forRedeclarationInCurContext() 10703 : ForVisibleRedeclaration); 10704 LookupName(Previous, S); 10705 10706 // Warn about shadowing the name of a template parameter. 10707 if (Previous.isSingleResult() && 10708 Previous.getFoundDecl()->isTemplateParameter()) { 10709 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10710 Previous.clear(); 10711 } 10712 10713 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10714 "name in alias declaration must be an identifier"); 10715 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10716 Name.StartLocation, 10717 Name.Identifier, TInfo); 10718 10719 NewTD->setAccess(AS); 10720 10721 if (Invalid) 10722 NewTD->setInvalidDecl(); 10723 10724 ProcessDeclAttributeList(S, NewTD, AttrList); 10725 AddPragmaAttributes(S, NewTD); 10726 10727 CheckTypedefForVariablyModifiedType(S, NewTD); 10728 Invalid |= NewTD->isInvalidDecl(); 10729 10730 bool Redeclaration = false; 10731 10732 NamedDecl *NewND; 10733 if (TemplateParamLists.size()) { 10734 TypeAliasTemplateDecl *OldDecl = nullptr; 10735 TemplateParameterList *OldTemplateParams = nullptr; 10736 10737 if (TemplateParamLists.size() != 1) { 10738 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10739 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10740 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10741 } 10742 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10743 10744 // Check that we can declare a template here. 10745 if (CheckTemplateDeclScope(S, TemplateParams)) 10746 return nullptr; 10747 10748 // Only consider previous declarations in the same scope. 10749 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10750 /*ExplicitInstantiationOrSpecialization*/false); 10751 if (!Previous.empty()) { 10752 Redeclaration = true; 10753 10754 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10755 if (!OldDecl && !Invalid) { 10756 Diag(UsingLoc, diag::err_redefinition_different_kind) 10757 << Name.Identifier; 10758 10759 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10760 if (OldD->getLocation().isValid()) 10761 Diag(OldD->getLocation(), diag::note_previous_definition); 10762 10763 Invalid = true; 10764 } 10765 10766 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10767 if (TemplateParameterListsAreEqual(TemplateParams, 10768 OldDecl->getTemplateParameters(), 10769 /*Complain=*/true, 10770 TPL_TemplateMatch)) 10771 OldTemplateParams = 10772 OldDecl->getMostRecentDecl()->getTemplateParameters(); 10773 else 10774 Invalid = true; 10775 10776 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10777 if (!Invalid && 10778 !Context.hasSameType(OldTD->getUnderlyingType(), 10779 NewTD->getUnderlyingType())) { 10780 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10781 // but we can't reasonably accept it. 10782 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10783 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10784 if (OldTD->getLocation().isValid()) 10785 Diag(OldTD->getLocation(), diag::note_previous_definition); 10786 Invalid = true; 10787 } 10788 } 10789 } 10790 10791 // Merge any previous default template arguments into our parameters, 10792 // and check the parameter list. 10793 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10794 TPC_TypeAliasTemplate)) 10795 return nullptr; 10796 10797 TypeAliasTemplateDecl *NewDecl = 10798 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10799 Name.Identifier, TemplateParams, 10800 NewTD); 10801 NewTD->setDescribedAliasTemplate(NewDecl); 10802 10803 NewDecl->setAccess(AS); 10804 10805 if (Invalid) 10806 NewDecl->setInvalidDecl(); 10807 else if (OldDecl) { 10808 NewDecl->setPreviousDecl(OldDecl); 10809 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10810 } 10811 10812 NewND = NewDecl; 10813 } else { 10814 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10815 setTagNameForLinkagePurposes(TD, NewTD); 10816 handleTagNumbering(TD, S); 10817 } 10818 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10819 NewND = NewTD; 10820 } 10821 10822 PushOnScopeChains(NewND, S); 10823 ActOnDocumentableDecl(NewND); 10824 return NewND; 10825 } 10826 10827 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10828 SourceLocation AliasLoc, 10829 IdentifierInfo *Alias, CXXScopeSpec &SS, 10830 SourceLocation IdentLoc, 10831 IdentifierInfo *Ident) { 10832 10833 // Lookup the namespace name. 10834 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10835 LookupParsedName(R, S, &SS); 10836 10837 if (R.isAmbiguous()) 10838 return nullptr; 10839 10840 if (R.empty()) { 10841 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10842 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10843 return nullptr; 10844 } 10845 } 10846 assert(!R.isAmbiguous() && !R.empty()); 10847 NamedDecl *ND = R.getRepresentativeDecl(); 10848 10849 // Check if we have a previous declaration with the same name. 10850 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10851 ForVisibleRedeclaration); 10852 LookupName(PrevR, S); 10853 10854 // Check we're not shadowing a template parameter. 10855 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10856 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10857 PrevR.clear(); 10858 } 10859 10860 // Filter out any other lookup result from an enclosing scope. 10861 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10862 /*AllowInlineNamespace*/false); 10863 10864 // Find the previous declaration and check that we can redeclare it. 10865 NamespaceAliasDecl *Prev = nullptr; 10866 if (PrevR.isSingleResult()) { 10867 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10868 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10869 // We already have an alias with the same name that points to the same 10870 // namespace; check that it matches. 10871 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10872 Prev = AD; 10873 } else if (isVisible(PrevDecl)) { 10874 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10875 << Alias; 10876 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10877 << AD->getNamespace(); 10878 return nullptr; 10879 } 10880 } else if (isVisible(PrevDecl)) { 10881 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10882 ? diag::err_redefinition 10883 : diag::err_redefinition_different_kind; 10884 Diag(AliasLoc, DiagID) << Alias; 10885 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10886 return nullptr; 10887 } 10888 } 10889 10890 // The use of a nested name specifier may trigger deprecation warnings. 10891 DiagnoseUseOfDecl(ND, IdentLoc); 10892 10893 NamespaceAliasDecl *AliasDecl = 10894 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10895 Alias, SS.getWithLocInContext(Context), 10896 IdentLoc, ND); 10897 if (Prev) 10898 AliasDecl->setPreviousDecl(Prev); 10899 10900 PushOnScopeChains(AliasDecl, S); 10901 return AliasDecl; 10902 } 10903 10904 namespace { 10905 struct SpecialMemberExceptionSpecInfo 10906 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10907 SourceLocation Loc; 10908 Sema::ImplicitExceptionSpecification ExceptSpec; 10909 10910 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10911 Sema::CXXSpecialMember CSM, 10912 Sema::InheritedConstructorInfo *ICI, 10913 SourceLocation Loc) 10914 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10915 10916 bool visitBase(CXXBaseSpecifier *Base); 10917 bool visitField(FieldDecl *FD); 10918 10919 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10920 unsigned Quals); 10921 10922 void visitSubobjectCall(Subobject Subobj, 10923 Sema::SpecialMemberOverloadResult SMOR); 10924 }; 10925 } 10926 10927 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10928 auto *RT = Base->getType()->getAs<RecordType>(); 10929 if (!RT) 10930 return false; 10931 10932 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10933 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10934 if (auto *BaseCtor = SMOR.getMethod()) { 10935 visitSubobjectCall(Base, BaseCtor); 10936 return false; 10937 } 10938 10939 visitClassSubobject(BaseClass, Base, 0); 10940 return false; 10941 } 10942 10943 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10944 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10945 Expr *E = FD->getInClassInitializer(); 10946 if (!E) 10947 // FIXME: It's a little wasteful to build and throw away a 10948 // CXXDefaultInitExpr here. 10949 // FIXME: We should have a single context note pointing at Loc, and 10950 // this location should be MD->getLocation() instead, since that's 10951 // the location where we actually use the default init expression. 10952 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10953 if (E) 10954 ExceptSpec.CalledExpr(E); 10955 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10956 ->getAs<RecordType>()) { 10957 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10958 FD->getType().getCVRQualifiers()); 10959 } 10960 return false; 10961 } 10962 10963 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10964 Subobject Subobj, 10965 unsigned Quals) { 10966 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10967 bool IsMutable = Field && Field->isMutable(); 10968 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10969 } 10970 10971 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10972 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10973 // Note, if lookup fails, it doesn't matter what exception specification we 10974 // choose because the special member will be deleted. 10975 if (CXXMethodDecl *MD = SMOR.getMethod()) 10976 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10977 } 10978 10979 namespace { 10980 /// RAII object to register a special member as being currently declared. 10981 struct ComputingExceptionSpec { 10982 Sema &S; 10983 10984 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 10985 : S(S) { 10986 Sema::CodeSynthesisContext Ctx; 10987 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 10988 Ctx.PointOfInstantiation = Loc; 10989 Ctx.Entity = MD; 10990 S.pushCodeSynthesisContext(Ctx); 10991 } 10992 ~ComputingExceptionSpec() { 10993 S.popCodeSynthesisContext(); 10994 } 10995 }; 10996 } 10997 10998 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 10999 llvm::APSInt Result; 11000 ExprResult Converted = CheckConvertedConstantExpression( 11001 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 11002 ExplicitSpec.setExpr(Converted.get()); 11003 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 11004 ExplicitSpec.setKind(Result.getBoolValue() 11005 ? ExplicitSpecKind::ResolvedTrue 11006 : ExplicitSpecKind::ResolvedFalse); 11007 return true; 11008 } 11009 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 11010 return false; 11011 } 11012 11013 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 11014 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 11015 if (!ExplicitExpr->isTypeDependent()) 11016 tryResolveExplicitSpecifier(ES); 11017 return ES; 11018 } 11019 11020 static Sema::ImplicitExceptionSpecification 11021 ComputeDefaultedSpecialMemberExceptionSpec( 11022 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 11023 Sema::InheritedConstructorInfo *ICI) { 11024 ComputingExceptionSpec CES(S, MD, Loc); 11025 11026 CXXRecordDecl *ClassDecl = MD->getParent(); 11027 11028 // C++ [except.spec]p14: 11029 // An implicitly declared special member function (Clause 12) shall have an 11030 // exception-specification. [...] 11031 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 11032 if (ClassDecl->isInvalidDecl()) 11033 return Info.ExceptSpec; 11034 11035 // FIXME: If this diagnostic fires, we're probably missing a check for 11036 // attempting to resolve an exception specification before it's known 11037 // at a higher level. 11038 if (S.RequireCompleteType(MD->getLocation(), 11039 S.Context.getRecordType(ClassDecl), 11040 diag::err_exception_spec_incomplete_type)) 11041 return Info.ExceptSpec; 11042 11043 // C++1z [except.spec]p7: 11044 // [Look for exceptions thrown by] a constructor selected [...] to 11045 // initialize a potentially constructed subobject, 11046 // C++1z [except.spec]p8: 11047 // The exception specification for an implicitly-declared destructor, or a 11048 // destructor without a noexcept-specifier, is potentially-throwing if and 11049 // only if any of the destructors for any of its potentially constructed 11050 // subojects is potentially throwing. 11051 // FIXME: We respect the first rule but ignore the "potentially constructed" 11052 // in the second rule to resolve a core issue (no number yet) that would have 11053 // us reject: 11054 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 11055 // struct B : A {}; 11056 // struct C : B { void f(); }; 11057 // ... due to giving B::~B() a non-throwing exception specification. 11058 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 11059 : Info.VisitAllBases); 11060 11061 return Info.ExceptSpec; 11062 } 11063 11064 namespace { 11065 /// RAII object to register a special member as being currently declared. 11066 struct DeclaringSpecialMember { 11067 Sema &S; 11068 Sema::SpecialMemberDecl D; 11069 Sema::ContextRAII SavedContext; 11070 bool WasAlreadyBeingDeclared; 11071 11072 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 11073 : S(S), D(RD, CSM), SavedContext(S, RD) { 11074 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 11075 if (WasAlreadyBeingDeclared) 11076 // This almost never happens, but if it does, ensure that our cache 11077 // doesn't contain a stale result. 11078 S.SpecialMemberCache.clear(); 11079 else { 11080 // Register a note to be produced if we encounter an error while 11081 // declaring the special member. 11082 Sema::CodeSynthesisContext Ctx; 11083 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 11084 // FIXME: We don't have a location to use here. Using the class's 11085 // location maintains the fiction that we declare all special members 11086 // with the class, but (1) it's not clear that lying about that helps our 11087 // users understand what's going on, and (2) there may be outer contexts 11088 // on the stack (some of which are relevant) and printing them exposes 11089 // our lies. 11090 Ctx.PointOfInstantiation = RD->getLocation(); 11091 Ctx.Entity = RD; 11092 Ctx.SpecialMember = CSM; 11093 S.pushCodeSynthesisContext(Ctx); 11094 } 11095 } 11096 ~DeclaringSpecialMember() { 11097 if (!WasAlreadyBeingDeclared) { 11098 S.SpecialMembersBeingDeclared.erase(D); 11099 S.popCodeSynthesisContext(); 11100 } 11101 } 11102 11103 /// Are we already trying to declare this special member? 11104 bool isAlreadyBeingDeclared() const { 11105 return WasAlreadyBeingDeclared; 11106 } 11107 }; 11108 } 11109 11110 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 11111 // Look up any existing declarations, but don't trigger declaration of all 11112 // implicit special members with this name. 11113 DeclarationName Name = FD->getDeclName(); 11114 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 11115 ForExternalRedeclaration); 11116 for (auto *D : FD->getParent()->lookup(Name)) 11117 if (auto *Acceptable = R.getAcceptableDecl(D)) 11118 R.addDecl(Acceptable); 11119 R.resolveKind(); 11120 R.suppressDiagnostics(); 11121 11122 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 11123 } 11124 11125 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 11126 QualType ResultTy, 11127 ArrayRef<QualType> Args) { 11128 // Build an exception specification pointing back at this constructor. 11129 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 11130 11131 if (getLangOpts().OpenCLCPlusPlus) { 11132 // OpenCL: Implicitly defaulted special member are of the generic address 11133 // space. 11134 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic); 11135 } 11136 11137 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 11138 SpecialMem->setType(QT); 11139 } 11140 11141 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 11142 CXXRecordDecl *ClassDecl) { 11143 // C++ [class.ctor]p5: 11144 // A default constructor for a class X is a constructor of class X 11145 // that can be called without an argument. If there is no 11146 // user-declared constructor for class X, a default constructor is 11147 // implicitly declared. An implicitly-declared default constructor 11148 // is an inline public member of its class. 11149 assert(ClassDecl->needsImplicitDefaultConstructor() && 11150 "Should not build implicit default constructor!"); 11151 11152 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 11153 if (DSM.isAlreadyBeingDeclared()) 11154 return nullptr; 11155 11156 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11157 CXXDefaultConstructor, 11158 false); 11159 11160 // Create the actual constructor declaration. 11161 CanQualType ClassType 11162 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11163 SourceLocation ClassLoc = ClassDecl->getLocation(); 11164 DeclarationName Name 11165 = Context.DeclarationNames.getCXXConstructorName(ClassType); 11166 DeclarationNameInfo NameInfo(Name, ClassLoc); 11167 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 11168 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 11169 /*TInfo=*/nullptr, ExplicitSpecifier(), 11170 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11171 Constexpr ? CSK_constexpr : CSK_unspecified); 11172 DefaultCon->setAccess(AS_public); 11173 DefaultCon->setDefaulted(); 11174 11175 if (getLangOpts().CUDA) { 11176 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 11177 DefaultCon, 11178 /* ConstRHS */ false, 11179 /* Diagnose */ false); 11180 } 11181 11182 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 11183 11184 // We don't need to use SpecialMemberIsTrivial here; triviality for default 11185 // constructors is easy to compute. 11186 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 11187 11188 // Note that we have declared this constructor. 11189 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 11190 11191 Scope *S = getScopeForContext(ClassDecl); 11192 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 11193 11194 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 11195 SetDeclDeleted(DefaultCon, ClassLoc); 11196 11197 if (S) 11198 PushOnScopeChains(DefaultCon, S, false); 11199 ClassDecl->addDecl(DefaultCon); 11200 11201 return DefaultCon; 11202 } 11203 11204 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 11205 CXXConstructorDecl *Constructor) { 11206 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 11207 !Constructor->doesThisDeclarationHaveABody() && 11208 !Constructor->isDeleted()) && 11209 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 11210 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11211 return; 11212 11213 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11214 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 11215 11216 SynthesizedFunctionScope Scope(*this, Constructor); 11217 11218 // The exception specification is needed because we are defining the 11219 // function. 11220 ResolveExceptionSpec(CurrentLocation, 11221 Constructor->getType()->castAs<FunctionProtoType>()); 11222 MarkVTableUsed(CurrentLocation, ClassDecl); 11223 11224 // Add a context note for diagnostics produced after this point. 11225 Scope.addContextNote(CurrentLocation); 11226 11227 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 11228 Constructor->setInvalidDecl(); 11229 return; 11230 } 11231 11232 SourceLocation Loc = Constructor->getEndLoc().isValid() 11233 ? Constructor->getEndLoc() 11234 : Constructor->getLocation(); 11235 Constructor->setBody(new (Context) CompoundStmt(Loc)); 11236 Constructor->markUsed(Context); 11237 11238 if (ASTMutationListener *L = getASTMutationListener()) { 11239 L->CompletedImplicitDefinition(Constructor); 11240 } 11241 11242 DiagnoseUninitializedFields(*this, Constructor); 11243 } 11244 11245 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 11246 // Perform any delayed checks on exception specifications. 11247 CheckDelayedMemberExceptionSpecs(); 11248 } 11249 11250 /// Find or create the fake constructor we synthesize to model constructing an 11251 /// object of a derived class via a constructor of a base class. 11252 CXXConstructorDecl * 11253 Sema::findInheritingConstructor(SourceLocation Loc, 11254 CXXConstructorDecl *BaseCtor, 11255 ConstructorUsingShadowDecl *Shadow) { 11256 CXXRecordDecl *Derived = Shadow->getParent(); 11257 SourceLocation UsingLoc = Shadow->getLocation(); 11258 11259 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 11260 // For now we use the name of the base class constructor as a member of the 11261 // derived class to indicate a (fake) inherited constructor name. 11262 DeclarationName Name = BaseCtor->getDeclName(); 11263 11264 // Check to see if we already have a fake constructor for this inherited 11265 // constructor call. 11266 for (NamedDecl *Ctor : Derived->lookup(Name)) 11267 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 11268 ->getInheritedConstructor() 11269 .getConstructor(), 11270 BaseCtor)) 11271 return cast<CXXConstructorDecl>(Ctor); 11272 11273 DeclarationNameInfo NameInfo(Name, UsingLoc); 11274 TypeSourceInfo *TInfo = 11275 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 11276 FunctionProtoTypeLoc ProtoLoc = 11277 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 11278 11279 // Check the inherited constructor is valid and find the list of base classes 11280 // from which it was inherited. 11281 InheritedConstructorInfo ICI(*this, Loc, Shadow); 11282 11283 bool Constexpr = 11284 BaseCtor->isConstexpr() && 11285 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 11286 false, BaseCtor, &ICI); 11287 11288 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 11289 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 11290 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 11291 /*isImplicitlyDeclared=*/true, 11292 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 11293 InheritedConstructor(Shadow, BaseCtor)); 11294 if (Shadow->isInvalidDecl()) 11295 DerivedCtor->setInvalidDecl(); 11296 11297 // Build an unevaluated exception specification for this fake constructor. 11298 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 11299 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11300 EPI.ExceptionSpec.Type = EST_Unevaluated; 11301 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 11302 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 11303 FPT->getParamTypes(), EPI)); 11304 11305 // Build the parameter declarations. 11306 SmallVector<ParmVarDecl *, 16> ParamDecls; 11307 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 11308 TypeSourceInfo *TInfo = 11309 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 11310 ParmVarDecl *PD = ParmVarDecl::Create( 11311 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 11312 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 11313 PD->setScopeInfo(0, I); 11314 PD->setImplicit(); 11315 // Ensure attributes are propagated onto parameters (this matters for 11316 // format, pass_object_size, ...). 11317 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 11318 ParamDecls.push_back(PD); 11319 ProtoLoc.setParam(I, PD); 11320 } 11321 11322 // Set up the new constructor. 11323 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 11324 DerivedCtor->setAccess(BaseCtor->getAccess()); 11325 DerivedCtor->setParams(ParamDecls); 11326 Derived->addDecl(DerivedCtor); 11327 11328 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 11329 SetDeclDeleted(DerivedCtor, UsingLoc); 11330 11331 return DerivedCtor; 11332 } 11333 11334 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 11335 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 11336 Ctor->getInheritedConstructor().getShadowDecl()); 11337 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 11338 /*Diagnose*/true); 11339 } 11340 11341 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 11342 CXXConstructorDecl *Constructor) { 11343 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11344 assert(Constructor->getInheritedConstructor() && 11345 !Constructor->doesThisDeclarationHaveABody() && 11346 !Constructor->isDeleted()); 11347 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11348 return; 11349 11350 // Initializations are performed "as if by a defaulted default constructor", 11351 // so enter the appropriate scope. 11352 SynthesizedFunctionScope Scope(*this, Constructor); 11353 11354 // The exception specification is needed because we are defining the 11355 // function. 11356 ResolveExceptionSpec(CurrentLocation, 11357 Constructor->getType()->castAs<FunctionProtoType>()); 11358 MarkVTableUsed(CurrentLocation, ClassDecl); 11359 11360 // Add a context note for diagnostics produced after this point. 11361 Scope.addContextNote(CurrentLocation); 11362 11363 ConstructorUsingShadowDecl *Shadow = 11364 Constructor->getInheritedConstructor().getShadowDecl(); 11365 CXXConstructorDecl *InheritedCtor = 11366 Constructor->getInheritedConstructor().getConstructor(); 11367 11368 // [class.inhctor.init]p1: 11369 // initialization proceeds as if a defaulted default constructor is used to 11370 // initialize the D object and each base class subobject from which the 11371 // constructor was inherited 11372 11373 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11374 CXXRecordDecl *RD = Shadow->getParent(); 11375 SourceLocation InitLoc = Shadow->getLocation(); 11376 11377 // Build explicit initializers for all base classes from which the 11378 // constructor was inherited. 11379 SmallVector<CXXCtorInitializer*, 8> Inits; 11380 for (bool VBase : {false, true}) { 11381 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11382 if (B.isVirtual() != VBase) 11383 continue; 11384 11385 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11386 if (!BaseRD) 11387 continue; 11388 11389 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11390 if (!BaseCtor.first) 11391 continue; 11392 11393 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11394 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11395 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11396 11397 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11398 Inits.push_back(new (Context) CXXCtorInitializer( 11399 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11400 SourceLocation())); 11401 } 11402 } 11403 11404 // We now proceed as if for a defaulted default constructor, with the relevant 11405 // initializers replaced. 11406 11407 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11408 Constructor->setInvalidDecl(); 11409 return; 11410 } 11411 11412 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11413 Constructor->markUsed(Context); 11414 11415 if (ASTMutationListener *L = getASTMutationListener()) { 11416 L->CompletedImplicitDefinition(Constructor); 11417 } 11418 11419 DiagnoseUninitializedFields(*this, Constructor); 11420 } 11421 11422 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11423 // C++ [class.dtor]p2: 11424 // If a class has no user-declared destructor, a destructor is 11425 // declared implicitly. An implicitly-declared destructor is an 11426 // inline public member of its class. 11427 assert(ClassDecl->needsImplicitDestructor()); 11428 11429 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11430 if (DSM.isAlreadyBeingDeclared()) 11431 return nullptr; 11432 11433 // Create the actual destructor declaration. 11434 CanQualType ClassType 11435 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11436 SourceLocation ClassLoc = ClassDecl->getLocation(); 11437 DeclarationName Name 11438 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11439 DeclarationNameInfo NameInfo(Name, ClassLoc); 11440 CXXDestructorDecl *Destructor 11441 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11442 QualType(), nullptr, /*isInline=*/true, 11443 /*isImplicitlyDeclared=*/true); 11444 Destructor->setAccess(AS_public); 11445 Destructor->setDefaulted(); 11446 11447 if (getLangOpts().CUDA) { 11448 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11449 Destructor, 11450 /* ConstRHS */ false, 11451 /* Diagnose */ false); 11452 } 11453 11454 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 11455 11456 // We don't need to use SpecialMemberIsTrivial here; triviality for 11457 // destructors is easy to compute. 11458 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11459 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11460 ClassDecl->hasTrivialDestructorForCall()); 11461 11462 // Note that we have declared this destructor. 11463 ++getASTContext().NumImplicitDestructorsDeclared; 11464 11465 Scope *S = getScopeForContext(ClassDecl); 11466 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11467 11468 // We can't check whether an implicit destructor is deleted before we complete 11469 // the definition of the class, because its validity depends on the alignment 11470 // of the class. We'll check this from ActOnFields once the class is complete. 11471 if (ClassDecl->isCompleteDefinition() && 11472 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11473 SetDeclDeleted(Destructor, ClassLoc); 11474 11475 // Introduce this destructor into its scope. 11476 if (S) 11477 PushOnScopeChains(Destructor, S, false); 11478 ClassDecl->addDecl(Destructor); 11479 11480 return Destructor; 11481 } 11482 11483 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11484 CXXDestructorDecl *Destructor) { 11485 assert((Destructor->isDefaulted() && 11486 !Destructor->doesThisDeclarationHaveABody() && 11487 !Destructor->isDeleted()) && 11488 "DefineImplicitDestructor - call it for implicit default dtor"); 11489 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11490 return; 11491 11492 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11493 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11494 11495 SynthesizedFunctionScope Scope(*this, Destructor); 11496 11497 // The exception specification is needed because we are defining the 11498 // function. 11499 ResolveExceptionSpec(CurrentLocation, 11500 Destructor->getType()->castAs<FunctionProtoType>()); 11501 MarkVTableUsed(CurrentLocation, ClassDecl); 11502 11503 // Add a context note for diagnostics produced after this point. 11504 Scope.addContextNote(CurrentLocation); 11505 11506 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11507 Destructor->getParent()); 11508 11509 if (CheckDestructor(Destructor)) { 11510 Destructor->setInvalidDecl(); 11511 return; 11512 } 11513 11514 SourceLocation Loc = Destructor->getEndLoc().isValid() 11515 ? Destructor->getEndLoc() 11516 : Destructor->getLocation(); 11517 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11518 Destructor->markUsed(Context); 11519 11520 if (ASTMutationListener *L = getASTMutationListener()) { 11521 L->CompletedImplicitDefinition(Destructor); 11522 } 11523 } 11524 11525 /// Perform any semantic analysis which needs to be delayed until all 11526 /// pending class member declarations have been parsed. 11527 void Sema::ActOnFinishCXXMemberDecls() { 11528 // If the context is an invalid C++ class, just suppress these checks. 11529 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11530 if (Record->isInvalidDecl()) { 11531 DelayedOverridingExceptionSpecChecks.clear(); 11532 DelayedEquivalentExceptionSpecChecks.clear(); 11533 return; 11534 } 11535 checkForMultipleExportedDefaultConstructors(*this, Record); 11536 } 11537 } 11538 11539 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11540 referenceDLLExportedClassMethods(); 11541 11542 if (!DelayedDllExportMemberFunctions.empty()) { 11543 SmallVector<CXXMethodDecl*, 4> WorkList; 11544 std::swap(DelayedDllExportMemberFunctions, WorkList); 11545 for (CXXMethodDecl *M : WorkList) { 11546 DefineImplicitSpecialMember(*this, M, M->getLocation()); 11547 11548 // Pass the method to the consumer to get emitted. This is not necessary 11549 // for explicit instantiation definitions, as they will get emitted 11550 // anyway. 11551 if (M->getParent()->getTemplateSpecializationKind() != 11552 TSK_ExplicitInstantiationDefinition) 11553 ActOnFinishInlineFunctionDef(M); 11554 } 11555 } 11556 } 11557 11558 void Sema::referenceDLLExportedClassMethods() { 11559 if (!DelayedDllExportClasses.empty()) { 11560 // Calling ReferenceDllExportedMembers might cause the current function to 11561 // be called again, so use a local copy of DelayedDllExportClasses. 11562 SmallVector<CXXRecordDecl *, 4> WorkList; 11563 std::swap(DelayedDllExportClasses, WorkList); 11564 for (CXXRecordDecl *Class : WorkList) 11565 ReferenceDllExportedMembers(*this, Class); 11566 } 11567 } 11568 11569 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 11570 assert(getLangOpts().CPlusPlus11 && 11571 "adjusting dtor exception specs was introduced in c++11"); 11572 11573 if (Destructor->isDependentContext()) 11574 return; 11575 11576 // C++11 [class.dtor]p3: 11577 // A declaration of a destructor that does not have an exception- 11578 // specification is implicitly considered to have the same exception- 11579 // specification as an implicit declaration. 11580 const FunctionProtoType *DtorType = Destructor->getType()-> 11581 getAs<FunctionProtoType>(); 11582 if (DtorType->hasExceptionSpec()) 11583 return; 11584 11585 // Replace the destructor's type, building off the existing one. Fortunately, 11586 // the only thing of interest in the destructor type is its extended info. 11587 // The return and arguments are fixed. 11588 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11589 EPI.ExceptionSpec.Type = EST_Unevaluated; 11590 EPI.ExceptionSpec.SourceDecl = Destructor; 11591 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11592 11593 // FIXME: If the destructor has a body that could throw, and the newly created 11594 // spec doesn't allow exceptions, we should emit a warning, because this 11595 // change in behavior can break conforming C++03 programs at runtime. 11596 // However, we don't have a body or an exception specification yet, so it 11597 // needs to be done somewhere else. 11598 } 11599 11600 namespace { 11601 /// An abstract base class for all helper classes used in building the 11602 // copy/move operators. These classes serve as factory functions and help us 11603 // avoid using the same Expr* in the AST twice. 11604 class ExprBuilder { 11605 ExprBuilder(const ExprBuilder&) = delete; 11606 ExprBuilder &operator=(const ExprBuilder&) = delete; 11607 11608 protected: 11609 static Expr *assertNotNull(Expr *E) { 11610 assert(E && "Expression construction must not fail."); 11611 return E; 11612 } 11613 11614 public: 11615 ExprBuilder() {} 11616 virtual ~ExprBuilder() {} 11617 11618 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11619 }; 11620 11621 class RefBuilder: public ExprBuilder { 11622 VarDecl *Var; 11623 QualType VarType; 11624 11625 public: 11626 Expr *build(Sema &S, SourceLocation Loc) const override { 11627 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 11628 } 11629 11630 RefBuilder(VarDecl *Var, QualType VarType) 11631 : Var(Var), VarType(VarType) {} 11632 }; 11633 11634 class ThisBuilder: public ExprBuilder { 11635 public: 11636 Expr *build(Sema &S, SourceLocation Loc) const override { 11637 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11638 } 11639 }; 11640 11641 class CastBuilder: public ExprBuilder { 11642 const ExprBuilder &Builder; 11643 QualType Type; 11644 ExprValueKind Kind; 11645 const CXXCastPath &Path; 11646 11647 public: 11648 Expr *build(Sema &S, SourceLocation Loc) const override { 11649 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11650 CK_UncheckedDerivedToBase, Kind, 11651 &Path).get()); 11652 } 11653 11654 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11655 const CXXCastPath &Path) 11656 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11657 }; 11658 11659 class DerefBuilder: public ExprBuilder { 11660 const ExprBuilder &Builder; 11661 11662 public: 11663 Expr *build(Sema &S, SourceLocation Loc) const override { 11664 return assertNotNull( 11665 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11666 } 11667 11668 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11669 }; 11670 11671 class MemberBuilder: public ExprBuilder { 11672 const ExprBuilder &Builder; 11673 QualType Type; 11674 CXXScopeSpec SS; 11675 bool IsArrow; 11676 LookupResult &MemberLookup; 11677 11678 public: 11679 Expr *build(Sema &S, SourceLocation Loc) const override { 11680 return assertNotNull(S.BuildMemberReferenceExpr( 11681 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11682 nullptr, MemberLookup, nullptr, nullptr).get()); 11683 } 11684 11685 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11686 LookupResult &MemberLookup) 11687 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11688 MemberLookup(MemberLookup) {} 11689 }; 11690 11691 class MoveCastBuilder: public ExprBuilder { 11692 const ExprBuilder &Builder; 11693 11694 public: 11695 Expr *build(Sema &S, SourceLocation Loc) const override { 11696 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11697 } 11698 11699 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11700 }; 11701 11702 class LvalueConvBuilder: public ExprBuilder { 11703 const ExprBuilder &Builder; 11704 11705 public: 11706 Expr *build(Sema &S, SourceLocation Loc) const override { 11707 return assertNotNull( 11708 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11709 } 11710 11711 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11712 }; 11713 11714 class SubscriptBuilder: public ExprBuilder { 11715 const ExprBuilder &Base; 11716 const ExprBuilder &Index; 11717 11718 public: 11719 Expr *build(Sema &S, SourceLocation Loc) const override { 11720 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11721 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11722 } 11723 11724 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11725 : Base(Base), Index(Index) {} 11726 }; 11727 11728 } // end anonymous namespace 11729 11730 /// When generating a defaulted copy or move assignment operator, if a field 11731 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11732 /// do so. This optimization only applies for arrays of scalars, and for arrays 11733 /// of class type where the selected copy/move-assignment operator is trivial. 11734 static StmtResult 11735 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11736 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11737 // Compute the size of the memory buffer to be copied. 11738 QualType SizeType = S.Context.getSizeType(); 11739 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11740 S.Context.getTypeSizeInChars(T).getQuantity()); 11741 11742 // Take the address of the field references for "from" and "to". We 11743 // directly construct UnaryOperators here because semantic analysis 11744 // does not permit us to take the address of an xvalue. 11745 Expr *From = FromB.build(S, Loc); 11746 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11747 S.Context.getPointerType(From->getType()), 11748 VK_RValue, OK_Ordinary, Loc, false); 11749 Expr *To = ToB.build(S, Loc); 11750 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11751 S.Context.getPointerType(To->getType()), 11752 VK_RValue, OK_Ordinary, Loc, false); 11753 11754 const Type *E = T->getBaseElementTypeUnsafe(); 11755 bool NeedsCollectableMemCpy = 11756 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11757 11758 // Create a reference to the __builtin_objc_memmove_collectable function 11759 StringRef MemCpyName = NeedsCollectableMemCpy ? 11760 "__builtin_objc_memmove_collectable" : 11761 "__builtin_memcpy"; 11762 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11763 Sema::LookupOrdinaryName); 11764 S.LookupName(R, S.TUScope, true); 11765 11766 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11767 if (!MemCpy) 11768 // Something went horribly wrong earlier, and we will have complained 11769 // about it. 11770 return StmtError(); 11771 11772 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11773 VK_RValue, Loc, nullptr); 11774 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11775 11776 Expr *CallArgs[] = { 11777 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11778 }; 11779 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11780 Loc, CallArgs, Loc); 11781 11782 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11783 return Call.getAs<Stmt>(); 11784 } 11785 11786 /// Builds a statement that copies/moves the given entity from \p From to 11787 /// \c To. 11788 /// 11789 /// This routine is used to copy/move the members of a class with an 11790 /// implicitly-declared copy/move assignment operator. When the entities being 11791 /// copied are arrays, this routine builds for loops to copy them. 11792 /// 11793 /// \param S The Sema object used for type-checking. 11794 /// 11795 /// \param Loc The location where the implicit copy/move is being generated. 11796 /// 11797 /// \param T The type of the expressions being copied/moved. Both expressions 11798 /// must have this type. 11799 /// 11800 /// \param To The expression we are copying/moving to. 11801 /// 11802 /// \param From The expression we are copying/moving from. 11803 /// 11804 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11805 /// Otherwise, it's a non-static member subobject. 11806 /// 11807 /// \param Copying Whether we're copying or moving. 11808 /// 11809 /// \param Depth Internal parameter recording the depth of the recursion. 11810 /// 11811 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11812 /// if a memcpy should be used instead. 11813 static StmtResult 11814 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11815 const ExprBuilder &To, const ExprBuilder &From, 11816 bool CopyingBaseSubobject, bool Copying, 11817 unsigned Depth = 0) { 11818 // C++11 [class.copy]p28: 11819 // Each subobject is assigned in the manner appropriate to its type: 11820 // 11821 // - if the subobject is of class type, as if by a call to operator= with 11822 // the subobject as the object expression and the corresponding 11823 // subobject of x as a single function argument (as if by explicit 11824 // qualification; that is, ignoring any possible virtual overriding 11825 // functions in more derived classes); 11826 // 11827 // C++03 [class.copy]p13: 11828 // - if the subobject is of class type, the copy assignment operator for 11829 // the class is used (as if by explicit qualification; that is, 11830 // ignoring any possible virtual overriding functions in more derived 11831 // classes); 11832 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11833 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11834 11835 // Look for operator=. 11836 DeclarationName Name 11837 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11838 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11839 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11840 11841 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11842 // operator. 11843 if (!S.getLangOpts().CPlusPlus11) { 11844 LookupResult::Filter F = OpLookup.makeFilter(); 11845 while (F.hasNext()) { 11846 NamedDecl *D = F.next(); 11847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11848 if (Method->isCopyAssignmentOperator() || 11849 (!Copying && Method->isMoveAssignmentOperator())) 11850 continue; 11851 11852 F.erase(); 11853 } 11854 F.done(); 11855 } 11856 11857 // Suppress the protected check (C++ [class.protected]) for each of the 11858 // assignment operators we found. This strange dance is required when 11859 // we're assigning via a base classes's copy-assignment operator. To 11860 // ensure that we're getting the right base class subobject (without 11861 // ambiguities), we need to cast "this" to that subobject type; to 11862 // ensure that we don't go through the virtual call mechanism, we need 11863 // to qualify the operator= name with the base class (see below). However, 11864 // this means that if the base class has a protected copy assignment 11865 // operator, the protected member access check will fail. So, we 11866 // rewrite "protected" access to "public" access in this case, since we 11867 // know by construction that we're calling from a derived class. 11868 if (CopyingBaseSubobject) { 11869 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11870 L != LEnd; ++L) { 11871 if (L.getAccess() == AS_protected) 11872 L.setAccess(AS_public); 11873 } 11874 } 11875 11876 // Create the nested-name-specifier that will be used to qualify the 11877 // reference to operator=; this is required to suppress the virtual 11878 // call mechanism. 11879 CXXScopeSpec SS; 11880 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11881 SS.MakeTrivial(S.Context, 11882 NestedNameSpecifier::Create(S.Context, nullptr, false, 11883 CanonicalT), 11884 Loc); 11885 11886 // Create the reference to operator=. 11887 ExprResult OpEqualRef 11888 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 11889 SS, /*TemplateKWLoc=*/SourceLocation(), 11890 /*FirstQualifierInScope=*/nullptr, 11891 OpLookup, 11892 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11893 /*SuppressQualifierCheck=*/true); 11894 if (OpEqualRef.isInvalid()) 11895 return StmtError(); 11896 11897 // Build the call to the assignment operator. 11898 11899 Expr *FromInst = From.build(S, Loc); 11900 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11901 OpEqualRef.getAs<Expr>(), 11902 Loc, FromInst, Loc); 11903 if (Call.isInvalid()) 11904 return StmtError(); 11905 11906 // If we built a call to a trivial 'operator=' while copying an array, 11907 // bail out. We'll replace the whole shebang with a memcpy. 11908 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11909 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11910 return StmtResult((Stmt*)nullptr); 11911 11912 // Convert to an expression-statement, and clean up any produced 11913 // temporaries. 11914 return S.ActOnExprStmt(Call); 11915 } 11916 11917 // - if the subobject is of scalar type, the built-in assignment 11918 // operator is used. 11919 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11920 if (!ArrayTy) { 11921 ExprResult Assignment = S.CreateBuiltinBinOp( 11922 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11923 if (Assignment.isInvalid()) 11924 return StmtError(); 11925 return S.ActOnExprStmt(Assignment); 11926 } 11927 11928 // - if the subobject is an array, each element is assigned, in the 11929 // manner appropriate to the element type; 11930 11931 // Construct a loop over the array bounds, e.g., 11932 // 11933 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11934 // 11935 // that will copy each of the array elements. 11936 QualType SizeType = S.Context.getSizeType(); 11937 11938 // Create the iteration variable. 11939 IdentifierInfo *IterationVarName = nullptr; 11940 { 11941 SmallString<8> Str; 11942 llvm::raw_svector_ostream OS(Str); 11943 OS << "__i" << Depth; 11944 IterationVarName = &S.Context.Idents.get(OS.str()); 11945 } 11946 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11947 IterationVarName, SizeType, 11948 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11949 SC_None); 11950 11951 // Initialize the iteration variable to zero. 11952 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11953 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11954 11955 // Creates a reference to the iteration variable. 11956 RefBuilder IterationVarRef(IterationVar, SizeType); 11957 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11958 11959 // Create the DeclStmt that holds the iteration variable. 11960 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11961 11962 // Subscript the "from" and "to" expressions with the iteration variable. 11963 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11964 MoveCastBuilder FromIndexMove(FromIndexCopy); 11965 const ExprBuilder *FromIndex; 11966 if (Copying) 11967 FromIndex = &FromIndexCopy; 11968 else 11969 FromIndex = &FromIndexMove; 11970 11971 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11972 11973 // Build the copy/move for an individual element of the array. 11974 StmtResult Copy = 11975 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11976 ToIndex, *FromIndex, CopyingBaseSubobject, 11977 Copying, Depth + 1); 11978 // Bail out if copying fails or if we determined that we should use memcpy. 11979 if (Copy.isInvalid() || !Copy.get()) 11980 return Copy; 11981 11982 // Create the comparison against the array bound. 11983 llvm::APInt Upper 11984 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11985 Expr *Comparison 11986 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11987 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11988 BO_NE, S.Context.BoolTy, 11989 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11990 11991 // Create the pre-increment of the iteration variable. We can determine 11992 // whether the increment will overflow based on the value of the array 11993 // bound. 11994 Expr *Increment = new (S.Context) 11995 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11996 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11997 11998 // Construct the loop that copies all elements of this array. 11999 return S.ActOnForStmt( 12000 Loc, Loc, InitStmt, 12001 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 12002 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 12003 } 12004 12005 static StmtResult 12006 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 12007 const ExprBuilder &To, const ExprBuilder &From, 12008 bool CopyingBaseSubobject, bool Copying) { 12009 // Maybe we should use a memcpy? 12010 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 12011 T.isTriviallyCopyableType(S.Context)) 12012 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 12013 12014 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 12015 CopyingBaseSubobject, 12016 Copying, 0)); 12017 12018 // If we ended up picking a trivial assignment operator for an array of a 12019 // non-trivially-copyable class type, just emit a memcpy. 12020 if (!Result.isInvalid() && !Result.get()) 12021 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 12022 12023 return Result; 12024 } 12025 12026 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 12027 // Note: The following rules are largely analoguous to the copy 12028 // constructor rules. Note that virtual bases are not taken into account 12029 // for determining the argument type of the operator. Note also that 12030 // operators taking an object instead of a reference are allowed. 12031 assert(ClassDecl->needsImplicitCopyAssignment()); 12032 12033 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 12034 if (DSM.isAlreadyBeingDeclared()) 12035 return nullptr; 12036 12037 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12038 if (Context.getLangOpts().OpenCLCPlusPlus) 12039 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12040 QualType RetType = Context.getLValueReferenceType(ArgType); 12041 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 12042 if (Const) 12043 ArgType = ArgType.withConst(); 12044 12045 ArgType = Context.getLValueReferenceType(ArgType); 12046 12047 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12048 CXXCopyAssignment, 12049 Const); 12050 12051 // An implicitly-declared copy assignment operator is an inline public 12052 // member of its class. 12053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12054 SourceLocation ClassLoc = ClassDecl->getLocation(); 12055 DeclarationNameInfo NameInfo(Name, ClassLoc); 12056 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 12057 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12058 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12059 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 12060 SourceLocation()); 12061 CopyAssignment->setAccess(AS_public); 12062 CopyAssignment->setDefaulted(); 12063 CopyAssignment->setImplicit(); 12064 12065 if (getLangOpts().CUDA) { 12066 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 12067 CopyAssignment, 12068 /* ConstRHS */ Const, 12069 /* Diagnose */ false); 12070 } 12071 12072 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 12073 12074 // Add the parameter to the operator. 12075 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 12076 ClassLoc, ClassLoc, 12077 /*Id=*/nullptr, ArgType, 12078 /*TInfo=*/nullptr, SC_None, 12079 nullptr); 12080 CopyAssignment->setParams(FromParam); 12081 12082 CopyAssignment->setTrivial( 12083 ClassDecl->needsOverloadResolutionForCopyAssignment() 12084 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 12085 : ClassDecl->hasTrivialCopyAssignment()); 12086 12087 // Note that we have added this copy-assignment operator. 12088 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 12089 12090 Scope *S = getScopeForContext(ClassDecl); 12091 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 12092 12093 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 12094 SetDeclDeleted(CopyAssignment, ClassLoc); 12095 12096 if (S) 12097 PushOnScopeChains(CopyAssignment, S, false); 12098 ClassDecl->addDecl(CopyAssignment); 12099 12100 return CopyAssignment; 12101 } 12102 12103 /// Diagnose an implicit copy operation for a class which is odr-used, but 12104 /// which is deprecated because the class has a user-declared copy constructor, 12105 /// copy assignment operator, or destructor. 12106 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 12107 assert(CopyOp->isImplicit()); 12108 12109 CXXRecordDecl *RD = CopyOp->getParent(); 12110 CXXMethodDecl *UserDeclaredOperation = nullptr; 12111 12112 // In Microsoft mode, assignment operations don't affect constructors and 12113 // vice versa. 12114 if (RD->hasUserDeclaredDestructor()) { 12115 UserDeclaredOperation = RD->getDestructor(); 12116 } else if (!isa<CXXConstructorDecl>(CopyOp) && 12117 RD->hasUserDeclaredCopyConstructor() && 12118 !S.getLangOpts().MSVCCompat) { 12119 // Find any user-declared copy constructor. 12120 for (auto *I : RD->ctors()) { 12121 if (I->isCopyConstructor()) { 12122 UserDeclaredOperation = I; 12123 break; 12124 } 12125 } 12126 assert(UserDeclaredOperation); 12127 } else if (isa<CXXConstructorDecl>(CopyOp) && 12128 RD->hasUserDeclaredCopyAssignment() && 12129 !S.getLangOpts().MSVCCompat) { 12130 // Find any user-declared move assignment operator. 12131 for (auto *I : RD->methods()) { 12132 if (I->isCopyAssignmentOperator()) { 12133 UserDeclaredOperation = I; 12134 break; 12135 } 12136 } 12137 assert(UserDeclaredOperation); 12138 } 12139 12140 if (UserDeclaredOperation) { 12141 S.Diag(UserDeclaredOperation->getLocation(), 12142 diag::warn_deprecated_copy_operation) 12143 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 12144 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 12145 } 12146 } 12147 12148 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 12149 CXXMethodDecl *CopyAssignOperator) { 12150 assert((CopyAssignOperator->isDefaulted() && 12151 CopyAssignOperator->isOverloadedOperator() && 12152 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 12153 !CopyAssignOperator->doesThisDeclarationHaveABody() && 12154 !CopyAssignOperator->isDeleted()) && 12155 "DefineImplicitCopyAssignment called for wrong function"); 12156 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 12157 return; 12158 12159 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 12160 if (ClassDecl->isInvalidDecl()) { 12161 CopyAssignOperator->setInvalidDecl(); 12162 return; 12163 } 12164 12165 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 12166 12167 // The exception specification is needed because we are defining the 12168 // function. 12169 ResolveExceptionSpec(CurrentLocation, 12170 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 12171 12172 // Add a context note for diagnostics produced after this point. 12173 Scope.addContextNote(CurrentLocation); 12174 12175 // C++11 [class.copy]p18: 12176 // The [definition of an implicitly declared copy assignment operator] is 12177 // deprecated if the class has a user-declared copy constructor or a 12178 // user-declared destructor. 12179 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 12180 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 12181 12182 // C++0x [class.copy]p30: 12183 // The implicitly-defined or explicitly-defaulted copy assignment operator 12184 // for a non-union class X performs memberwise copy assignment of its 12185 // subobjects. The direct base classes of X are assigned first, in the 12186 // order of their declaration in the base-specifier-list, and then the 12187 // immediate non-static data members of X are assigned, in the order in 12188 // which they were declared in the class definition. 12189 12190 // The statements that form the synthesized function body. 12191 SmallVector<Stmt*, 8> Statements; 12192 12193 // The parameter for the "other" object, which we are copying from. 12194 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 12195 Qualifiers OtherQuals = Other->getType().getQualifiers(); 12196 QualType OtherRefType = Other->getType(); 12197 if (const LValueReferenceType *OtherRef 12198 = OtherRefType->getAs<LValueReferenceType>()) { 12199 OtherRefType = OtherRef->getPointeeType(); 12200 OtherQuals = OtherRefType.getQualifiers(); 12201 } 12202 12203 // Our location for everything implicitly-generated. 12204 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 12205 ? CopyAssignOperator->getEndLoc() 12206 : CopyAssignOperator->getLocation(); 12207 12208 // Builds a DeclRefExpr for the "other" object. 12209 RefBuilder OtherRef(Other, OtherRefType); 12210 12211 // Builds the "this" pointer. 12212 ThisBuilder This; 12213 12214 // Assign base classes. 12215 bool Invalid = false; 12216 for (auto &Base : ClassDecl->bases()) { 12217 // Form the assignment: 12218 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 12219 QualType BaseType = Base.getType().getUnqualifiedType(); 12220 if (!BaseType->isRecordType()) { 12221 Invalid = true; 12222 continue; 12223 } 12224 12225 CXXCastPath BasePath; 12226 BasePath.push_back(&Base); 12227 12228 // Construct the "from" expression, which is an implicit cast to the 12229 // appropriately-qualified base type. 12230 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 12231 VK_LValue, BasePath); 12232 12233 // Dereference "this". 12234 DerefBuilder DerefThis(This); 12235 CastBuilder To(DerefThis, 12236 Context.getQualifiedType( 12237 BaseType, CopyAssignOperator->getMethodQualifiers()), 12238 VK_LValue, BasePath); 12239 12240 // Build the copy. 12241 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 12242 To, From, 12243 /*CopyingBaseSubobject=*/true, 12244 /*Copying=*/true); 12245 if (Copy.isInvalid()) { 12246 CopyAssignOperator->setInvalidDecl(); 12247 return; 12248 } 12249 12250 // Success! Record the copy. 12251 Statements.push_back(Copy.getAs<Expr>()); 12252 } 12253 12254 // Assign non-static members. 12255 for (auto *Field : ClassDecl->fields()) { 12256 // FIXME: We should form some kind of AST representation for the implied 12257 // memcpy in a union copy operation. 12258 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12259 continue; 12260 12261 if (Field->isInvalidDecl()) { 12262 Invalid = true; 12263 continue; 12264 } 12265 12266 // Check for members of reference type; we can't copy those. 12267 if (Field->getType()->isReferenceType()) { 12268 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12269 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12270 Diag(Field->getLocation(), diag::note_declared_at); 12271 Invalid = true; 12272 continue; 12273 } 12274 12275 // Check for members of const-qualified, non-class type. 12276 QualType BaseType = Context.getBaseElementType(Field->getType()); 12277 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12278 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12279 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12280 Diag(Field->getLocation(), diag::note_declared_at); 12281 Invalid = true; 12282 continue; 12283 } 12284 12285 // Suppress assigning zero-width bitfields. 12286 if (Field->isZeroLengthBitField(Context)) 12287 continue; 12288 12289 QualType FieldType = Field->getType().getNonReferenceType(); 12290 if (FieldType->isIncompleteArrayType()) { 12291 assert(ClassDecl->hasFlexibleArrayMember() && 12292 "Incomplete array type is not valid"); 12293 continue; 12294 } 12295 12296 // Build references to the field in the object we're copying from and to. 12297 CXXScopeSpec SS; // Intentionally empty 12298 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12299 LookupMemberName); 12300 MemberLookup.addDecl(Field); 12301 MemberLookup.resolveKind(); 12302 12303 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 12304 12305 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 12306 12307 // Build the copy of this field. 12308 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 12309 To, From, 12310 /*CopyingBaseSubobject=*/false, 12311 /*Copying=*/true); 12312 if (Copy.isInvalid()) { 12313 CopyAssignOperator->setInvalidDecl(); 12314 return; 12315 } 12316 12317 // Success! Record the copy. 12318 Statements.push_back(Copy.getAs<Stmt>()); 12319 } 12320 12321 if (!Invalid) { 12322 // Add a "return *this;" 12323 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12324 12325 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12326 if (Return.isInvalid()) 12327 Invalid = true; 12328 else 12329 Statements.push_back(Return.getAs<Stmt>()); 12330 } 12331 12332 if (Invalid) { 12333 CopyAssignOperator->setInvalidDecl(); 12334 return; 12335 } 12336 12337 StmtResult Body; 12338 { 12339 CompoundScopeRAII CompoundScope(*this); 12340 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12341 /*isStmtExpr=*/false); 12342 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12343 } 12344 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 12345 CopyAssignOperator->markUsed(Context); 12346 12347 if (ASTMutationListener *L = getASTMutationListener()) { 12348 L->CompletedImplicitDefinition(CopyAssignOperator); 12349 } 12350 } 12351 12352 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 12353 assert(ClassDecl->needsImplicitMoveAssignment()); 12354 12355 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 12356 if (DSM.isAlreadyBeingDeclared()) 12357 return nullptr; 12358 12359 // Note: The following rules are largely analoguous to the move 12360 // constructor rules. 12361 12362 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12363 if (Context.getLangOpts().OpenCLCPlusPlus) 12364 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12365 QualType RetType = Context.getLValueReferenceType(ArgType); 12366 ArgType = Context.getRValueReferenceType(ArgType); 12367 12368 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12369 CXXMoveAssignment, 12370 false); 12371 12372 // An implicitly-declared move assignment operator is an inline public 12373 // member of its class. 12374 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12375 SourceLocation ClassLoc = ClassDecl->getLocation(); 12376 DeclarationNameInfo NameInfo(Name, ClassLoc); 12377 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 12378 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12379 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12380 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 12381 SourceLocation()); 12382 MoveAssignment->setAccess(AS_public); 12383 MoveAssignment->setDefaulted(); 12384 MoveAssignment->setImplicit(); 12385 12386 if (getLangOpts().CUDA) { 12387 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12388 MoveAssignment, 12389 /* ConstRHS */ false, 12390 /* Diagnose */ false); 12391 } 12392 12393 // Build an exception specification pointing back at this member. 12394 FunctionProtoType::ExtProtoInfo EPI = 12395 getImplicitMethodEPI(*this, MoveAssignment); 12396 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12397 12398 // Add the parameter to the operator. 12399 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12400 ClassLoc, ClassLoc, 12401 /*Id=*/nullptr, ArgType, 12402 /*TInfo=*/nullptr, SC_None, 12403 nullptr); 12404 MoveAssignment->setParams(FromParam); 12405 12406 MoveAssignment->setTrivial( 12407 ClassDecl->needsOverloadResolutionForMoveAssignment() 12408 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12409 : ClassDecl->hasTrivialMoveAssignment()); 12410 12411 // Note that we have added this copy-assignment operator. 12412 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 12413 12414 Scope *S = getScopeForContext(ClassDecl); 12415 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12416 12417 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12418 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12419 SetDeclDeleted(MoveAssignment, ClassLoc); 12420 } 12421 12422 if (S) 12423 PushOnScopeChains(MoveAssignment, S, false); 12424 ClassDecl->addDecl(MoveAssignment); 12425 12426 return MoveAssignment; 12427 } 12428 12429 /// Check if we're implicitly defining a move assignment operator for a class 12430 /// with virtual bases. Such a move assignment might move-assign the virtual 12431 /// base multiple times. 12432 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12433 SourceLocation CurrentLocation) { 12434 assert(!Class->isDependentContext() && "should not define dependent move"); 12435 12436 // Only a virtual base could get implicitly move-assigned multiple times. 12437 // Only a non-trivial move assignment can observe this. We only want to 12438 // diagnose if we implicitly define an assignment operator that assigns 12439 // two base classes, both of which move-assign the same virtual base. 12440 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12441 Class->getNumBases() < 2) 12442 return; 12443 12444 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12445 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12446 VBaseMap VBases; 12447 12448 for (auto &BI : Class->bases()) { 12449 Worklist.push_back(&BI); 12450 while (!Worklist.empty()) { 12451 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12452 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12453 12454 // If the base has no non-trivial move assignment operators, 12455 // we don't care about moves from it. 12456 if (!Base->hasNonTrivialMoveAssignment()) 12457 continue; 12458 12459 // If there's nothing virtual here, skip it. 12460 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12461 continue; 12462 12463 // If we're not actually going to call a move assignment for this base, 12464 // or the selected move assignment is trivial, skip it. 12465 Sema::SpecialMemberOverloadResult SMOR = 12466 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12467 /*ConstArg*/false, /*VolatileArg*/false, 12468 /*RValueThis*/true, /*ConstThis*/false, 12469 /*VolatileThis*/false); 12470 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12471 !SMOR.getMethod()->isMoveAssignmentOperator()) 12472 continue; 12473 12474 if (BaseSpec->isVirtual()) { 12475 // We're going to move-assign this virtual base, and its move 12476 // assignment operator is not trivial. If this can happen for 12477 // multiple distinct direct bases of Class, diagnose it. (If it 12478 // only happens in one base, we'll diagnose it when synthesizing 12479 // that base class's move assignment operator.) 12480 CXXBaseSpecifier *&Existing = 12481 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12482 .first->second; 12483 if (Existing && Existing != &BI) { 12484 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12485 << Class << Base; 12486 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 12487 << (Base->getCanonicalDecl() == 12488 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12489 << Base << Existing->getType() << Existing->getSourceRange(); 12490 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 12491 << (Base->getCanonicalDecl() == 12492 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12493 << Base << BI.getType() << BaseSpec->getSourceRange(); 12494 12495 // Only diagnose each vbase once. 12496 Existing = nullptr; 12497 } 12498 } else { 12499 // Only walk over bases that have defaulted move assignment operators. 12500 // We assume that any user-provided move assignment operator handles 12501 // the multiple-moves-of-vbase case itself somehow. 12502 if (!SMOR.getMethod()->isDefaulted()) 12503 continue; 12504 12505 // We're going to move the base classes of Base. Add them to the list. 12506 for (auto &BI : Base->bases()) 12507 Worklist.push_back(&BI); 12508 } 12509 } 12510 } 12511 } 12512 12513 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12514 CXXMethodDecl *MoveAssignOperator) { 12515 assert((MoveAssignOperator->isDefaulted() && 12516 MoveAssignOperator->isOverloadedOperator() && 12517 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12518 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12519 !MoveAssignOperator->isDeleted()) && 12520 "DefineImplicitMoveAssignment called for wrong function"); 12521 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12522 return; 12523 12524 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12525 if (ClassDecl->isInvalidDecl()) { 12526 MoveAssignOperator->setInvalidDecl(); 12527 return; 12528 } 12529 12530 // C++0x [class.copy]p28: 12531 // The implicitly-defined or move assignment operator for a non-union class 12532 // X performs memberwise move assignment of its subobjects. The direct base 12533 // classes of X are assigned first, in the order of their declaration in the 12534 // base-specifier-list, and then the immediate non-static data members of X 12535 // are assigned, in the order in which they were declared in the class 12536 // definition. 12537 12538 // Issue a warning if our implicit move assignment operator will move 12539 // from a virtual base more than once. 12540 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12541 12542 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12543 12544 // The exception specification is needed because we are defining the 12545 // function. 12546 ResolveExceptionSpec(CurrentLocation, 12547 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12548 12549 // Add a context note for diagnostics produced after this point. 12550 Scope.addContextNote(CurrentLocation); 12551 12552 // The statements that form the synthesized function body. 12553 SmallVector<Stmt*, 8> Statements; 12554 12555 // The parameter for the "other" object, which we are move from. 12556 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12557 QualType OtherRefType = Other->getType()-> 12558 getAs<RValueReferenceType>()->getPointeeType(); 12559 12560 // Our location for everything implicitly-generated. 12561 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 12562 ? MoveAssignOperator->getEndLoc() 12563 : MoveAssignOperator->getLocation(); 12564 12565 // Builds a reference to the "other" object. 12566 RefBuilder OtherRef(Other, OtherRefType); 12567 // Cast to rvalue. 12568 MoveCastBuilder MoveOther(OtherRef); 12569 12570 // Builds the "this" pointer. 12571 ThisBuilder This; 12572 12573 // Assign base classes. 12574 bool Invalid = false; 12575 for (auto &Base : ClassDecl->bases()) { 12576 // C++11 [class.copy]p28: 12577 // It is unspecified whether subobjects representing virtual base classes 12578 // are assigned more than once by the implicitly-defined copy assignment 12579 // operator. 12580 // FIXME: Do not assign to a vbase that will be assigned by some other base 12581 // class. For a move-assignment, this can result in the vbase being moved 12582 // multiple times. 12583 12584 // Form the assignment: 12585 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12586 QualType BaseType = Base.getType().getUnqualifiedType(); 12587 if (!BaseType->isRecordType()) { 12588 Invalid = true; 12589 continue; 12590 } 12591 12592 CXXCastPath BasePath; 12593 BasePath.push_back(&Base); 12594 12595 // Construct the "from" expression, which is an implicit cast to the 12596 // appropriately-qualified base type. 12597 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12598 12599 // Dereference "this". 12600 DerefBuilder DerefThis(This); 12601 12602 // Implicitly cast "this" to the appropriately-qualified base type. 12603 CastBuilder To(DerefThis, 12604 Context.getQualifiedType( 12605 BaseType, MoveAssignOperator->getMethodQualifiers()), 12606 VK_LValue, BasePath); 12607 12608 // Build the move. 12609 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12610 To, From, 12611 /*CopyingBaseSubobject=*/true, 12612 /*Copying=*/false); 12613 if (Move.isInvalid()) { 12614 MoveAssignOperator->setInvalidDecl(); 12615 return; 12616 } 12617 12618 // Success! Record the move. 12619 Statements.push_back(Move.getAs<Expr>()); 12620 } 12621 12622 // Assign non-static members. 12623 for (auto *Field : ClassDecl->fields()) { 12624 // FIXME: We should form some kind of AST representation for the implied 12625 // memcpy in a union copy operation. 12626 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12627 continue; 12628 12629 if (Field->isInvalidDecl()) { 12630 Invalid = true; 12631 continue; 12632 } 12633 12634 // Check for members of reference type; we can't move those. 12635 if (Field->getType()->isReferenceType()) { 12636 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12637 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12638 Diag(Field->getLocation(), diag::note_declared_at); 12639 Invalid = true; 12640 continue; 12641 } 12642 12643 // Check for members of const-qualified, non-class type. 12644 QualType BaseType = Context.getBaseElementType(Field->getType()); 12645 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12646 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12647 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12648 Diag(Field->getLocation(), diag::note_declared_at); 12649 Invalid = true; 12650 continue; 12651 } 12652 12653 // Suppress assigning zero-width bitfields. 12654 if (Field->isZeroLengthBitField(Context)) 12655 continue; 12656 12657 QualType FieldType = Field->getType().getNonReferenceType(); 12658 if (FieldType->isIncompleteArrayType()) { 12659 assert(ClassDecl->hasFlexibleArrayMember() && 12660 "Incomplete array type is not valid"); 12661 continue; 12662 } 12663 12664 // Build references to the field in the object we're copying from and to. 12665 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12666 LookupMemberName); 12667 MemberLookup.addDecl(Field); 12668 MemberLookup.resolveKind(); 12669 MemberBuilder From(MoveOther, OtherRefType, 12670 /*IsArrow=*/false, MemberLookup); 12671 MemberBuilder To(This, getCurrentThisType(), 12672 /*IsArrow=*/true, MemberLookup); 12673 12674 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12675 "Member reference with rvalue base must be rvalue except for reference " 12676 "members, which aren't allowed for move assignment."); 12677 12678 // Build the move of this field. 12679 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12680 To, From, 12681 /*CopyingBaseSubobject=*/false, 12682 /*Copying=*/false); 12683 if (Move.isInvalid()) { 12684 MoveAssignOperator->setInvalidDecl(); 12685 return; 12686 } 12687 12688 // Success! Record the copy. 12689 Statements.push_back(Move.getAs<Stmt>()); 12690 } 12691 12692 if (!Invalid) { 12693 // Add a "return *this;" 12694 ExprResult ThisObj = 12695 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12696 12697 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12698 if (Return.isInvalid()) 12699 Invalid = true; 12700 else 12701 Statements.push_back(Return.getAs<Stmt>()); 12702 } 12703 12704 if (Invalid) { 12705 MoveAssignOperator->setInvalidDecl(); 12706 return; 12707 } 12708 12709 StmtResult Body; 12710 { 12711 CompoundScopeRAII CompoundScope(*this); 12712 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12713 /*isStmtExpr=*/false); 12714 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12715 } 12716 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12717 MoveAssignOperator->markUsed(Context); 12718 12719 if (ASTMutationListener *L = getASTMutationListener()) { 12720 L->CompletedImplicitDefinition(MoveAssignOperator); 12721 } 12722 } 12723 12724 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12725 CXXRecordDecl *ClassDecl) { 12726 // C++ [class.copy]p4: 12727 // If the class definition does not explicitly declare a copy 12728 // constructor, one is declared implicitly. 12729 assert(ClassDecl->needsImplicitCopyConstructor()); 12730 12731 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12732 if (DSM.isAlreadyBeingDeclared()) 12733 return nullptr; 12734 12735 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12736 QualType ArgType = ClassType; 12737 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12738 if (Const) 12739 ArgType = ArgType.withConst(); 12740 12741 if (Context.getLangOpts().OpenCLCPlusPlus) 12742 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12743 12744 ArgType = Context.getLValueReferenceType(ArgType); 12745 12746 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12747 CXXCopyConstructor, 12748 Const); 12749 12750 DeclarationName Name 12751 = Context.DeclarationNames.getCXXConstructorName( 12752 Context.getCanonicalType(ClassType)); 12753 SourceLocation ClassLoc = ClassDecl->getLocation(); 12754 DeclarationNameInfo NameInfo(Name, ClassLoc); 12755 12756 // An implicitly-declared copy constructor is an inline public 12757 // member of its class. 12758 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12759 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12760 ExplicitSpecifier(), 12761 /*isInline=*/true, 12762 /*isImplicitlyDeclared=*/true, 12763 Constexpr ? CSK_constexpr : CSK_unspecified); 12764 CopyConstructor->setAccess(AS_public); 12765 CopyConstructor->setDefaulted(); 12766 12767 if (getLangOpts().CUDA) { 12768 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12769 CopyConstructor, 12770 /* ConstRHS */ Const, 12771 /* Diagnose */ false); 12772 } 12773 12774 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 12775 12776 // Add the parameter to the constructor. 12777 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12778 ClassLoc, ClassLoc, 12779 /*IdentifierInfo=*/nullptr, 12780 ArgType, /*TInfo=*/nullptr, 12781 SC_None, nullptr); 12782 CopyConstructor->setParams(FromParam); 12783 12784 CopyConstructor->setTrivial( 12785 ClassDecl->needsOverloadResolutionForCopyConstructor() 12786 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12787 : ClassDecl->hasTrivialCopyConstructor()); 12788 12789 CopyConstructor->setTrivialForCall( 12790 ClassDecl->hasAttr<TrivialABIAttr>() || 12791 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12792 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12793 TAH_ConsiderTrivialABI) 12794 : ClassDecl->hasTrivialCopyConstructorForCall())); 12795 12796 // Note that we have declared this constructor. 12797 ++getASTContext().NumImplicitCopyConstructorsDeclared; 12798 12799 Scope *S = getScopeForContext(ClassDecl); 12800 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12801 12802 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12803 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12804 SetDeclDeleted(CopyConstructor, ClassLoc); 12805 } 12806 12807 if (S) 12808 PushOnScopeChains(CopyConstructor, S, false); 12809 ClassDecl->addDecl(CopyConstructor); 12810 12811 return CopyConstructor; 12812 } 12813 12814 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12815 CXXConstructorDecl *CopyConstructor) { 12816 assert((CopyConstructor->isDefaulted() && 12817 CopyConstructor->isCopyConstructor() && 12818 !CopyConstructor->doesThisDeclarationHaveABody() && 12819 !CopyConstructor->isDeleted()) && 12820 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12821 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12822 return; 12823 12824 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12825 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12826 12827 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12828 12829 // The exception specification is needed because we are defining the 12830 // function. 12831 ResolveExceptionSpec(CurrentLocation, 12832 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12833 MarkVTableUsed(CurrentLocation, ClassDecl); 12834 12835 // Add a context note for diagnostics produced after this point. 12836 Scope.addContextNote(CurrentLocation); 12837 12838 // C++11 [class.copy]p7: 12839 // The [definition of an implicitly declared copy constructor] is 12840 // deprecated if the class has a user-declared copy assignment operator 12841 // or a user-declared destructor. 12842 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12843 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12844 12845 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12846 CopyConstructor->setInvalidDecl(); 12847 } else { 12848 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 12849 ? CopyConstructor->getEndLoc() 12850 : CopyConstructor->getLocation(); 12851 Sema::CompoundScopeRAII CompoundScope(*this); 12852 CopyConstructor->setBody( 12853 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12854 CopyConstructor->markUsed(Context); 12855 } 12856 12857 if (ASTMutationListener *L = getASTMutationListener()) { 12858 L->CompletedImplicitDefinition(CopyConstructor); 12859 } 12860 } 12861 12862 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12863 CXXRecordDecl *ClassDecl) { 12864 assert(ClassDecl->needsImplicitMoveConstructor()); 12865 12866 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12867 if (DSM.isAlreadyBeingDeclared()) 12868 return nullptr; 12869 12870 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12871 12872 QualType ArgType = ClassType; 12873 if (Context.getLangOpts().OpenCLCPlusPlus) 12874 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic); 12875 ArgType = Context.getRValueReferenceType(ArgType); 12876 12877 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12878 CXXMoveConstructor, 12879 false); 12880 12881 DeclarationName Name 12882 = Context.DeclarationNames.getCXXConstructorName( 12883 Context.getCanonicalType(ClassType)); 12884 SourceLocation ClassLoc = ClassDecl->getLocation(); 12885 DeclarationNameInfo NameInfo(Name, ClassLoc); 12886 12887 // C++11 [class.copy]p11: 12888 // An implicitly-declared copy/move constructor is an inline public 12889 // member of its class. 12890 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12891 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12892 ExplicitSpecifier(), 12893 /*isInline=*/true, 12894 /*isImplicitlyDeclared=*/true, 12895 Constexpr ? CSK_constexpr : CSK_unspecified); 12896 MoveConstructor->setAccess(AS_public); 12897 MoveConstructor->setDefaulted(); 12898 12899 if (getLangOpts().CUDA) { 12900 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12901 MoveConstructor, 12902 /* ConstRHS */ false, 12903 /* Diagnose */ false); 12904 } 12905 12906 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 12907 12908 // Add the parameter to the constructor. 12909 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12910 ClassLoc, ClassLoc, 12911 /*IdentifierInfo=*/nullptr, 12912 ArgType, /*TInfo=*/nullptr, 12913 SC_None, nullptr); 12914 MoveConstructor->setParams(FromParam); 12915 12916 MoveConstructor->setTrivial( 12917 ClassDecl->needsOverloadResolutionForMoveConstructor() 12918 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12919 : ClassDecl->hasTrivialMoveConstructor()); 12920 12921 MoveConstructor->setTrivialForCall( 12922 ClassDecl->hasAttr<TrivialABIAttr>() || 12923 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12924 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12925 TAH_ConsiderTrivialABI) 12926 : ClassDecl->hasTrivialMoveConstructorForCall())); 12927 12928 // Note that we have declared this constructor. 12929 ++getASTContext().NumImplicitMoveConstructorsDeclared; 12930 12931 Scope *S = getScopeForContext(ClassDecl); 12932 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12933 12934 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12935 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12936 SetDeclDeleted(MoveConstructor, ClassLoc); 12937 } 12938 12939 if (S) 12940 PushOnScopeChains(MoveConstructor, S, false); 12941 ClassDecl->addDecl(MoveConstructor); 12942 12943 return MoveConstructor; 12944 } 12945 12946 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12947 CXXConstructorDecl *MoveConstructor) { 12948 assert((MoveConstructor->isDefaulted() && 12949 MoveConstructor->isMoveConstructor() && 12950 !MoveConstructor->doesThisDeclarationHaveABody() && 12951 !MoveConstructor->isDeleted()) && 12952 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12953 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12954 return; 12955 12956 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12957 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12958 12959 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12960 12961 // The exception specification is needed because we are defining the 12962 // function. 12963 ResolveExceptionSpec(CurrentLocation, 12964 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12965 MarkVTableUsed(CurrentLocation, ClassDecl); 12966 12967 // Add a context note for diagnostics produced after this point. 12968 Scope.addContextNote(CurrentLocation); 12969 12970 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12971 MoveConstructor->setInvalidDecl(); 12972 } else { 12973 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 12974 ? MoveConstructor->getEndLoc() 12975 : MoveConstructor->getLocation(); 12976 Sema::CompoundScopeRAII CompoundScope(*this); 12977 MoveConstructor->setBody(ActOnCompoundStmt( 12978 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12979 MoveConstructor->markUsed(Context); 12980 } 12981 12982 if (ASTMutationListener *L = getASTMutationListener()) { 12983 L->CompletedImplicitDefinition(MoveConstructor); 12984 } 12985 } 12986 12987 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12988 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12989 } 12990 12991 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12992 SourceLocation CurrentLocation, 12993 CXXConversionDecl *Conv) { 12994 SynthesizedFunctionScope Scope(*this, Conv); 12995 assert(!Conv->getReturnType()->isUndeducedType()); 12996 12997 CXXRecordDecl *Lambda = Conv->getParent(); 12998 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12999 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 13000 13001 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 13002 CallOp = InstantiateFunctionDeclaration( 13003 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 13004 if (!CallOp) 13005 return; 13006 13007 Invoker = InstantiateFunctionDeclaration( 13008 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 13009 if (!Invoker) 13010 return; 13011 } 13012 13013 if (CallOp->isInvalidDecl()) 13014 return; 13015 13016 // Mark the call operator referenced (and add to pending instantiations 13017 // if necessary). 13018 // For both the conversion and static-invoker template specializations 13019 // we construct their body's in this function, so no need to add them 13020 // to the PendingInstantiations. 13021 MarkFunctionReferenced(CurrentLocation, CallOp); 13022 13023 // Fill in the __invoke function with a dummy implementation. IR generation 13024 // will fill in the actual details. Update its type in case it contained 13025 // an 'auto'. 13026 Invoker->markUsed(Context); 13027 Invoker->setReferenced(); 13028 Invoker->setType(Conv->getReturnType()->getPointeeType()); 13029 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 13030 13031 // Construct the body of the conversion function { return __invoke; }. 13032 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 13033 VK_LValue, Conv->getLocation()); 13034 assert(FunctionRef && "Can't refer to __invoke function?"); 13035 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 13036 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 13037 Conv->getLocation())); 13038 Conv->markUsed(Context); 13039 Conv->setReferenced(); 13040 13041 if (ASTMutationListener *L = getASTMutationListener()) { 13042 L->CompletedImplicitDefinition(Conv); 13043 L->CompletedImplicitDefinition(Invoker); 13044 } 13045 } 13046 13047 13048 13049 void Sema::DefineImplicitLambdaToBlockPointerConversion( 13050 SourceLocation CurrentLocation, 13051 CXXConversionDecl *Conv) 13052 { 13053 assert(!Conv->getParent()->isGenericLambda()); 13054 13055 SynthesizedFunctionScope Scope(*this, Conv); 13056 13057 // Copy-initialize the lambda object as needed to capture it. 13058 Expr *This = ActOnCXXThis(CurrentLocation).get(); 13059 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 13060 13061 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 13062 Conv->getLocation(), 13063 Conv, DerefThis); 13064 13065 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 13066 // behavior. Note that only the general conversion function does this 13067 // (since it's unusable otherwise); in the case where we inline the 13068 // block literal, it has block literal lifetime semantics. 13069 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 13070 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 13071 CK_CopyAndAutoreleaseBlockObject, 13072 BuildBlock.get(), nullptr, VK_RValue); 13073 13074 if (BuildBlock.isInvalid()) { 13075 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 13076 Conv->setInvalidDecl(); 13077 return; 13078 } 13079 13080 // Create the return statement that returns the block from the conversion 13081 // function. 13082 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 13083 if (Return.isInvalid()) { 13084 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 13085 Conv->setInvalidDecl(); 13086 return; 13087 } 13088 13089 // Set the body of the conversion function. 13090 Stmt *ReturnS = Return.get(); 13091 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 13092 Conv->getLocation())); 13093 Conv->markUsed(Context); 13094 13095 // We're done; notify the mutation listener, if any. 13096 if (ASTMutationListener *L = getASTMutationListener()) { 13097 L->CompletedImplicitDefinition(Conv); 13098 } 13099 } 13100 13101 /// Determine whether the given list arguments contains exactly one 13102 /// "real" (non-default) argument. 13103 static bool hasOneRealArgument(MultiExprArg Args) { 13104 switch (Args.size()) { 13105 case 0: 13106 return false; 13107 13108 default: 13109 if (!Args[1]->isDefaultArgument()) 13110 return false; 13111 13112 LLVM_FALLTHROUGH; 13113 case 1: 13114 return !Args[0]->isDefaultArgument(); 13115 } 13116 13117 return false; 13118 } 13119 13120 ExprResult 13121 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13122 NamedDecl *FoundDecl, 13123 CXXConstructorDecl *Constructor, 13124 MultiExprArg ExprArgs, 13125 bool HadMultipleCandidates, 13126 bool IsListInitialization, 13127 bool IsStdInitListInitialization, 13128 bool RequiresZeroInit, 13129 unsigned ConstructKind, 13130 SourceRange ParenRange) { 13131 bool Elidable = false; 13132 13133 // C++0x [class.copy]p34: 13134 // When certain criteria are met, an implementation is allowed to 13135 // omit the copy/move construction of a class object, even if the 13136 // copy/move constructor and/or destructor for the object have 13137 // side effects. [...] 13138 // - when a temporary class object that has not been bound to a 13139 // reference (12.2) would be copied/moved to a class object 13140 // with the same cv-unqualified type, the copy/move operation 13141 // can be omitted by constructing the temporary object 13142 // directly into the target of the omitted copy/move 13143 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 13144 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 13145 Expr *SubExpr = ExprArgs[0]; 13146 Elidable = SubExpr->isTemporaryObject( 13147 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 13148 } 13149 13150 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 13151 FoundDecl, Constructor, 13152 Elidable, ExprArgs, HadMultipleCandidates, 13153 IsListInitialization, 13154 IsStdInitListInitialization, RequiresZeroInit, 13155 ConstructKind, ParenRange); 13156 } 13157 13158 ExprResult 13159 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13160 NamedDecl *FoundDecl, 13161 CXXConstructorDecl *Constructor, 13162 bool Elidable, 13163 MultiExprArg ExprArgs, 13164 bool HadMultipleCandidates, 13165 bool IsListInitialization, 13166 bool IsStdInitListInitialization, 13167 bool RequiresZeroInit, 13168 unsigned ConstructKind, 13169 SourceRange ParenRange) { 13170 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 13171 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 13172 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 13173 return ExprError(); 13174 } 13175 13176 return BuildCXXConstructExpr( 13177 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 13178 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 13179 RequiresZeroInit, ConstructKind, ParenRange); 13180 } 13181 13182 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 13183 /// including handling of its default argument expressions. 13184 ExprResult 13185 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13186 CXXConstructorDecl *Constructor, 13187 bool Elidable, 13188 MultiExprArg ExprArgs, 13189 bool HadMultipleCandidates, 13190 bool IsListInitialization, 13191 bool IsStdInitListInitialization, 13192 bool RequiresZeroInit, 13193 unsigned ConstructKind, 13194 SourceRange ParenRange) { 13195 assert(declaresSameEntity( 13196 Constructor->getParent(), 13197 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 13198 "given constructor for wrong type"); 13199 MarkFunctionReferenced(ConstructLoc, Constructor); 13200 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 13201 return ExprError(); 13202 13203 return CXXConstructExpr::Create( 13204 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 13205 ExprArgs, HadMultipleCandidates, IsListInitialization, 13206 IsStdInitListInitialization, RequiresZeroInit, 13207 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 13208 ParenRange); 13209 } 13210 13211 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 13212 assert(Field->hasInClassInitializer()); 13213 13214 // If we already have the in-class initializer nothing needs to be done. 13215 if (Field->getInClassInitializer()) 13216 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13217 13218 // If we might have already tried and failed to instantiate, don't try again. 13219 if (Field->isInvalidDecl()) 13220 return ExprError(); 13221 13222 // Maybe we haven't instantiated the in-class initializer. Go check the 13223 // pattern FieldDecl to see if it has one. 13224 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 13225 13226 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 13227 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 13228 DeclContext::lookup_result Lookup = 13229 ClassPattern->lookup(Field->getDeclName()); 13230 13231 // Lookup can return at most two results: the pattern for the field, or the 13232 // injected class name of the parent record. No other member can have the 13233 // same name as the field. 13234 // In modules mode, lookup can return multiple results (coming from 13235 // different modules). 13236 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 13237 "more than two lookup results for field name"); 13238 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 13239 if (!Pattern) { 13240 assert(isa<CXXRecordDecl>(Lookup[0]) && 13241 "cannot have other non-field member with same name"); 13242 for (auto L : Lookup) 13243 if (isa<FieldDecl>(L)) { 13244 Pattern = cast<FieldDecl>(L); 13245 break; 13246 } 13247 assert(Pattern && "We must have set the Pattern!"); 13248 } 13249 13250 if (!Pattern->hasInClassInitializer() || 13251 InstantiateInClassInitializer(Loc, Field, Pattern, 13252 getTemplateInstantiationArgs(Field))) { 13253 // Don't diagnose this again. 13254 Field->setInvalidDecl(); 13255 return ExprError(); 13256 } 13257 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13258 } 13259 13260 // DR1351: 13261 // If the brace-or-equal-initializer of a non-static data member 13262 // invokes a defaulted default constructor of its class or of an 13263 // enclosing class in a potentially evaluated subexpression, the 13264 // program is ill-formed. 13265 // 13266 // This resolution is unworkable: the exception specification of the 13267 // default constructor can be needed in an unevaluated context, in 13268 // particular, in the operand of a noexcept-expression, and we can be 13269 // unable to compute an exception specification for an enclosed class. 13270 // 13271 // Any attempt to resolve the exception specification of a defaulted default 13272 // constructor before the initializer is lexically complete will ultimately 13273 // come here at which point we can diagnose it. 13274 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 13275 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 13276 << OutermostClass << Field; 13277 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 13278 // Recover by marking the field invalid, unless we're in a SFINAE context. 13279 if (!isSFINAEContext()) 13280 Field->setInvalidDecl(); 13281 return ExprError(); 13282 } 13283 13284 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 13285 if (VD->isInvalidDecl()) return; 13286 13287 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 13288 if (ClassDecl->isInvalidDecl()) return; 13289 if (ClassDecl->hasIrrelevantDestructor()) return; 13290 if (ClassDecl->isDependentContext()) return; 13291 13292 if (VD->isNoDestroy(getASTContext())) 13293 return; 13294 13295 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13296 13297 // If this is an array, we'll require the destructor during initialization, so 13298 // we can skip over this. We still want to emit exit-time destructor warnings 13299 // though. 13300 if (!VD->getType()->isArrayType()) { 13301 MarkFunctionReferenced(VD->getLocation(), Destructor); 13302 CheckDestructorAccess(VD->getLocation(), Destructor, 13303 PDiag(diag::err_access_dtor_var) 13304 << VD->getDeclName() << VD->getType()); 13305 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 13306 } 13307 13308 if (Destructor->isTrivial()) return; 13309 if (!VD->hasGlobalStorage()) return; 13310 13311 // Emit warning for non-trivial dtor in global scope (a real global, 13312 // class-static, function-static). 13313 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 13314 13315 // TODO: this should be re-enabled for static locals by !CXAAtExit 13316 if (!VD->isStaticLocal()) 13317 Diag(VD->getLocation(), diag::warn_global_destructor); 13318 } 13319 13320 /// Given a constructor and the set of arguments provided for the 13321 /// constructor, convert the arguments and add any required default arguments 13322 /// to form a proper call to this constructor. 13323 /// 13324 /// \returns true if an error occurred, false otherwise. 13325 bool 13326 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 13327 MultiExprArg ArgsPtr, 13328 SourceLocation Loc, 13329 SmallVectorImpl<Expr*> &ConvertedArgs, 13330 bool AllowExplicit, 13331 bool IsListInitialization) { 13332 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 13333 unsigned NumArgs = ArgsPtr.size(); 13334 Expr **Args = ArgsPtr.data(); 13335 13336 const FunctionProtoType *Proto 13337 = Constructor->getType()->getAs<FunctionProtoType>(); 13338 assert(Proto && "Constructor without a prototype?"); 13339 unsigned NumParams = Proto->getNumParams(); 13340 13341 // If too few arguments are available, we'll fill in the rest with defaults. 13342 if (NumArgs < NumParams) 13343 ConvertedArgs.reserve(NumParams); 13344 else 13345 ConvertedArgs.reserve(NumArgs); 13346 13347 VariadicCallType CallType = 13348 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 13349 SmallVector<Expr *, 8> AllArgs; 13350 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 13351 Proto, 0, 13352 llvm::makeArrayRef(Args, NumArgs), 13353 AllArgs, 13354 CallType, AllowExplicit, 13355 IsListInitialization); 13356 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 13357 13358 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 13359 13360 CheckConstructorCall(Constructor, 13361 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 13362 Proto, Loc); 13363 13364 return Invalid; 13365 } 13366 13367 static inline bool 13368 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 13369 const FunctionDecl *FnDecl) { 13370 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 13371 if (isa<NamespaceDecl>(DC)) { 13372 return SemaRef.Diag(FnDecl->getLocation(), 13373 diag::err_operator_new_delete_declared_in_namespace) 13374 << FnDecl->getDeclName(); 13375 } 13376 13377 if (isa<TranslationUnitDecl>(DC) && 13378 FnDecl->getStorageClass() == SC_Static) { 13379 return SemaRef.Diag(FnDecl->getLocation(), 13380 diag::err_operator_new_delete_declared_static) 13381 << FnDecl->getDeclName(); 13382 } 13383 13384 return false; 13385 } 13386 13387 static QualType 13388 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13389 QualType QTy = PtrTy->getPointeeType(); 13390 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13391 return SemaRef.Context.getPointerType(QTy); 13392 } 13393 13394 static inline bool 13395 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13396 CanQualType ExpectedResultType, 13397 CanQualType ExpectedFirstParamType, 13398 unsigned DependentParamTypeDiag, 13399 unsigned InvalidParamTypeDiag) { 13400 QualType ResultType = 13401 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13402 13403 // Check that the result type is not dependent. 13404 if (ResultType->isDependentType()) 13405 return SemaRef.Diag(FnDecl->getLocation(), 13406 diag::err_operator_new_delete_dependent_result_type) 13407 << FnDecl->getDeclName() << ExpectedResultType; 13408 13409 // The operator is valid on any address space for OpenCL. 13410 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13411 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13412 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13413 } 13414 } 13415 13416 // Check that the result type is what we expect. 13417 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13418 return SemaRef.Diag(FnDecl->getLocation(), 13419 diag::err_operator_new_delete_invalid_result_type) 13420 << FnDecl->getDeclName() << ExpectedResultType; 13421 13422 // A function template must have at least 2 parameters. 13423 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13424 return SemaRef.Diag(FnDecl->getLocation(), 13425 diag::err_operator_new_delete_template_too_few_parameters) 13426 << FnDecl->getDeclName(); 13427 13428 // The function decl must have at least 1 parameter. 13429 if (FnDecl->getNumParams() == 0) 13430 return SemaRef.Diag(FnDecl->getLocation(), 13431 diag::err_operator_new_delete_too_few_parameters) 13432 << FnDecl->getDeclName(); 13433 13434 // Check the first parameter type is not dependent. 13435 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13436 if (FirstParamType->isDependentType()) 13437 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13438 << FnDecl->getDeclName() << ExpectedFirstParamType; 13439 13440 // Check that the first parameter type is what we expect. 13441 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13442 // The operator is valid on any address space for OpenCL. 13443 if (auto *PtrTy = 13444 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13445 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13446 } 13447 } 13448 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13449 ExpectedFirstParamType) 13450 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13451 << FnDecl->getDeclName() << ExpectedFirstParamType; 13452 13453 return false; 13454 } 13455 13456 static bool 13457 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13458 // C++ [basic.stc.dynamic.allocation]p1: 13459 // A program is ill-formed if an allocation function is declared in a 13460 // namespace scope other than global scope or declared static in global 13461 // scope. 13462 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13463 return true; 13464 13465 CanQualType SizeTy = 13466 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13467 13468 // C++ [basic.stc.dynamic.allocation]p1: 13469 // The return type shall be void*. The first parameter shall have type 13470 // std::size_t. 13471 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13472 SizeTy, 13473 diag::err_operator_new_dependent_param_type, 13474 diag::err_operator_new_param_type)) 13475 return true; 13476 13477 // C++ [basic.stc.dynamic.allocation]p1: 13478 // The first parameter shall not have an associated default argument. 13479 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13480 return SemaRef.Diag(FnDecl->getLocation(), 13481 diag::err_operator_new_default_arg) 13482 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13483 13484 return false; 13485 } 13486 13487 static bool 13488 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13489 // C++ [basic.stc.dynamic.deallocation]p1: 13490 // A program is ill-formed if deallocation functions are declared in a 13491 // namespace scope other than global scope or declared static in global 13492 // scope. 13493 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13494 return true; 13495 13496 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13497 13498 // C++ P0722: 13499 // Within a class C, the first parameter of a destroying operator delete 13500 // shall be of type C *. The first parameter of any other deallocation 13501 // function shall be of type void *. 13502 CanQualType ExpectedFirstParamType = 13503 MD && MD->isDestroyingOperatorDelete() 13504 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13505 SemaRef.Context.getRecordType(MD->getParent()))) 13506 : SemaRef.Context.VoidPtrTy; 13507 13508 // C++ [basic.stc.dynamic.deallocation]p2: 13509 // Each deallocation function shall return void 13510 if (CheckOperatorNewDeleteTypes( 13511 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13512 diag::err_operator_delete_dependent_param_type, 13513 diag::err_operator_delete_param_type)) 13514 return true; 13515 13516 // C++ P0722: 13517 // A destroying operator delete shall be a usual deallocation function. 13518 if (MD && !MD->getParent()->isDependentContext() && 13519 MD->isDestroyingOperatorDelete() && 13520 !SemaRef.isUsualDeallocationFunction(MD)) { 13521 SemaRef.Diag(MD->getLocation(), 13522 diag::err_destroying_operator_delete_not_usual); 13523 return true; 13524 } 13525 13526 return false; 13527 } 13528 13529 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13530 /// of this overloaded operator is well-formed. If so, returns false; 13531 /// otherwise, emits appropriate diagnostics and returns true. 13532 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13533 assert(FnDecl && FnDecl->isOverloadedOperator() && 13534 "Expected an overloaded operator declaration"); 13535 13536 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13537 13538 // C++ [over.oper]p5: 13539 // The allocation and deallocation functions, operator new, 13540 // operator new[], operator delete and operator delete[], are 13541 // described completely in 3.7.3. The attributes and restrictions 13542 // found in the rest of this subclause do not apply to them unless 13543 // explicitly stated in 3.7.3. 13544 if (Op == OO_Delete || Op == OO_Array_Delete) 13545 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13546 13547 if (Op == OO_New || Op == OO_Array_New) 13548 return CheckOperatorNewDeclaration(*this, FnDecl); 13549 13550 // C++ [over.oper]p6: 13551 // An operator function shall either be a non-static member 13552 // function or be a non-member function and have at least one 13553 // parameter whose type is a class, a reference to a class, an 13554 // enumeration, or a reference to an enumeration. 13555 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13556 if (MethodDecl->isStatic()) 13557 return Diag(FnDecl->getLocation(), 13558 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13559 } else { 13560 bool ClassOrEnumParam = false; 13561 for (auto Param : FnDecl->parameters()) { 13562 QualType ParamType = Param->getType().getNonReferenceType(); 13563 if (ParamType->isDependentType() || ParamType->isRecordType() || 13564 ParamType->isEnumeralType()) { 13565 ClassOrEnumParam = true; 13566 break; 13567 } 13568 } 13569 13570 if (!ClassOrEnumParam) 13571 return Diag(FnDecl->getLocation(), 13572 diag::err_operator_overload_needs_class_or_enum) 13573 << FnDecl->getDeclName(); 13574 } 13575 13576 // C++ [over.oper]p8: 13577 // An operator function cannot have default arguments (8.3.6), 13578 // except where explicitly stated below. 13579 // 13580 // Only the function-call operator allows default arguments 13581 // (C++ [over.call]p1). 13582 if (Op != OO_Call) { 13583 for (auto Param : FnDecl->parameters()) { 13584 if (Param->hasDefaultArg()) 13585 return Diag(Param->getLocation(), 13586 diag::err_operator_overload_default_arg) 13587 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13588 } 13589 } 13590 13591 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13592 { false, false, false } 13593 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13594 , { Unary, Binary, MemberOnly } 13595 #include "clang/Basic/OperatorKinds.def" 13596 }; 13597 13598 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13599 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13600 bool MustBeMemberOperator = OperatorUses[Op][2]; 13601 13602 // C++ [over.oper]p8: 13603 // [...] Operator functions cannot have more or fewer parameters 13604 // than the number required for the corresponding operator, as 13605 // described in the rest of this subclause. 13606 unsigned NumParams = FnDecl->getNumParams() 13607 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13608 if (Op != OO_Call && 13609 ((NumParams == 1 && !CanBeUnaryOperator) || 13610 (NumParams == 2 && !CanBeBinaryOperator) || 13611 (NumParams < 1) || (NumParams > 2))) { 13612 // We have the wrong number of parameters. 13613 unsigned ErrorKind; 13614 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13615 ErrorKind = 2; // 2 -> unary or binary. 13616 } else if (CanBeUnaryOperator) { 13617 ErrorKind = 0; // 0 -> unary 13618 } else { 13619 assert(CanBeBinaryOperator && 13620 "All non-call overloaded operators are unary or binary!"); 13621 ErrorKind = 1; // 1 -> binary 13622 } 13623 13624 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13625 << FnDecl->getDeclName() << NumParams << ErrorKind; 13626 } 13627 13628 // Overloaded operators other than operator() cannot be variadic. 13629 if (Op != OO_Call && 13630 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13631 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13632 << FnDecl->getDeclName(); 13633 } 13634 13635 // Some operators must be non-static member functions. 13636 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13637 return Diag(FnDecl->getLocation(), 13638 diag::err_operator_overload_must_be_member) 13639 << FnDecl->getDeclName(); 13640 } 13641 13642 // C++ [over.inc]p1: 13643 // The user-defined function called operator++ implements the 13644 // prefix and postfix ++ operator. If this function is a member 13645 // function with no parameters, or a non-member function with one 13646 // parameter of class or enumeration type, it defines the prefix 13647 // increment operator ++ for objects of that type. If the function 13648 // is a member function with one parameter (which shall be of type 13649 // int) or a non-member function with two parameters (the second 13650 // of which shall be of type int), it defines the postfix 13651 // increment operator ++ for objects of that type. 13652 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13653 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13654 QualType ParamType = LastParam->getType(); 13655 13656 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13657 !ParamType->isDependentType()) 13658 return Diag(LastParam->getLocation(), 13659 diag::err_operator_overload_post_incdec_must_be_int) 13660 << LastParam->getType() << (Op == OO_MinusMinus); 13661 } 13662 13663 return false; 13664 } 13665 13666 static bool 13667 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13668 FunctionTemplateDecl *TpDecl) { 13669 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13670 13671 // Must have one or two template parameters. 13672 if (TemplateParams->size() == 1) { 13673 NonTypeTemplateParmDecl *PmDecl = 13674 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13675 13676 // The template parameter must be a char parameter pack. 13677 if (PmDecl && PmDecl->isTemplateParameterPack() && 13678 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13679 return false; 13680 13681 } else if (TemplateParams->size() == 2) { 13682 TemplateTypeParmDecl *PmType = 13683 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13684 NonTypeTemplateParmDecl *PmArgs = 13685 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13686 13687 // The second template parameter must be a parameter pack with the 13688 // first template parameter as its type. 13689 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13690 PmArgs->isTemplateParameterPack()) { 13691 const TemplateTypeParmType *TArgs = 13692 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13693 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13694 TArgs->getIndex() == PmType->getIndex()) { 13695 if (!SemaRef.inTemplateInstantiation()) 13696 SemaRef.Diag(TpDecl->getLocation(), 13697 diag::ext_string_literal_operator_template); 13698 return false; 13699 } 13700 } 13701 } 13702 13703 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13704 diag::err_literal_operator_template) 13705 << TpDecl->getTemplateParameters()->getSourceRange(); 13706 return true; 13707 } 13708 13709 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13710 /// of this literal operator function is well-formed. If so, returns 13711 /// false; otherwise, emits appropriate diagnostics and returns true. 13712 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13713 if (isa<CXXMethodDecl>(FnDecl)) { 13714 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13715 << FnDecl->getDeclName(); 13716 return true; 13717 } 13718 13719 if (FnDecl->isExternC()) { 13720 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13721 if (const LinkageSpecDecl *LSD = 13722 FnDecl->getDeclContext()->getExternCContext()) 13723 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13724 return true; 13725 } 13726 13727 // This might be the definition of a literal operator template. 13728 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13729 13730 // This might be a specialization of a literal operator template. 13731 if (!TpDecl) 13732 TpDecl = FnDecl->getPrimaryTemplate(); 13733 13734 // template <char...> type operator "" name() and 13735 // template <class T, T...> type operator "" name() are the only valid 13736 // template signatures, and the only valid signatures with no parameters. 13737 if (TpDecl) { 13738 if (FnDecl->param_size() != 0) { 13739 Diag(FnDecl->getLocation(), 13740 diag::err_literal_operator_template_with_params); 13741 return true; 13742 } 13743 13744 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13745 return true; 13746 13747 } else if (FnDecl->param_size() == 1) { 13748 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13749 13750 QualType ParamType = Param->getType().getUnqualifiedType(); 13751 13752 // Only unsigned long long int, long double, any character type, and const 13753 // char * are allowed as the only parameters. 13754 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13755 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13756 Context.hasSameType(ParamType, Context.CharTy) || 13757 Context.hasSameType(ParamType, Context.WideCharTy) || 13758 Context.hasSameType(ParamType, Context.Char8Ty) || 13759 Context.hasSameType(ParamType, Context.Char16Ty) || 13760 Context.hasSameType(ParamType, Context.Char32Ty)) { 13761 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13762 QualType InnerType = Ptr->getPointeeType(); 13763 13764 // Pointer parameter must be a const char *. 13765 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13766 Context.CharTy) && 13767 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13768 Diag(Param->getSourceRange().getBegin(), 13769 diag::err_literal_operator_param) 13770 << ParamType << "'const char *'" << Param->getSourceRange(); 13771 return true; 13772 } 13773 13774 } else if (ParamType->isRealFloatingType()) { 13775 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13776 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13777 return true; 13778 13779 } else if (ParamType->isIntegerType()) { 13780 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13781 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13782 return true; 13783 13784 } else { 13785 Diag(Param->getSourceRange().getBegin(), 13786 diag::err_literal_operator_invalid_param) 13787 << ParamType << Param->getSourceRange(); 13788 return true; 13789 } 13790 13791 } else if (FnDecl->param_size() == 2) { 13792 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13793 13794 // First, verify that the first parameter is correct. 13795 13796 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13797 13798 // Two parameter function must have a pointer to const as a 13799 // first parameter; let's strip those qualifiers. 13800 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13801 13802 if (!PT) { 13803 Diag((*Param)->getSourceRange().getBegin(), 13804 diag::err_literal_operator_param) 13805 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13806 return true; 13807 } 13808 13809 QualType PointeeType = PT->getPointeeType(); 13810 // First parameter must be const 13811 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13812 Diag((*Param)->getSourceRange().getBegin(), 13813 diag::err_literal_operator_param) 13814 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13815 return true; 13816 } 13817 13818 QualType InnerType = PointeeType.getUnqualifiedType(); 13819 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13820 // const char32_t* are allowed as the first parameter to a two-parameter 13821 // function 13822 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13823 Context.hasSameType(InnerType, Context.WideCharTy) || 13824 Context.hasSameType(InnerType, Context.Char8Ty) || 13825 Context.hasSameType(InnerType, Context.Char16Ty) || 13826 Context.hasSameType(InnerType, Context.Char32Ty))) { 13827 Diag((*Param)->getSourceRange().getBegin(), 13828 diag::err_literal_operator_param) 13829 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13830 return true; 13831 } 13832 13833 // Move on to the second and final parameter. 13834 ++Param; 13835 13836 // The second parameter must be a std::size_t. 13837 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13838 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13839 Diag((*Param)->getSourceRange().getBegin(), 13840 diag::err_literal_operator_param) 13841 << SecondParamType << Context.getSizeType() 13842 << (*Param)->getSourceRange(); 13843 return true; 13844 } 13845 } else { 13846 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13847 return true; 13848 } 13849 13850 // Parameters are good. 13851 13852 // A parameter-declaration-clause containing a default argument is not 13853 // equivalent to any of the permitted forms. 13854 for (auto Param : FnDecl->parameters()) { 13855 if (Param->hasDefaultArg()) { 13856 Diag(Param->getDefaultArgRange().getBegin(), 13857 diag::err_literal_operator_default_argument) 13858 << Param->getDefaultArgRange(); 13859 break; 13860 } 13861 } 13862 13863 StringRef LiteralName 13864 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13865 if (LiteralName[0] != '_' && 13866 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13867 // C++11 [usrlit.suffix]p1: 13868 // Literal suffix identifiers that do not start with an underscore 13869 // are reserved for future standardization. 13870 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13871 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13872 } 13873 13874 return false; 13875 } 13876 13877 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13878 /// linkage specification, including the language and (if present) 13879 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13880 /// language string literal. LBraceLoc, if valid, provides the location of 13881 /// the '{' brace. Otherwise, this linkage specification does not 13882 /// have any braces. 13883 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13884 Expr *LangStr, 13885 SourceLocation LBraceLoc) { 13886 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13887 if (!Lit->isAscii()) { 13888 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13889 << LangStr->getSourceRange(); 13890 return nullptr; 13891 } 13892 13893 StringRef Lang = Lit->getString(); 13894 LinkageSpecDecl::LanguageIDs Language; 13895 if (Lang == "C") 13896 Language = LinkageSpecDecl::lang_c; 13897 else if (Lang == "C++") 13898 Language = LinkageSpecDecl::lang_cxx; 13899 else { 13900 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13901 << LangStr->getSourceRange(); 13902 return nullptr; 13903 } 13904 13905 // FIXME: Add all the various semantics of linkage specifications 13906 13907 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13908 LangStr->getExprLoc(), Language, 13909 LBraceLoc.isValid()); 13910 CurContext->addDecl(D); 13911 PushDeclContext(S, D); 13912 return D; 13913 } 13914 13915 /// ActOnFinishLinkageSpecification - Complete the definition of 13916 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13917 /// valid, it's the position of the closing '}' brace in a linkage 13918 /// specification that uses braces. 13919 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13920 Decl *LinkageSpec, 13921 SourceLocation RBraceLoc) { 13922 if (RBraceLoc.isValid()) { 13923 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13924 LSDecl->setRBraceLoc(RBraceLoc); 13925 } 13926 PopDeclContext(); 13927 return LinkageSpec; 13928 } 13929 13930 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13931 const ParsedAttributesView &AttrList, 13932 SourceLocation SemiLoc) { 13933 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13934 // Attribute declarations appertain to empty declaration so we handle 13935 // them here. 13936 ProcessDeclAttributeList(S, ED, AttrList); 13937 13938 CurContext->addDecl(ED); 13939 return ED; 13940 } 13941 13942 /// Perform semantic analysis for the variable declaration that 13943 /// occurs within a C++ catch clause, returning the newly-created 13944 /// variable. 13945 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13946 TypeSourceInfo *TInfo, 13947 SourceLocation StartLoc, 13948 SourceLocation Loc, 13949 IdentifierInfo *Name) { 13950 bool Invalid = false; 13951 QualType ExDeclType = TInfo->getType(); 13952 13953 // Arrays and functions decay. 13954 if (ExDeclType->isArrayType()) 13955 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13956 else if (ExDeclType->isFunctionType()) 13957 ExDeclType = Context.getPointerType(ExDeclType); 13958 13959 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13960 // The exception-declaration shall not denote a pointer or reference to an 13961 // incomplete type, other than [cv] void*. 13962 // N2844 forbids rvalue references. 13963 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13964 Diag(Loc, diag::err_catch_rvalue_ref); 13965 Invalid = true; 13966 } 13967 13968 if (ExDeclType->isVariablyModifiedType()) { 13969 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13970 Invalid = true; 13971 } 13972 13973 QualType BaseType = ExDeclType; 13974 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13975 unsigned DK = diag::err_catch_incomplete; 13976 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13977 BaseType = Ptr->getPointeeType(); 13978 Mode = 1; 13979 DK = diag::err_catch_incomplete_ptr; 13980 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13981 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13982 BaseType = Ref->getPointeeType(); 13983 Mode = 2; 13984 DK = diag::err_catch_incomplete_ref; 13985 } 13986 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13987 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13988 Invalid = true; 13989 13990 if (!Invalid && !ExDeclType->isDependentType() && 13991 RequireNonAbstractType(Loc, ExDeclType, 13992 diag::err_abstract_type_in_decl, 13993 AbstractVariableType)) 13994 Invalid = true; 13995 13996 // Only the non-fragile NeXT runtime currently supports C++ catches 13997 // of ObjC types, and no runtime supports catching ObjC types by value. 13998 if (!Invalid && getLangOpts().ObjC) { 13999 QualType T = ExDeclType; 14000 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 14001 T = RT->getPointeeType(); 14002 14003 if (T->isObjCObjectType()) { 14004 Diag(Loc, diag::err_objc_object_catch); 14005 Invalid = true; 14006 } else if (T->isObjCObjectPointerType()) { 14007 // FIXME: should this be a test for macosx-fragile specifically? 14008 if (getLangOpts().ObjCRuntime.isFragile()) 14009 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 14010 } 14011 } 14012 14013 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 14014 ExDeclType, TInfo, SC_None); 14015 ExDecl->setExceptionVariable(true); 14016 14017 // In ARC, infer 'retaining' for variables of retainable type. 14018 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 14019 Invalid = true; 14020 14021 if (!Invalid && !ExDeclType->isDependentType()) { 14022 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 14023 // Insulate this from anything else we might currently be parsing. 14024 EnterExpressionEvaluationContext scope( 14025 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14026 14027 // C++ [except.handle]p16: 14028 // The object declared in an exception-declaration or, if the 14029 // exception-declaration does not specify a name, a temporary (12.2) is 14030 // copy-initialized (8.5) from the exception object. [...] 14031 // The object is destroyed when the handler exits, after the destruction 14032 // of any automatic objects initialized within the handler. 14033 // 14034 // We just pretend to initialize the object with itself, then make sure 14035 // it can be destroyed later. 14036 QualType initType = Context.getExceptionObjectType(ExDeclType); 14037 14038 InitializedEntity entity = 14039 InitializedEntity::InitializeVariable(ExDecl); 14040 InitializationKind initKind = 14041 InitializationKind::CreateCopy(Loc, SourceLocation()); 14042 14043 Expr *opaqueValue = 14044 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 14045 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 14046 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 14047 if (result.isInvalid()) 14048 Invalid = true; 14049 else { 14050 // If the constructor used was non-trivial, set this as the 14051 // "initializer". 14052 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 14053 if (!construct->getConstructor()->isTrivial()) { 14054 Expr *init = MaybeCreateExprWithCleanups(construct); 14055 ExDecl->setInit(init); 14056 } 14057 14058 // And make sure it's destructable. 14059 FinalizeVarWithDestructor(ExDecl, recordType); 14060 } 14061 } 14062 } 14063 14064 if (Invalid) 14065 ExDecl->setInvalidDecl(); 14066 14067 return ExDecl; 14068 } 14069 14070 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 14071 /// handler. 14072 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 14073 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14074 bool Invalid = D.isInvalidType(); 14075 14076 // Check for unexpanded parameter packs. 14077 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14078 UPPC_ExceptionType)) { 14079 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 14080 D.getIdentifierLoc()); 14081 Invalid = true; 14082 } 14083 14084 IdentifierInfo *II = D.getIdentifier(); 14085 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 14086 LookupOrdinaryName, 14087 ForVisibleRedeclaration)) { 14088 // The scope should be freshly made just for us. There is just no way 14089 // it contains any previous declaration, except for function parameters in 14090 // a function-try-block's catch statement. 14091 assert(!S->isDeclScope(PrevDecl)); 14092 if (isDeclInScope(PrevDecl, CurContext, S)) { 14093 Diag(D.getIdentifierLoc(), diag::err_redefinition) 14094 << D.getIdentifier(); 14095 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14096 Invalid = true; 14097 } else if (PrevDecl->isTemplateParameter()) 14098 // Maybe we will complain about the shadowed template parameter. 14099 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14100 } 14101 14102 if (D.getCXXScopeSpec().isSet() && !Invalid) { 14103 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 14104 << D.getCXXScopeSpec().getRange(); 14105 Invalid = true; 14106 } 14107 14108 VarDecl *ExDecl = BuildExceptionDeclaration( 14109 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 14110 if (Invalid) 14111 ExDecl->setInvalidDecl(); 14112 14113 // Add the exception declaration into this scope. 14114 if (II) 14115 PushOnScopeChains(ExDecl, S); 14116 else 14117 CurContext->addDecl(ExDecl); 14118 14119 ProcessDeclAttributes(S, ExDecl, D); 14120 return ExDecl; 14121 } 14122 14123 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 14124 Expr *AssertExpr, 14125 Expr *AssertMessageExpr, 14126 SourceLocation RParenLoc) { 14127 StringLiteral *AssertMessage = 14128 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 14129 14130 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 14131 return nullptr; 14132 14133 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 14134 AssertMessage, RParenLoc, false); 14135 } 14136 14137 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 14138 Expr *AssertExpr, 14139 StringLiteral *AssertMessage, 14140 SourceLocation RParenLoc, 14141 bool Failed) { 14142 assert(AssertExpr != nullptr && "Expected non-null condition"); 14143 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 14144 !Failed) { 14145 // In a static_assert-declaration, the constant-expression shall be a 14146 // constant expression that can be contextually converted to bool. 14147 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 14148 if (Converted.isInvalid()) 14149 Failed = true; 14150 14151 llvm::APSInt Cond; 14152 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 14153 diag::err_static_assert_expression_is_not_constant, 14154 /*AllowFold=*/false).isInvalid()) 14155 Failed = true; 14156 14157 if (!Failed && !Cond) { 14158 SmallString<256> MsgBuffer; 14159 llvm::raw_svector_ostream Msg(MsgBuffer); 14160 if (AssertMessage) 14161 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 14162 14163 Expr *InnerCond = nullptr; 14164 std::string InnerCondDescription; 14165 std::tie(InnerCond, InnerCondDescription) = 14166 findFailedBooleanCondition(Converted.get()); 14167 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 14168 && !isa<IntegerLiteral>(InnerCond)) { 14169 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 14170 << InnerCondDescription << !AssertMessage 14171 << Msg.str() << InnerCond->getSourceRange(); 14172 } else { 14173 Diag(StaticAssertLoc, diag::err_static_assert_failed) 14174 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 14175 } 14176 Failed = true; 14177 } 14178 } 14179 14180 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 14181 /*DiscardedValue*/false, 14182 /*IsConstexpr*/true); 14183 if (FullAssertExpr.isInvalid()) 14184 Failed = true; 14185 else 14186 AssertExpr = FullAssertExpr.get(); 14187 14188 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 14189 AssertExpr, AssertMessage, RParenLoc, 14190 Failed); 14191 14192 CurContext->addDecl(Decl); 14193 return Decl; 14194 } 14195 14196 /// Perform semantic analysis of the given friend type declaration. 14197 /// 14198 /// \returns A friend declaration that. 14199 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 14200 SourceLocation FriendLoc, 14201 TypeSourceInfo *TSInfo) { 14202 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 14203 14204 QualType T = TSInfo->getType(); 14205 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 14206 14207 // C++03 [class.friend]p2: 14208 // An elaborated-type-specifier shall be used in a friend declaration 14209 // for a class.* 14210 // 14211 // * The class-key of the elaborated-type-specifier is required. 14212 if (!CodeSynthesisContexts.empty()) { 14213 // Do not complain about the form of friend template types during any kind 14214 // of code synthesis. For template instantiation, we will have complained 14215 // when the template was defined. 14216 } else { 14217 if (!T->isElaboratedTypeSpecifier()) { 14218 // If we evaluated the type to a record type, suggest putting 14219 // a tag in front. 14220 if (const RecordType *RT = T->getAs<RecordType>()) { 14221 RecordDecl *RD = RT->getDecl(); 14222 14223 SmallString<16> InsertionText(" "); 14224 InsertionText += RD->getKindName(); 14225 14226 Diag(TypeRange.getBegin(), 14227 getLangOpts().CPlusPlus11 ? 14228 diag::warn_cxx98_compat_unelaborated_friend_type : 14229 diag::ext_unelaborated_friend_type) 14230 << (unsigned) RD->getTagKind() 14231 << T 14232 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 14233 InsertionText); 14234 } else { 14235 Diag(FriendLoc, 14236 getLangOpts().CPlusPlus11 ? 14237 diag::warn_cxx98_compat_nonclass_type_friend : 14238 diag::ext_nonclass_type_friend) 14239 << T 14240 << TypeRange; 14241 } 14242 } else if (T->getAs<EnumType>()) { 14243 Diag(FriendLoc, 14244 getLangOpts().CPlusPlus11 ? 14245 diag::warn_cxx98_compat_enum_friend : 14246 diag::ext_enum_friend) 14247 << T 14248 << TypeRange; 14249 } 14250 14251 // C++11 [class.friend]p3: 14252 // A friend declaration that does not declare a function shall have one 14253 // of the following forms: 14254 // friend elaborated-type-specifier ; 14255 // friend simple-type-specifier ; 14256 // friend typename-specifier ; 14257 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 14258 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 14259 } 14260 14261 // If the type specifier in a friend declaration designates a (possibly 14262 // cv-qualified) class type, that class is declared as a friend; otherwise, 14263 // the friend declaration is ignored. 14264 return FriendDecl::Create(Context, CurContext, 14265 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 14266 FriendLoc); 14267 } 14268 14269 /// Handle a friend tag declaration where the scope specifier was 14270 /// templated. 14271 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 14272 unsigned TagSpec, SourceLocation TagLoc, 14273 CXXScopeSpec &SS, IdentifierInfo *Name, 14274 SourceLocation NameLoc, 14275 const ParsedAttributesView &Attr, 14276 MultiTemplateParamsArg TempParamLists) { 14277 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14278 14279 bool IsMemberSpecialization = false; 14280 bool Invalid = false; 14281 14282 if (TemplateParameterList *TemplateParams = 14283 MatchTemplateParametersToScopeSpecifier( 14284 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 14285 IsMemberSpecialization, Invalid)) { 14286 if (TemplateParams->size() > 0) { 14287 // This is a declaration of a class template. 14288 if (Invalid) 14289 return nullptr; 14290 14291 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 14292 NameLoc, Attr, TemplateParams, AS_public, 14293 /*ModulePrivateLoc=*/SourceLocation(), 14294 FriendLoc, TempParamLists.size() - 1, 14295 TempParamLists.data()).get(); 14296 } else { 14297 // The "template<>" header is extraneous. 14298 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14299 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14300 IsMemberSpecialization = true; 14301 } 14302 } 14303 14304 if (Invalid) return nullptr; 14305 14306 bool isAllExplicitSpecializations = true; 14307 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 14308 if (TempParamLists[I]->size()) { 14309 isAllExplicitSpecializations = false; 14310 break; 14311 } 14312 } 14313 14314 // FIXME: don't ignore attributes. 14315 14316 // If it's explicit specializations all the way down, just forget 14317 // about the template header and build an appropriate non-templated 14318 // friend. TODO: for source fidelity, remember the headers. 14319 if (isAllExplicitSpecializations) { 14320 if (SS.isEmpty()) { 14321 bool Owned = false; 14322 bool IsDependent = false; 14323 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 14324 Attr, AS_public, 14325 /*ModulePrivateLoc=*/SourceLocation(), 14326 MultiTemplateParamsArg(), Owned, IsDependent, 14327 /*ScopedEnumKWLoc=*/SourceLocation(), 14328 /*ScopedEnumUsesClassTag=*/false, 14329 /*UnderlyingType=*/TypeResult(), 14330 /*IsTypeSpecifier=*/false, 14331 /*IsTemplateParamOrArg=*/false); 14332 } 14333 14334 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 14335 ElaboratedTypeKeyword Keyword 14336 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14337 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 14338 *Name, NameLoc); 14339 if (T.isNull()) 14340 return nullptr; 14341 14342 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14343 if (isa<DependentNameType>(T)) { 14344 DependentNameTypeLoc TL = 14345 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14346 TL.setElaboratedKeywordLoc(TagLoc); 14347 TL.setQualifierLoc(QualifierLoc); 14348 TL.setNameLoc(NameLoc); 14349 } else { 14350 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 14351 TL.setElaboratedKeywordLoc(TagLoc); 14352 TL.setQualifierLoc(QualifierLoc); 14353 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 14354 } 14355 14356 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14357 TSI, FriendLoc, TempParamLists); 14358 Friend->setAccess(AS_public); 14359 CurContext->addDecl(Friend); 14360 return Friend; 14361 } 14362 14363 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 14364 14365 14366 14367 // Handle the case of a templated-scope friend class. e.g. 14368 // template <class T> class A<T>::B; 14369 // FIXME: we don't support these right now. 14370 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 14371 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 14372 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14373 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 14374 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14375 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14376 TL.setElaboratedKeywordLoc(TagLoc); 14377 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14378 TL.setNameLoc(NameLoc); 14379 14380 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14381 TSI, FriendLoc, TempParamLists); 14382 Friend->setAccess(AS_public); 14383 Friend->setUnsupportedFriend(true); 14384 CurContext->addDecl(Friend); 14385 return Friend; 14386 } 14387 14388 /// Handle a friend type declaration. This works in tandem with 14389 /// ActOnTag. 14390 /// 14391 /// Notes on friend class templates: 14392 /// 14393 /// We generally treat friend class declarations as if they were 14394 /// declaring a class. So, for example, the elaborated type specifier 14395 /// in a friend declaration is required to obey the restrictions of a 14396 /// class-head (i.e. no typedefs in the scope chain), template 14397 /// parameters are required to match up with simple template-ids, &c. 14398 /// However, unlike when declaring a template specialization, it's 14399 /// okay to refer to a template specialization without an empty 14400 /// template parameter declaration, e.g. 14401 /// friend class A<T>::B<unsigned>; 14402 /// We permit this as a special case; if there are any template 14403 /// parameters present at all, require proper matching, i.e. 14404 /// template <> template \<class T> friend class A<int>::B; 14405 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14406 MultiTemplateParamsArg TempParams) { 14407 SourceLocation Loc = DS.getBeginLoc(); 14408 14409 assert(DS.isFriendSpecified()); 14410 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14411 14412 // C++ [class.friend]p3: 14413 // A friend declaration that does not declare a function shall have one of 14414 // the following forms: 14415 // friend elaborated-type-specifier ; 14416 // friend simple-type-specifier ; 14417 // friend typename-specifier ; 14418 // 14419 // Any declaration with a type qualifier does not have that form. (It's 14420 // legal to specify a qualified type as a friend, you just can't write the 14421 // keywords.) 14422 if (DS.getTypeQualifiers()) { 14423 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 14424 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 14425 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 14426 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 14427 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 14428 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 14429 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 14430 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 14431 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 14432 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 14433 } 14434 14435 // Try to convert the decl specifier to a type. This works for 14436 // friend templates because ActOnTag never produces a ClassTemplateDecl 14437 // for a TUK_Friend. 14438 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14439 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14440 QualType T = TSI->getType(); 14441 if (TheDeclarator.isInvalidType()) 14442 return nullptr; 14443 14444 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14445 return nullptr; 14446 14447 // This is definitely an error in C++98. It's probably meant to 14448 // be forbidden in C++0x, too, but the specification is just 14449 // poorly written. 14450 // 14451 // The problem is with declarations like the following: 14452 // template <T> friend A<T>::foo; 14453 // where deciding whether a class C is a friend or not now hinges 14454 // on whether there exists an instantiation of A that causes 14455 // 'foo' to equal C. There are restrictions on class-heads 14456 // (which we declare (by fiat) elaborated friend declarations to 14457 // be) that makes this tractable. 14458 // 14459 // FIXME: handle "template <> friend class A<T>;", which 14460 // is possibly well-formed? Who even knows? 14461 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14462 Diag(Loc, diag::err_tagless_friend_type_template) 14463 << DS.getSourceRange(); 14464 return nullptr; 14465 } 14466 14467 // C++98 [class.friend]p1: A friend of a class is a function 14468 // or class that is not a member of the class . . . 14469 // This is fixed in DR77, which just barely didn't make the C++03 14470 // deadline. It's also a very silly restriction that seriously 14471 // affects inner classes and which nobody else seems to implement; 14472 // thus we never diagnose it, not even in -pedantic. 14473 // 14474 // But note that we could warn about it: it's always useless to 14475 // friend one of your own members (it's not, however, worthless to 14476 // friend a member of an arbitrary specialization of your template). 14477 14478 Decl *D; 14479 if (!TempParams.empty()) 14480 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14481 TempParams, 14482 TSI, 14483 DS.getFriendSpecLoc()); 14484 else 14485 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14486 14487 if (!D) 14488 return nullptr; 14489 14490 D->setAccess(AS_public); 14491 CurContext->addDecl(D); 14492 14493 return D; 14494 } 14495 14496 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14497 MultiTemplateParamsArg TemplateParams) { 14498 const DeclSpec &DS = D.getDeclSpec(); 14499 14500 assert(DS.isFriendSpecified()); 14501 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14502 14503 SourceLocation Loc = D.getIdentifierLoc(); 14504 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14505 14506 // C++ [class.friend]p1 14507 // A friend of a class is a function or class.... 14508 // Note that this sees through typedefs, which is intended. 14509 // It *doesn't* see through dependent types, which is correct 14510 // according to [temp.arg.type]p3: 14511 // If a declaration acquires a function type through a 14512 // type dependent on a template-parameter and this causes 14513 // a declaration that does not use the syntactic form of a 14514 // function declarator to have a function type, the program 14515 // is ill-formed. 14516 if (!TInfo->getType()->isFunctionType()) { 14517 Diag(Loc, diag::err_unexpected_friend); 14518 14519 // It might be worthwhile to try to recover by creating an 14520 // appropriate declaration. 14521 return nullptr; 14522 } 14523 14524 // C++ [namespace.memdef]p3 14525 // - If a friend declaration in a non-local class first declares a 14526 // class or function, the friend class or function is a member 14527 // of the innermost enclosing namespace. 14528 // - The name of the friend is not found by simple name lookup 14529 // until a matching declaration is provided in that namespace 14530 // scope (either before or after the class declaration granting 14531 // friendship). 14532 // - If a friend function is called, its name may be found by the 14533 // name lookup that considers functions from namespaces and 14534 // classes associated with the types of the function arguments. 14535 // - When looking for a prior declaration of a class or a function 14536 // declared as a friend, scopes outside the innermost enclosing 14537 // namespace scope are not considered. 14538 14539 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14540 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14541 assert(NameInfo.getName()); 14542 14543 // Check for unexpanded parameter packs. 14544 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14545 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14546 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14547 return nullptr; 14548 14549 // The context we found the declaration in, or in which we should 14550 // create the declaration. 14551 DeclContext *DC; 14552 Scope *DCScope = S; 14553 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14554 ForExternalRedeclaration); 14555 14556 // There are five cases here. 14557 // - There's no scope specifier and we're in a local class. Only look 14558 // for functions declared in the immediately-enclosing block scope. 14559 // We recover from invalid scope qualifiers as if they just weren't there. 14560 FunctionDecl *FunctionContainingLocalClass = nullptr; 14561 if ((SS.isInvalid() || !SS.isSet()) && 14562 (FunctionContainingLocalClass = 14563 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14564 // C++11 [class.friend]p11: 14565 // If a friend declaration appears in a local class and the name 14566 // specified is an unqualified name, a prior declaration is 14567 // looked up without considering scopes that are outside the 14568 // innermost enclosing non-class scope. For a friend function 14569 // declaration, if there is no prior declaration, the program is 14570 // ill-formed. 14571 14572 // Find the innermost enclosing non-class scope. This is the block 14573 // scope containing the local class definition (or for a nested class, 14574 // the outer local class). 14575 DCScope = S->getFnParent(); 14576 14577 // Look up the function name in the scope. 14578 Previous.clear(LookupLocalFriendName); 14579 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14580 14581 if (!Previous.empty()) { 14582 // All possible previous declarations must have the same context: 14583 // either they were declared at block scope or they are members of 14584 // one of the enclosing local classes. 14585 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14586 } else { 14587 // This is ill-formed, but provide the context that we would have 14588 // declared the function in, if we were permitted to, for error recovery. 14589 DC = FunctionContainingLocalClass; 14590 } 14591 adjustContextForLocalExternDecl(DC); 14592 14593 // C++ [class.friend]p6: 14594 // A function can be defined in a friend declaration of a class if and 14595 // only if the class is a non-local class (9.8), the function name is 14596 // unqualified, and the function has namespace scope. 14597 if (D.isFunctionDefinition()) { 14598 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14599 } 14600 14601 // - There's no scope specifier, in which case we just go to the 14602 // appropriate scope and look for a function or function template 14603 // there as appropriate. 14604 } else if (SS.isInvalid() || !SS.isSet()) { 14605 // C++11 [namespace.memdef]p3: 14606 // If the name in a friend declaration is neither qualified nor 14607 // a template-id and the declaration is a function or an 14608 // elaborated-type-specifier, the lookup to determine whether 14609 // the entity has been previously declared shall not consider 14610 // any scopes outside the innermost enclosing namespace. 14611 bool isTemplateId = 14612 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14613 14614 // Find the appropriate context according to the above. 14615 DC = CurContext; 14616 14617 // Skip class contexts. If someone can cite chapter and verse 14618 // for this behavior, that would be nice --- it's what GCC and 14619 // EDG do, and it seems like a reasonable intent, but the spec 14620 // really only says that checks for unqualified existing 14621 // declarations should stop at the nearest enclosing namespace, 14622 // not that they should only consider the nearest enclosing 14623 // namespace. 14624 while (DC->isRecord()) 14625 DC = DC->getParent(); 14626 14627 DeclContext *LookupDC = DC; 14628 while (LookupDC->isTransparentContext()) 14629 LookupDC = LookupDC->getParent(); 14630 14631 while (true) { 14632 LookupQualifiedName(Previous, LookupDC); 14633 14634 if (!Previous.empty()) { 14635 DC = LookupDC; 14636 break; 14637 } 14638 14639 if (isTemplateId) { 14640 if (isa<TranslationUnitDecl>(LookupDC)) break; 14641 } else { 14642 if (LookupDC->isFileContext()) break; 14643 } 14644 LookupDC = LookupDC->getParent(); 14645 } 14646 14647 DCScope = getScopeForDeclContext(S, DC); 14648 14649 // - There's a non-dependent scope specifier, in which case we 14650 // compute it and do a previous lookup there for a function 14651 // or function template. 14652 } else if (!SS.getScopeRep()->isDependent()) { 14653 DC = computeDeclContext(SS); 14654 if (!DC) return nullptr; 14655 14656 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14657 14658 LookupQualifiedName(Previous, DC); 14659 14660 // C++ [class.friend]p1: A friend of a class is a function or 14661 // class that is not a member of the class . . . 14662 if (DC->Equals(CurContext)) 14663 Diag(DS.getFriendSpecLoc(), 14664 getLangOpts().CPlusPlus11 ? 14665 diag::warn_cxx98_compat_friend_is_member : 14666 diag::err_friend_is_member); 14667 14668 if (D.isFunctionDefinition()) { 14669 // C++ [class.friend]p6: 14670 // A function can be defined in a friend declaration of a class if and 14671 // only if the class is a non-local class (9.8), the function name is 14672 // unqualified, and the function has namespace scope. 14673 // 14674 // FIXME: We should only do this if the scope specifier names the 14675 // innermost enclosing namespace; otherwise the fixit changes the 14676 // meaning of the code. 14677 SemaDiagnosticBuilder DB 14678 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14679 14680 DB << SS.getScopeRep(); 14681 if (DC->isFileContext()) 14682 DB << FixItHint::CreateRemoval(SS.getRange()); 14683 SS.clear(); 14684 } 14685 14686 // - There's a scope specifier that does not match any template 14687 // parameter lists, in which case we use some arbitrary context, 14688 // create a method or method template, and wait for instantiation. 14689 // - There's a scope specifier that does match some template 14690 // parameter lists, which we don't handle right now. 14691 } else { 14692 if (D.isFunctionDefinition()) { 14693 // C++ [class.friend]p6: 14694 // A function can be defined in a friend declaration of a class if and 14695 // only if the class is a non-local class (9.8), the function name is 14696 // unqualified, and the function has namespace scope. 14697 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14698 << SS.getScopeRep(); 14699 } 14700 14701 DC = CurContext; 14702 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14703 } 14704 14705 if (!DC->isRecord()) { 14706 int DiagArg = -1; 14707 switch (D.getName().getKind()) { 14708 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14709 case UnqualifiedIdKind::IK_ConstructorName: 14710 DiagArg = 0; 14711 break; 14712 case UnqualifiedIdKind::IK_DestructorName: 14713 DiagArg = 1; 14714 break; 14715 case UnqualifiedIdKind::IK_ConversionFunctionId: 14716 DiagArg = 2; 14717 break; 14718 case UnqualifiedIdKind::IK_DeductionGuideName: 14719 DiagArg = 3; 14720 break; 14721 case UnqualifiedIdKind::IK_Identifier: 14722 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14723 case UnqualifiedIdKind::IK_LiteralOperatorId: 14724 case UnqualifiedIdKind::IK_OperatorFunctionId: 14725 case UnqualifiedIdKind::IK_TemplateId: 14726 break; 14727 } 14728 // This implies that it has to be an operator or function. 14729 if (DiagArg >= 0) { 14730 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14731 return nullptr; 14732 } 14733 } 14734 14735 // FIXME: This is an egregious hack to cope with cases where the scope stack 14736 // does not contain the declaration context, i.e., in an out-of-line 14737 // definition of a class. 14738 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14739 if (!DCScope) { 14740 FakeDCScope.setEntity(DC); 14741 DCScope = &FakeDCScope; 14742 } 14743 14744 bool AddToScope = true; 14745 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14746 TemplateParams, AddToScope); 14747 if (!ND) return nullptr; 14748 14749 assert(ND->getLexicalDeclContext() == CurContext); 14750 14751 // If we performed typo correction, we might have added a scope specifier 14752 // and changed the decl context. 14753 DC = ND->getDeclContext(); 14754 14755 // Add the function declaration to the appropriate lookup tables, 14756 // adjusting the redeclarations list as necessary. We don't 14757 // want to do this yet if the friending class is dependent. 14758 // 14759 // Also update the scope-based lookup if the target context's 14760 // lookup context is in lexical scope. 14761 if (!CurContext->isDependentContext()) { 14762 DC = DC->getRedeclContext(); 14763 DC->makeDeclVisibleInContext(ND); 14764 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14765 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14766 } 14767 14768 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14769 D.getIdentifierLoc(), ND, 14770 DS.getFriendSpecLoc()); 14771 FrD->setAccess(AS_public); 14772 CurContext->addDecl(FrD); 14773 14774 if (ND->isInvalidDecl()) { 14775 FrD->setInvalidDecl(); 14776 } else { 14777 if (DC->isRecord()) CheckFriendAccess(ND); 14778 14779 FunctionDecl *FD; 14780 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14781 FD = FTD->getTemplatedDecl(); 14782 else 14783 FD = cast<FunctionDecl>(ND); 14784 14785 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14786 // default argument expression, that declaration shall be a definition 14787 // and shall be the only declaration of the function or function 14788 // template in the translation unit. 14789 if (functionDeclHasDefaultArgument(FD)) { 14790 // We can't look at FD->getPreviousDecl() because it may not have been set 14791 // if we're in a dependent context. If the function is known to be a 14792 // redeclaration, we will have narrowed Previous down to the right decl. 14793 if (D.isRedeclaration()) { 14794 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14795 Diag(Previous.getRepresentativeDecl()->getLocation(), 14796 diag::note_previous_declaration); 14797 } else if (!D.isFunctionDefinition()) 14798 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14799 } 14800 14801 // Mark templated-scope function declarations as unsupported. 14802 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14803 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14804 << SS.getScopeRep() << SS.getRange() 14805 << cast<CXXRecordDecl>(CurContext); 14806 FrD->setUnsupportedFriend(true); 14807 } 14808 } 14809 14810 return ND; 14811 } 14812 14813 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14814 AdjustDeclIfTemplate(Dcl); 14815 14816 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14817 if (!Fn) { 14818 Diag(DelLoc, diag::err_deleted_non_function); 14819 return; 14820 } 14821 14822 // Deleted function does not have a body. 14823 Fn->setWillHaveBody(false); 14824 14825 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14826 // Don't consider the implicit declaration we generate for explicit 14827 // specializations. FIXME: Do not generate these implicit declarations. 14828 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14829 Prev->getPreviousDecl()) && 14830 !Prev->isDefined()) { 14831 Diag(DelLoc, diag::err_deleted_decl_not_first); 14832 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14833 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14834 : diag::note_previous_declaration); 14835 } 14836 // If the declaration wasn't the first, we delete the function anyway for 14837 // recovery. 14838 Fn = Fn->getCanonicalDecl(); 14839 } 14840 14841 // dllimport/dllexport cannot be deleted. 14842 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14843 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14844 Fn->setInvalidDecl(); 14845 } 14846 14847 if (Fn->isDeleted()) 14848 return; 14849 14850 // See if we're deleting a function which is already known to override a 14851 // non-deleted virtual function. 14852 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14853 bool IssuedDiagnostic = false; 14854 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14855 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14856 if (!IssuedDiagnostic) { 14857 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14858 IssuedDiagnostic = true; 14859 } 14860 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14861 } 14862 } 14863 // If this function was implicitly deleted because it was defaulted, 14864 // explain why it was deleted. 14865 if (IssuedDiagnostic && MD->isDefaulted()) 14866 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14867 /*Diagnose*/true); 14868 } 14869 14870 // C++11 [basic.start.main]p3: 14871 // A program that defines main as deleted [...] is ill-formed. 14872 if (Fn->isMain()) 14873 Diag(DelLoc, diag::err_deleted_main); 14874 14875 // C++11 [dcl.fct.def.delete]p4: 14876 // A deleted function is implicitly inline. 14877 Fn->setImplicitlyInline(); 14878 Fn->setDeletedAsWritten(); 14879 } 14880 14881 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14882 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14883 14884 if (MD) { 14885 if (MD->getParent()->isDependentType()) { 14886 MD->setDefaulted(); 14887 MD->setExplicitlyDefaulted(); 14888 return; 14889 } 14890 14891 CXXSpecialMember Member = getSpecialMember(MD); 14892 if (Member == CXXInvalid) { 14893 if (!MD->isInvalidDecl()) 14894 Diag(DefaultLoc, diag::err_default_special_members); 14895 return; 14896 } 14897 14898 MD->setDefaulted(); 14899 MD->setExplicitlyDefaulted(); 14900 14901 // Unset that we will have a body for this function. We might not, 14902 // if it turns out to be trivial, and we don't need this marking now 14903 // that we've marked it as defaulted. 14904 MD->setWillHaveBody(false); 14905 14906 // If this definition appears within the record, do the checking when 14907 // the record is complete. 14908 const FunctionDecl *Primary = MD; 14909 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14910 // Ask the template instantiation pattern that actually had the 14911 // '= default' on it. 14912 Primary = Pattern; 14913 14914 // If the method was defaulted on its first declaration, we will have 14915 // already performed the checking in CheckCompletedCXXClass. Such a 14916 // declaration doesn't trigger an implicit definition. 14917 if (Primary->getCanonicalDecl()->isDefaulted()) 14918 return; 14919 14920 CheckExplicitlyDefaultedSpecialMember(MD); 14921 14922 if (!MD->isInvalidDecl()) 14923 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14924 } else { 14925 Diag(DefaultLoc, diag::err_default_special_members); 14926 } 14927 } 14928 14929 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14930 for (Stmt *SubStmt : S->children()) { 14931 if (!SubStmt) 14932 continue; 14933 if (isa<ReturnStmt>(SubStmt)) 14934 Self.Diag(SubStmt->getBeginLoc(), 14935 diag::err_return_in_constructor_handler); 14936 if (!isa<Expr>(SubStmt)) 14937 SearchForReturnInStmt(Self, SubStmt); 14938 } 14939 } 14940 14941 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14942 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14943 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14944 SearchForReturnInStmt(*this, Handler); 14945 } 14946 } 14947 14948 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14949 const CXXMethodDecl *Old) { 14950 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14951 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14952 14953 if (OldFT->hasExtParameterInfos()) { 14954 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14955 // A parameter of the overriding method should be annotated with noescape 14956 // if the corresponding parameter of the overridden method is annotated. 14957 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14958 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14959 Diag(New->getParamDecl(I)->getLocation(), 14960 diag::warn_overriding_method_missing_noescape); 14961 Diag(Old->getParamDecl(I)->getLocation(), 14962 diag::note_overridden_marked_noescape); 14963 } 14964 } 14965 14966 // Virtual overrides must have the same code_seg. 14967 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 14968 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 14969 if ((NewCSA || OldCSA) && 14970 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 14971 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 14972 Diag(Old->getLocation(), diag::note_previous_declaration); 14973 return true; 14974 } 14975 14976 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14977 14978 // If the calling conventions match, everything is fine 14979 if (NewCC == OldCC) 14980 return false; 14981 14982 // If the calling conventions mismatch because the new function is static, 14983 // suppress the calling convention mismatch error; the error about static 14984 // function override (err_static_overrides_virtual from 14985 // Sema::CheckFunctionDeclaration) is more clear. 14986 if (New->getStorageClass() == SC_Static) 14987 return false; 14988 14989 Diag(New->getLocation(), 14990 diag::err_conflicting_overriding_cc_attributes) 14991 << New->getDeclName() << New->getType() << Old->getType(); 14992 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14993 return true; 14994 } 14995 14996 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14997 const CXXMethodDecl *Old) { 14998 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14999 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 15000 15001 if (Context.hasSameType(NewTy, OldTy) || 15002 NewTy->isDependentType() || OldTy->isDependentType()) 15003 return false; 15004 15005 // Check if the return types are covariant 15006 QualType NewClassTy, OldClassTy; 15007 15008 /// Both types must be pointers or references to classes. 15009 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 15010 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 15011 NewClassTy = NewPT->getPointeeType(); 15012 OldClassTy = OldPT->getPointeeType(); 15013 } 15014 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 15015 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 15016 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 15017 NewClassTy = NewRT->getPointeeType(); 15018 OldClassTy = OldRT->getPointeeType(); 15019 } 15020 } 15021 } 15022 15023 // The return types aren't either both pointers or references to a class type. 15024 if (NewClassTy.isNull()) { 15025 Diag(New->getLocation(), 15026 diag::err_different_return_type_for_overriding_virtual_function) 15027 << New->getDeclName() << NewTy << OldTy 15028 << New->getReturnTypeSourceRange(); 15029 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15030 << Old->getReturnTypeSourceRange(); 15031 15032 return true; 15033 } 15034 15035 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 15036 // C++14 [class.virtual]p8: 15037 // If the class type in the covariant return type of D::f differs from 15038 // that of B::f, the class type in the return type of D::f shall be 15039 // complete at the point of declaration of D::f or shall be the class 15040 // type D. 15041 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 15042 if (!RT->isBeingDefined() && 15043 RequireCompleteType(New->getLocation(), NewClassTy, 15044 diag::err_covariant_return_incomplete, 15045 New->getDeclName())) 15046 return true; 15047 } 15048 15049 // Check if the new class derives from the old class. 15050 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 15051 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 15052 << New->getDeclName() << NewTy << OldTy 15053 << New->getReturnTypeSourceRange(); 15054 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15055 << Old->getReturnTypeSourceRange(); 15056 return true; 15057 } 15058 15059 // Check if we the conversion from derived to base is valid. 15060 if (CheckDerivedToBaseConversion( 15061 NewClassTy, OldClassTy, 15062 diag::err_covariant_return_inaccessible_base, 15063 diag::err_covariant_return_ambiguous_derived_to_base_conv, 15064 New->getLocation(), New->getReturnTypeSourceRange(), 15065 New->getDeclName(), nullptr)) { 15066 // FIXME: this note won't trigger for delayed access control 15067 // diagnostics, and it's impossible to get an undelayed error 15068 // here from access control during the original parse because 15069 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 15070 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15071 << Old->getReturnTypeSourceRange(); 15072 return true; 15073 } 15074 } 15075 15076 // The qualifiers of the return types must be the same. 15077 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 15078 Diag(New->getLocation(), 15079 diag::err_covariant_return_type_different_qualifications) 15080 << New->getDeclName() << NewTy << OldTy 15081 << New->getReturnTypeSourceRange(); 15082 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15083 << Old->getReturnTypeSourceRange(); 15084 return true; 15085 } 15086 15087 15088 // The new class type must have the same or less qualifiers as the old type. 15089 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 15090 Diag(New->getLocation(), 15091 diag::err_covariant_return_type_class_type_more_qualified) 15092 << New->getDeclName() << NewTy << OldTy 15093 << New->getReturnTypeSourceRange(); 15094 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15095 << Old->getReturnTypeSourceRange(); 15096 return true; 15097 } 15098 15099 return false; 15100 } 15101 15102 /// Mark the given method pure. 15103 /// 15104 /// \param Method the method to be marked pure. 15105 /// 15106 /// \param InitRange the source range that covers the "0" initializer. 15107 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 15108 SourceLocation EndLoc = InitRange.getEnd(); 15109 if (EndLoc.isValid()) 15110 Method->setRangeEnd(EndLoc); 15111 15112 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 15113 Method->setPure(); 15114 return false; 15115 } 15116 15117 if (!Method->isInvalidDecl()) 15118 Diag(Method->getLocation(), diag::err_non_virtual_pure) 15119 << Method->getDeclName() << InitRange; 15120 return true; 15121 } 15122 15123 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 15124 if (D->getFriendObjectKind()) 15125 Diag(D->getLocation(), diag::err_pure_friend); 15126 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 15127 CheckPureMethod(M, ZeroLoc); 15128 else 15129 Diag(D->getLocation(), diag::err_illegal_initializer); 15130 } 15131 15132 /// Determine whether the given declaration is a global variable or 15133 /// static data member. 15134 static bool isNonlocalVariable(const Decl *D) { 15135 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 15136 return Var->hasGlobalStorage(); 15137 15138 return false; 15139 } 15140 15141 /// Invoked when we are about to parse an initializer for the declaration 15142 /// 'Dcl'. 15143 /// 15144 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 15145 /// static data member of class X, names should be looked up in the scope of 15146 /// class X. If the declaration had a scope specifier, a scope will have 15147 /// been created and passed in for this purpose. Otherwise, S will be null. 15148 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 15149 // If there is no declaration, there was an error parsing it. 15150 if (!D || D->isInvalidDecl()) 15151 return; 15152 15153 // We will always have a nested name specifier here, but this declaration 15154 // might not be out of line if the specifier names the current namespace: 15155 // extern int n; 15156 // int ::n = 0; 15157 if (S && D->isOutOfLine()) 15158 EnterDeclaratorContext(S, D->getDeclContext()); 15159 15160 // If we are parsing the initializer for a static data member, push a 15161 // new expression evaluation context that is associated with this static 15162 // data member. 15163 if (isNonlocalVariable(D)) 15164 PushExpressionEvaluationContext( 15165 ExpressionEvaluationContext::PotentiallyEvaluated, D); 15166 } 15167 15168 /// Invoked after we are finished parsing an initializer for the declaration D. 15169 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 15170 // If there is no declaration, there was an error parsing it. 15171 if (!D || D->isInvalidDecl()) 15172 return; 15173 15174 if (isNonlocalVariable(D)) 15175 PopExpressionEvaluationContext(); 15176 15177 if (S && D->isOutOfLine()) 15178 ExitDeclaratorContext(S); 15179 } 15180 15181 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 15182 /// C++ if/switch/while/for statement. 15183 /// e.g: "if (int x = f()) {...}" 15184 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 15185 // C++ 6.4p2: 15186 // The declarator shall not specify a function or an array. 15187 // The type-specifier-seq shall not contain typedef and shall not declare a 15188 // new class or enumeration. 15189 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 15190 "Parser allowed 'typedef' as storage class of condition decl."); 15191 15192 Decl *Dcl = ActOnDeclarator(S, D); 15193 if (!Dcl) 15194 return true; 15195 15196 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 15197 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 15198 << D.getSourceRange(); 15199 return true; 15200 } 15201 15202 return Dcl; 15203 } 15204 15205 void Sema::LoadExternalVTableUses() { 15206 if (!ExternalSource) 15207 return; 15208 15209 SmallVector<ExternalVTableUse, 4> VTables; 15210 ExternalSource->ReadUsedVTables(VTables); 15211 SmallVector<VTableUse, 4> NewUses; 15212 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 15213 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 15214 = VTablesUsed.find(VTables[I].Record); 15215 // Even if a definition wasn't required before, it may be required now. 15216 if (Pos != VTablesUsed.end()) { 15217 if (!Pos->second && VTables[I].DefinitionRequired) 15218 Pos->second = true; 15219 continue; 15220 } 15221 15222 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 15223 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 15224 } 15225 15226 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 15227 } 15228 15229 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 15230 bool DefinitionRequired) { 15231 // Ignore any vtable uses in unevaluated operands or for classes that do 15232 // not have a vtable. 15233 if (!Class->isDynamicClass() || Class->isDependentContext() || 15234 CurContext->isDependentContext() || isUnevaluatedContext()) 15235 return; 15236 // Do not mark as used if compiling for the device outside of the target 15237 // region. 15238 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 15239 !isInOpenMPDeclareTargetContext() && 15240 !isInOpenMPTargetExecutionDirective()) { 15241 if (!DefinitionRequired) 15242 MarkVirtualMembersReferenced(Loc, Class); 15243 return; 15244 } 15245 15246 // Try to insert this class into the map. 15247 LoadExternalVTableUses(); 15248 Class = Class->getCanonicalDecl(); 15249 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 15250 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 15251 if (!Pos.second) { 15252 // If we already had an entry, check to see if we are promoting this vtable 15253 // to require a definition. If so, we need to reappend to the VTableUses 15254 // list, since we may have already processed the first entry. 15255 if (DefinitionRequired && !Pos.first->second) { 15256 Pos.first->second = true; 15257 } else { 15258 // Otherwise, we can early exit. 15259 return; 15260 } 15261 } else { 15262 // The Microsoft ABI requires that we perform the destructor body 15263 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 15264 // the deleting destructor is emitted with the vtable, not with the 15265 // destructor definition as in the Itanium ABI. 15266 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15267 CXXDestructorDecl *DD = Class->getDestructor(); 15268 if (DD && DD->isVirtual() && !DD->isDeleted()) { 15269 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 15270 // If this is an out-of-line declaration, marking it referenced will 15271 // not do anything. Manually call CheckDestructor to look up operator 15272 // delete(). 15273 ContextRAII SavedContext(*this, DD); 15274 CheckDestructor(DD); 15275 } else { 15276 MarkFunctionReferenced(Loc, Class->getDestructor()); 15277 } 15278 } 15279 } 15280 } 15281 15282 // Local classes need to have their virtual members marked 15283 // immediately. For all other classes, we mark their virtual members 15284 // at the end of the translation unit. 15285 if (Class->isLocalClass()) 15286 MarkVirtualMembersReferenced(Loc, Class); 15287 else 15288 VTableUses.push_back(std::make_pair(Class, Loc)); 15289 } 15290 15291 bool Sema::DefineUsedVTables() { 15292 LoadExternalVTableUses(); 15293 if (VTableUses.empty()) 15294 return false; 15295 15296 // Note: The VTableUses vector could grow as a result of marking 15297 // the members of a class as "used", so we check the size each 15298 // time through the loop and prefer indices (which are stable) to 15299 // iterators (which are not). 15300 bool DefinedAnything = false; 15301 for (unsigned I = 0; I != VTableUses.size(); ++I) { 15302 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 15303 if (!Class) 15304 continue; 15305 TemplateSpecializationKind ClassTSK = 15306 Class->getTemplateSpecializationKind(); 15307 15308 SourceLocation Loc = VTableUses[I].second; 15309 15310 bool DefineVTable = true; 15311 15312 // If this class has a key function, but that key function is 15313 // defined in another translation unit, we don't need to emit the 15314 // vtable even though we're using it. 15315 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 15316 if (KeyFunction && !KeyFunction->hasBody()) { 15317 // The key function is in another translation unit. 15318 DefineVTable = false; 15319 TemplateSpecializationKind TSK = 15320 KeyFunction->getTemplateSpecializationKind(); 15321 assert(TSK != TSK_ExplicitInstantiationDefinition && 15322 TSK != TSK_ImplicitInstantiation && 15323 "Instantiations don't have key functions"); 15324 (void)TSK; 15325 } else if (!KeyFunction) { 15326 // If we have a class with no key function that is the subject 15327 // of an explicit instantiation declaration, suppress the 15328 // vtable; it will live with the explicit instantiation 15329 // definition. 15330 bool IsExplicitInstantiationDeclaration = 15331 ClassTSK == TSK_ExplicitInstantiationDeclaration; 15332 for (auto R : Class->redecls()) { 15333 TemplateSpecializationKind TSK 15334 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 15335 if (TSK == TSK_ExplicitInstantiationDeclaration) 15336 IsExplicitInstantiationDeclaration = true; 15337 else if (TSK == TSK_ExplicitInstantiationDefinition) { 15338 IsExplicitInstantiationDeclaration = false; 15339 break; 15340 } 15341 } 15342 15343 if (IsExplicitInstantiationDeclaration) 15344 DefineVTable = false; 15345 } 15346 15347 // The exception specifications for all virtual members may be needed even 15348 // if we are not providing an authoritative form of the vtable in this TU. 15349 // We may choose to emit it available_externally anyway. 15350 if (!DefineVTable) { 15351 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 15352 continue; 15353 } 15354 15355 // Mark all of the virtual members of this class as referenced, so 15356 // that we can build a vtable. Then, tell the AST consumer that a 15357 // vtable for this class is required. 15358 DefinedAnything = true; 15359 MarkVirtualMembersReferenced(Loc, Class); 15360 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 15361 if (VTablesUsed[Canonical]) 15362 Consumer.HandleVTable(Class); 15363 15364 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 15365 // no key function or the key function is inlined. Don't warn in C++ ABIs 15366 // that lack key functions, since the user won't be able to make one. 15367 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 15368 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 15369 const FunctionDecl *KeyFunctionDef = nullptr; 15370 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 15371 KeyFunctionDef->isInlined())) { 15372 Diag(Class->getLocation(), 15373 ClassTSK == TSK_ExplicitInstantiationDefinition 15374 ? diag::warn_weak_template_vtable 15375 : diag::warn_weak_vtable) 15376 << Class; 15377 } 15378 } 15379 } 15380 VTableUses.clear(); 15381 15382 return DefinedAnything; 15383 } 15384 15385 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 15386 const CXXRecordDecl *RD) { 15387 for (const auto *I : RD->methods()) 15388 if (I->isVirtual() && !I->isPure()) 15389 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 15390 } 15391 15392 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 15393 const CXXRecordDecl *RD, 15394 bool ConstexprOnly) { 15395 // Mark all functions which will appear in RD's vtable as used. 15396 CXXFinalOverriderMap FinalOverriders; 15397 RD->getFinalOverriders(FinalOverriders); 15398 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 15399 E = FinalOverriders.end(); 15400 I != E; ++I) { 15401 for (OverridingMethods::const_iterator OI = I->second.begin(), 15402 OE = I->second.end(); 15403 OI != OE; ++OI) { 15404 assert(OI->second.size() > 0 && "no final overrider"); 15405 CXXMethodDecl *Overrider = OI->second.front().Method; 15406 15407 // C++ [basic.def.odr]p2: 15408 // [...] A virtual member function is used if it is not pure. [...] 15409 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 15410 MarkFunctionReferenced(Loc, Overrider); 15411 } 15412 } 15413 15414 // Only classes that have virtual bases need a VTT. 15415 if (RD->getNumVBases() == 0) 15416 return; 15417 15418 for (const auto &I : RD->bases()) { 15419 const CXXRecordDecl *Base = 15420 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15421 if (Base->getNumVBases() == 0) 15422 continue; 15423 MarkVirtualMembersReferenced(Loc, Base); 15424 } 15425 } 15426 15427 /// SetIvarInitializers - This routine builds initialization ASTs for the 15428 /// Objective-C implementation whose ivars need be initialized. 15429 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15430 if (!getLangOpts().CPlusPlus) 15431 return; 15432 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15433 SmallVector<ObjCIvarDecl*, 8> ivars; 15434 CollectIvarsToConstructOrDestruct(OID, ivars); 15435 if (ivars.empty()) 15436 return; 15437 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15438 for (unsigned i = 0; i < ivars.size(); i++) { 15439 FieldDecl *Field = ivars[i]; 15440 if (Field->isInvalidDecl()) 15441 continue; 15442 15443 CXXCtorInitializer *Member; 15444 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15445 InitializationKind InitKind = 15446 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15447 15448 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15449 ExprResult MemberInit = 15450 InitSeq.Perform(*this, InitEntity, InitKind, None); 15451 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15452 // Note, MemberInit could actually come back empty if no initialization 15453 // is required (e.g., because it would call a trivial default constructor) 15454 if (!MemberInit.get() || MemberInit.isInvalid()) 15455 continue; 15456 15457 Member = 15458 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15459 SourceLocation(), 15460 MemberInit.getAs<Expr>(), 15461 SourceLocation()); 15462 AllToInit.push_back(Member); 15463 15464 // Be sure that the destructor is accessible and is marked as referenced. 15465 if (const RecordType *RecordTy = 15466 Context.getBaseElementType(Field->getType()) 15467 ->getAs<RecordType>()) { 15468 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15469 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15470 MarkFunctionReferenced(Field->getLocation(), Destructor); 15471 CheckDestructorAccess(Field->getLocation(), Destructor, 15472 PDiag(diag::err_access_dtor_ivar) 15473 << Context.getBaseElementType(Field->getType())); 15474 } 15475 } 15476 } 15477 ObjCImplementation->setIvarInitializers(Context, 15478 AllToInit.data(), AllToInit.size()); 15479 } 15480 } 15481 15482 static 15483 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15484 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15485 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15486 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15487 Sema &S) { 15488 if (Ctor->isInvalidDecl()) 15489 return; 15490 15491 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15492 15493 // Target may not be determinable yet, for instance if this is a dependent 15494 // call in an uninstantiated template. 15495 if (Target) { 15496 const FunctionDecl *FNTarget = nullptr; 15497 (void)Target->hasBody(FNTarget); 15498 Target = const_cast<CXXConstructorDecl*>( 15499 cast_or_null<CXXConstructorDecl>(FNTarget)); 15500 } 15501 15502 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15503 // Avoid dereferencing a null pointer here. 15504 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15505 15506 if (!Current.insert(Canonical).second) 15507 return; 15508 15509 // We know that beyond here, we aren't chaining into a cycle. 15510 if (!Target || !Target->isDelegatingConstructor() || 15511 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15512 Valid.insert(Current.begin(), Current.end()); 15513 Current.clear(); 15514 // We've hit a cycle. 15515 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15516 Current.count(TCanonical)) { 15517 // If we haven't diagnosed this cycle yet, do so now. 15518 if (!Invalid.count(TCanonical)) { 15519 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15520 diag::warn_delegating_ctor_cycle) 15521 << Ctor; 15522 15523 // Don't add a note for a function delegating directly to itself. 15524 if (TCanonical != Canonical) 15525 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15526 15527 CXXConstructorDecl *C = Target; 15528 while (C->getCanonicalDecl() != Canonical) { 15529 const FunctionDecl *FNTarget = nullptr; 15530 (void)C->getTargetConstructor()->hasBody(FNTarget); 15531 assert(FNTarget && "Ctor cycle through bodiless function"); 15532 15533 C = const_cast<CXXConstructorDecl*>( 15534 cast<CXXConstructorDecl>(FNTarget)); 15535 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15536 } 15537 } 15538 15539 Invalid.insert(Current.begin(), Current.end()); 15540 Current.clear(); 15541 } else { 15542 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15543 } 15544 } 15545 15546 15547 void Sema::CheckDelegatingCtorCycles() { 15548 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15549 15550 for (DelegatingCtorDeclsType::iterator 15551 I = DelegatingCtorDecls.begin(ExternalSource), 15552 E = DelegatingCtorDecls.end(); 15553 I != E; ++I) 15554 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15555 15556 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15557 (*CI)->setInvalidDecl(); 15558 } 15559 15560 namespace { 15561 /// AST visitor that finds references to the 'this' expression. 15562 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15563 Sema &S; 15564 15565 public: 15566 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15567 15568 bool VisitCXXThisExpr(CXXThisExpr *E) { 15569 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15570 << E->isImplicit(); 15571 return false; 15572 } 15573 }; 15574 } 15575 15576 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15577 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15578 if (!TSInfo) 15579 return false; 15580 15581 TypeLoc TL = TSInfo->getTypeLoc(); 15582 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15583 if (!ProtoTL) 15584 return false; 15585 15586 // C++11 [expr.prim.general]p3: 15587 // [The expression this] shall not appear before the optional 15588 // cv-qualifier-seq and it shall not appear within the declaration of a 15589 // static member function (although its type and value category are defined 15590 // within a static member function as they are within a non-static member 15591 // function). [ Note: this is because declaration matching does not occur 15592 // until the complete declarator is known. - end note ] 15593 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15594 FindCXXThisExpr Finder(*this); 15595 15596 // If the return type came after the cv-qualifier-seq, check it now. 15597 if (Proto->hasTrailingReturn() && 15598 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15599 return true; 15600 15601 // Check the exception specification. 15602 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15603 return true; 15604 15605 return checkThisInStaticMemberFunctionAttributes(Method); 15606 } 15607 15608 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15609 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15610 if (!TSInfo) 15611 return false; 15612 15613 TypeLoc TL = TSInfo->getTypeLoc(); 15614 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15615 if (!ProtoTL) 15616 return false; 15617 15618 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15619 FindCXXThisExpr Finder(*this); 15620 15621 switch (Proto->getExceptionSpecType()) { 15622 case EST_Unparsed: 15623 case EST_Uninstantiated: 15624 case EST_Unevaluated: 15625 case EST_BasicNoexcept: 15626 case EST_NoThrow: 15627 case EST_DynamicNone: 15628 case EST_MSAny: 15629 case EST_None: 15630 break; 15631 15632 case EST_DependentNoexcept: 15633 case EST_NoexceptFalse: 15634 case EST_NoexceptTrue: 15635 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15636 return true; 15637 LLVM_FALLTHROUGH; 15638 15639 case EST_Dynamic: 15640 for (const auto &E : Proto->exceptions()) { 15641 if (!Finder.TraverseType(E)) 15642 return true; 15643 } 15644 break; 15645 } 15646 15647 return false; 15648 } 15649 15650 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15651 FindCXXThisExpr Finder(*this); 15652 15653 // Check attributes. 15654 for (const auto *A : Method->attrs()) { 15655 // FIXME: This should be emitted by tblgen. 15656 Expr *Arg = nullptr; 15657 ArrayRef<Expr *> Args; 15658 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15659 Arg = G->getArg(); 15660 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15661 Arg = G->getArg(); 15662 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15663 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15664 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15665 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15666 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15667 Arg = ETLF->getSuccessValue(); 15668 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15669 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15670 Arg = STLF->getSuccessValue(); 15671 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15672 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15673 Arg = LR->getArg(); 15674 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15675 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15676 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15677 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15678 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15679 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15680 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15681 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15682 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15683 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15684 15685 if (Arg && !Finder.TraverseStmt(Arg)) 15686 return true; 15687 15688 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15689 if (!Finder.TraverseStmt(Args[I])) 15690 return true; 15691 } 15692 } 15693 15694 return false; 15695 } 15696 15697 void Sema::checkExceptionSpecification( 15698 bool IsTopLevel, ExceptionSpecificationType EST, 15699 ArrayRef<ParsedType> DynamicExceptions, 15700 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15701 SmallVectorImpl<QualType> &Exceptions, 15702 FunctionProtoType::ExceptionSpecInfo &ESI) { 15703 Exceptions.clear(); 15704 ESI.Type = EST; 15705 if (EST == EST_Dynamic) { 15706 Exceptions.reserve(DynamicExceptions.size()); 15707 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15708 // FIXME: Preserve type source info. 15709 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15710 15711 if (IsTopLevel) { 15712 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15713 collectUnexpandedParameterPacks(ET, Unexpanded); 15714 if (!Unexpanded.empty()) { 15715 DiagnoseUnexpandedParameterPacks( 15716 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15717 Unexpanded); 15718 continue; 15719 } 15720 } 15721 15722 // Check that the type is valid for an exception spec, and 15723 // drop it if not. 15724 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15725 Exceptions.push_back(ET); 15726 } 15727 ESI.Exceptions = Exceptions; 15728 return; 15729 } 15730 15731 if (isComputedNoexcept(EST)) { 15732 assert((NoexceptExpr->isTypeDependent() || 15733 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15734 Context.BoolTy) && 15735 "Parser should have made sure that the expression is boolean"); 15736 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15737 ESI.Type = EST_BasicNoexcept; 15738 return; 15739 } 15740 15741 ESI.NoexceptExpr = NoexceptExpr; 15742 return; 15743 } 15744 } 15745 15746 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15747 ExceptionSpecificationType EST, 15748 SourceRange SpecificationRange, 15749 ArrayRef<ParsedType> DynamicExceptions, 15750 ArrayRef<SourceRange> DynamicExceptionRanges, 15751 Expr *NoexceptExpr) { 15752 if (!MethodD) 15753 return; 15754 15755 // Dig out the method we're referring to. 15756 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15757 MethodD = FunTmpl->getTemplatedDecl(); 15758 15759 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15760 if (!Method) 15761 return; 15762 15763 // Check the exception specification. 15764 llvm::SmallVector<QualType, 4> Exceptions; 15765 FunctionProtoType::ExceptionSpecInfo ESI; 15766 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15767 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15768 ESI); 15769 15770 // Update the exception specification on the function type. 15771 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15772 15773 if (Method->isStatic()) 15774 checkThisInStaticMemberFunctionExceptionSpec(Method); 15775 15776 if (Method->isVirtual()) { 15777 // Check overrides, which we previously had to delay. 15778 for (const CXXMethodDecl *O : Method->overridden_methods()) 15779 CheckOverridingFunctionExceptionSpec(Method, O); 15780 } 15781 } 15782 15783 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15784 /// 15785 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15786 SourceLocation DeclStart, Declarator &D, 15787 Expr *BitWidth, 15788 InClassInitStyle InitStyle, 15789 AccessSpecifier AS, 15790 const ParsedAttr &MSPropertyAttr) { 15791 IdentifierInfo *II = D.getIdentifier(); 15792 if (!II) { 15793 Diag(DeclStart, diag::err_anonymous_property); 15794 return nullptr; 15795 } 15796 SourceLocation Loc = D.getIdentifierLoc(); 15797 15798 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15799 QualType T = TInfo->getType(); 15800 if (getLangOpts().CPlusPlus) { 15801 CheckExtraCXXDefaultArguments(D); 15802 15803 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15804 UPPC_DataMemberType)) { 15805 D.setInvalidType(); 15806 T = Context.IntTy; 15807 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15808 } 15809 } 15810 15811 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15812 15813 if (D.getDeclSpec().isInlineSpecified()) 15814 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15815 << getLangOpts().CPlusPlus17; 15816 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15817 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15818 diag::err_invalid_thread) 15819 << DeclSpec::getSpecifierName(TSCS); 15820 15821 // Check to see if this name was declared as a member previously 15822 NamedDecl *PrevDecl = nullptr; 15823 LookupResult Previous(*this, II, Loc, LookupMemberName, 15824 ForVisibleRedeclaration); 15825 LookupName(Previous, S); 15826 switch (Previous.getResultKind()) { 15827 case LookupResult::Found: 15828 case LookupResult::FoundUnresolvedValue: 15829 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15830 break; 15831 15832 case LookupResult::FoundOverloaded: 15833 PrevDecl = Previous.getRepresentativeDecl(); 15834 break; 15835 15836 case LookupResult::NotFound: 15837 case LookupResult::NotFoundInCurrentInstantiation: 15838 case LookupResult::Ambiguous: 15839 break; 15840 } 15841 15842 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15843 // Maybe we will complain about the shadowed template parameter. 15844 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15845 // Just pretend that we didn't see the previous declaration. 15846 PrevDecl = nullptr; 15847 } 15848 15849 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15850 PrevDecl = nullptr; 15851 15852 SourceLocation TSSL = D.getBeginLoc(); 15853 MSPropertyDecl *NewPD = 15854 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 15855 MSPropertyAttr.getPropertyDataGetter(), 15856 MSPropertyAttr.getPropertyDataSetter()); 15857 ProcessDeclAttributes(TUScope, NewPD, D); 15858 NewPD->setAccess(AS); 15859 15860 if (NewPD->isInvalidDecl()) 15861 Record->setInvalidDecl(); 15862 15863 if (D.getDeclSpec().isModulePrivateSpecified()) 15864 NewPD->setModulePrivate(); 15865 15866 if (NewPD->isInvalidDecl() && PrevDecl) { 15867 // Don't introduce NewFD into scope; there's already something 15868 // with the same name in the same scope. 15869 } else if (II) { 15870 PushOnScopeChains(NewPD, S); 15871 } else 15872 Record->addDecl(NewPD); 15873 15874 return NewPD; 15875 } 15876