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 return; 196 // If we're still at noexcept(true) and there's a throw() callee, 197 // change to that specification. 198 case EST_DynamicNone: 199 if (ComputedEST == EST_BasicNoexcept) 200 ComputedEST = EST_DynamicNone; 201 return; 202 case EST_DependentNoexcept: 203 llvm_unreachable( 204 "should not generate implicit declarations for dependent cases"); 205 case EST_Dynamic: 206 break; 207 } 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (const auto &E : Proto->exceptions()) 214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 215 Exceptions.push_back(E); 216 } 217 218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 219 if (!E || ComputedEST == EST_MSAny) 220 return; 221 222 // FIXME: 223 // 224 // C++0x [except.spec]p14: 225 // [An] implicit exception-specification specifies the type-id T if and 226 // only if T is allowed by the exception-specification of a function directly 227 // invoked by f's implicit definition; f shall allow all exceptions if any 228 // function it directly invokes allows all exceptions, and f shall allow no 229 // exceptions if every function it directly invokes allows no exceptions. 230 // 231 // Note in particular that if an implicit exception-specification is generated 232 // for a function containing a throw-expression, that specification can still 233 // be noexcept(true). 234 // 235 // Note also that 'directly invoked' is not defined in the standard, and there 236 // is no indication that we should only consider potentially-evaluated calls. 237 // 238 // Ultimately we should implement the intent of the standard: the exception 239 // specification should be the set of exceptions which can be thrown by the 240 // implicit definition. For now, we assume that any non-nothrow expression can 241 // throw any exception. 242 243 if (Self->canThrow(E)) 244 ComputedEST = EST_None; 245 } 246 247 bool 248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 249 SourceLocation EqualLoc) { 250 if (RequireCompleteType(Param->getLocation(), Param->getType(), 251 diag::err_typecheck_decl_incomplete_type)) { 252 Param->setInvalidDecl(); 253 return true; 254 } 255 256 // C++ [dcl.fct.default]p5 257 // A default argument expression is implicitly converted (clause 258 // 4) to the parameter type. The default argument expression has 259 // the same semantic constraints as the initializer expression in 260 // a declaration of a variable of the parameter type, using the 261 // copy-initialization semantics (8.5). 262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 263 Param); 264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 265 EqualLoc); 266 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 268 if (Result.isInvalid()) 269 return true; 270 Arg = Result.getAs<Expr>(); 271 272 CheckCompletedExpr(Arg, EqualLoc); 273 Arg = MaybeCreateExprWithCleanups(Arg); 274 275 // Okay: add the default argument to the parameter 276 Param->setDefaultArg(Arg); 277 278 // We have already instantiated this parameter; provide each of the 279 // instantiations with the uninstantiated default argument. 280 UnparsedDefaultArgInstantiationsMap::iterator InstPos 281 = UnparsedDefaultArgInstantiations.find(Param); 282 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 285 286 // We're done tracking this parameter's instantiations. 287 UnparsedDefaultArgInstantiations.erase(InstPos); 288 } 289 290 return false; 291 } 292 293 /// ActOnParamDefaultArgument - Check whether the default argument 294 /// provided for a function parameter is well-formed. If so, attach it 295 /// to the parameter declaration. 296 void 297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 298 Expr *DefaultArg) { 299 if (!param || !DefaultArg) 300 return; 301 302 ParmVarDecl *Param = cast<ParmVarDecl>(param); 303 UnparsedDefaultArgLocs.erase(Param); 304 305 // Default arguments are only permitted in C++ 306 if (!getLangOpts().CPlusPlus) { 307 Diag(EqualLoc, diag::err_param_default_argument) 308 << DefaultArg->getSourceRange(); 309 Param->setInvalidDecl(); 310 return; 311 } 312 313 // Check for unexpanded parameter packs. 314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 315 Param->setInvalidDecl(); 316 return; 317 } 318 319 // C++11 [dcl.fct.default]p3 320 // A default argument expression [...] shall not be specified for a 321 // parameter pack. 322 if (Param->isParameterPack()) { 323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 324 << DefaultArg->getSourceRange(); 325 return; 326 } 327 328 // Check that the default argument is well-formed 329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 330 if (DefaultArgChecker.Visit(DefaultArg)) { 331 Param->setInvalidDecl(); 332 return; 333 } 334 335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 336 } 337 338 /// ActOnParamUnparsedDefaultArgument - We've seen a default 339 /// argument for a function parameter, but we can't parse it yet 340 /// because we're inside a class definition. Note that this default 341 /// argument will be parsed later. 342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 343 SourceLocation EqualLoc, 344 SourceLocation ArgLoc) { 345 if (!param) 346 return; 347 348 ParmVarDecl *Param = cast<ParmVarDecl>(param); 349 Param->setUnparsedDefaultArg(); 350 UnparsedDefaultArgLocs[Param] = ArgLoc; 351 } 352 353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 354 /// the default argument for the parameter param failed. 355 void Sema::ActOnParamDefaultArgumentError(Decl *param, 356 SourceLocation EqualLoc) { 357 if (!param) 358 return; 359 360 ParmVarDecl *Param = cast<ParmVarDecl>(param); 361 Param->setInvalidDecl(); 362 UnparsedDefaultArgLocs.erase(Param); 363 Param->setDefaultArg(new(Context) 364 OpaqueValueExpr(EqualLoc, 365 Param->getType().getNonReferenceType(), 366 VK_RValue)); 367 } 368 369 /// CheckExtraCXXDefaultArguments - Check for any extra default 370 /// arguments in the declarator, which is not a function declaration 371 /// or definition and therefore is not permitted to have default 372 /// arguments. This routine should be invoked for every declarator 373 /// that is not a function declaration or definition. 374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 375 // C++ [dcl.fct.default]p3 376 // A default argument expression shall be specified only in the 377 // parameter-declaration-clause of a function declaration or in a 378 // template-parameter (14.1). It shall not be specified for a 379 // parameter pack. If it is specified in a 380 // parameter-declaration-clause, it shall not occur within a 381 // declarator or abstract-declarator of a parameter-declaration. 382 bool MightBeFunction = D.isFunctionDeclarationContext(); 383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 384 DeclaratorChunk &chunk = D.getTypeObject(i); 385 if (chunk.Kind == DeclaratorChunk::Function) { 386 if (MightBeFunction) { 387 // This is a function declaration. It can have default arguments, but 388 // keep looking in case its return type is a function type with default 389 // arguments. 390 MightBeFunction = false; 391 continue; 392 } 393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 394 ++argIdx) { 395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 396 if (Param->hasUnparsedDefaultArg()) { 397 std::unique_ptr<CachedTokens> Toks = 398 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 399 SourceRange SR; 400 if (Toks->size() > 1) 401 SR = SourceRange((*Toks)[1].getLocation(), 402 Toks->back().getLocation()); 403 else 404 SR = UnparsedDefaultArgLocs[Param]; 405 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 406 << SR; 407 } else if (Param->getDefaultArg()) { 408 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 409 << Param->getDefaultArg()->getSourceRange(); 410 Param->setDefaultArg(nullptr); 411 } 412 } 413 } else if (chunk.Kind != DeclaratorChunk::Paren) { 414 MightBeFunction = false; 415 } 416 } 417 } 418 419 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 420 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 421 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 422 if (!PVD->hasDefaultArg()) 423 return false; 424 if (!PVD->hasInheritedDefaultArg()) 425 return true; 426 } 427 return false; 428 } 429 430 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 431 /// function, once we already know that they have the same 432 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 433 /// error, false otherwise. 434 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 435 Scope *S) { 436 bool Invalid = false; 437 438 // The declaration context corresponding to the scope is the semantic 439 // parent, unless this is a local function declaration, in which case 440 // it is that surrounding function. 441 DeclContext *ScopeDC = New->isLocalExternDecl() 442 ? New->getLexicalDeclContext() 443 : New->getDeclContext(); 444 445 // Find the previous declaration for the purpose of default arguments. 446 FunctionDecl *PrevForDefaultArgs = Old; 447 for (/**/; PrevForDefaultArgs; 448 // Don't bother looking back past the latest decl if this is a local 449 // extern declaration; nothing else could work. 450 PrevForDefaultArgs = New->isLocalExternDecl() 451 ? nullptr 452 : PrevForDefaultArgs->getPreviousDecl()) { 453 // Ignore hidden declarations. 454 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 455 continue; 456 457 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 458 !New->isCXXClassMember()) { 459 // Ignore default arguments of old decl if they are not in 460 // the same scope and this is not an out-of-line definition of 461 // a member function. 462 continue; 463 } 464 465 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 466 // If only one of these is a local function declaration, then they are 467 // declared in different scopes, even though isDeclInScope may think 468 // they're in the same scope. (If both are local, the scope check is 469 // sufficient, and if neither is local, then they are in the same scope.) 470 continue; 471 } 472 473 // We found the right previous declaration. 474 break; 475 } 476 477 // C++ [dcl.fct.default]p4: 478 // For non-template functions, default arguments can be added in 479 // later declarations of a function in the same 480 // scope. Declarations in different scopes have completely 481 // distinct sets of default arguments. That is, declarations in 482 // inner scopes do not acquire default arguments from 483 // declarations in outer scopes, and vice versa. In a given 484 // function declaration, all parameters subsequent to a 485 // parameter with a default argument shall have default 486 // arguments supplied in this or previous declarations. A 487 // default argument shall not be redefined by a later 488 // declaration (not even to the same value). 489 // 490 // C++ [dcl.fct.default]p6: 491 // Except for member functions of class templates, the default arguments 492 // in a member function definition that appears outside of the class 493 // definition are added to the set of default arguments provided by the 494 // member function declaration in the class definition. 495 for (unsigned p = 0, NumParams = PrevForDefaultArgs 496 ? PrevForDefaultArgs->getNumParams() 497 : 0; 498 p < NumParams; ++p) { 499 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 500 ParmVarDecl *NewParam = New->getParamDecl(p); 501 502 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 503 bool NewParamHasDfl = NewParam->hasDefaultArg(); 504 505 if (OldParamHasDfl && NewParamHasDfl) { 506 unsigned DiagDefaultParamID = 507 diag::err_param_default_argument_redefinition; 508 509 // MSVC accepts that default parameters be redefined for member functions 510 // of template class. The new default parameter's value is ignored. 511 Invalid = true; 512 if (getLangOpts().MicrosoftExt) { 513 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 514 if (MD && MD->getParent()->getDescribedClassTemplate()) { 515 // Merge the old default argument into the new parameter. 516 NewParam->setHasInheritedDefaultArg(); 517 if (OldParam->hasUninstantiatedDefaultArg()) 518 NewParam->setUninstantiatedDefaultArg( 519 OldParam->getUninstantiatedDefaultArg()); 520 else 521 NewParam->setDefaultArg(OldParam->getInit()); 522 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 523 Invalid = false; 524 } 525 } 526 527 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 528 // hint here. Alternatively, we could walk the type-source information 529 // for NewParam to find the last source location in the type... but it 530 // isn't worth the effort right now. This is the kind of test case that 531 // is hard to get right: 532 // int f(int); 533 // void g(int (*fp)(int) = f); 534 // void g(int (*fp)(int) = &f); 535 Diag(NewParam->getLocation(), DiagDefaultParamID) 536 << NewParam->getDefaultArgRange(); 537 538 // Look for the function declaration where the default argument was 539 // actually written, which may be a declaration prior to Old. 540 for (auto Older = PrevForDefaultArgs; 541 OldParam->hasInheritedDefaultArg(); /**/) { 542 Older = Older->getPreviousDecl(); 543 OldParam = Older->getParamDecl(p); 544 } 545 546 Diag(OldParam->getLocation(), diag::note_previous_definition) 547 << OldParam->getDefaultArgRange(); 548 } else if (OldParamHasDfl) { 549 // Merge the old default argument into the new parameter unless the new 550 // function is a friend declaration in a template class. In the latter 551 // case the default arguments will be inherited when the friend 552 // declaration will be instantiated. 553 if (New->getFriendObjectKind() == Decl::FOK_None || 554 !New->getLexicalDeclContext()->isDependentContext()) { 555 // It's important to use getInit() here; getDefaultArg() 556 // strips off any top-level ExprWithCleanups. 557 NewParam->setHasInheritedDefaultArg(); 558 if (OldParam->hasUnparsedDefaultArg()) 559 NewParam->setUnparsedDefaultArg(); 560 else if (OldParam->hasUninstantiatedDefaultArg()) 561 NewParam->setUninstantiatedDefaultArg( 562 OldParam->getUninstantiatedDefaultArg()); 563 else 564 NewParam->setDefaultArg(OldParam->getInit()); 565 } 566 } else if (NewParamHasDfl) { 567 if (New->getDescribedFunctionTemplate()) { 568 // Paragraph 4, quoted above, only applies to non-template functions. 569 Diag(NewParam->getLocation(), 570 diag::err_param_default_argument_template_redecl) 571 << NewParam->getDefaultArgRange(); 572 Diag(PrevForDefaultArgs->getLocation(), 573 diag::note_template_prev_declaration) 574 << false; 575 } else if (New->getTemplateSpecializationKind() 576 != TSK_ImplicitInstantiation && 577 New->getTemplateSpecializationKind() != TSK_Undeclared) { 578 // C++ [temp.expr.spec]p21: 579 // Default function arguments shall not be specified in a declaration 580 // or a definition for one of the following explicit specializations: 581 // - the explicit specialization of a function template; 582 // - the explicit specialization of a member function template; 583 // - the explicit specialization of a member function of a class 584 // template where the class template specialization to which the 585 // member function specialization belongs is implicitly 586 // instantiated. 587 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 588 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 589 << New->getDeclName() 590 << NewParam->getDefaultArgRange(); 591 } else if (New->getDeclContext()->isDependentContext()) { 592 // C++ [dcl.fct.default]p6 (DR217): 593 // Default arguments for a member function of a class template shall 594 // be specified on the initial declaration of the member function 595 // within the class template. 596 // 597 // Reading the tea leaves a bit in DR217 and its reference to DR205 598 // leads me to the conclusion that one cannot add default function 599 // arguments for an out-of-line definition of a member function of a 600 // dependent type. 601 int WhichKind = 2; 602 if (CXXRecordDecl *Record 603 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 604 if (Record->getDescribedClassTemplate()) 605 WhichKind = 0; 606 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 607 WhichKind = 1; 608 else 609 WhichKind = 2; 610 } 611 612 Diag(NewParam->getLocation(), 613 diag::err_param_default_argument_member_template_redecl) 614 << WhichKind 615 << NewParam->getDefaultArgRange(); 616 } 617 } 618 } 619 620 // DR1344: If a default argument is added outside a class definition and that 621 // default argument makes the function a special member function, the program 622 // is ill-formed. This can only happen for constructors. 623 if (isa<CXXConstructorDecl>(New) && 624 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 625 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 626 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 627 if (NewSM != OldSM) { 628 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 629 assert(NewParam->hasDefaultArg()); 630 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 631 << NewParam->getDefaultArgRange() << NewSM; 632 Diag(Old->getLocation(), diag::note_previous_declaration); 633 } 634 } 635 636 const FunctionDecl *Def; 637 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 638 // template has a constexpr specifier then all its declarations shall 639 // contain the constexpr specifier. 640 if (New->isConstexpr() != Old->isConstexpr()) { 641 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 642 << New << New->isConstexpr(); 643 Diag(Old->getLocation(), diag::note_previous_declaration); 644 Invalid = true; 645 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 646 Old->isDefined(Def) && 647 // If a friend function is inlined but does not have 'inline' 648 // specifier, it is a definition. Do not report attribute conflict 649 // in this case, redefinition will be diagnosed later. 650 (New->isInlineSpecified() || 651 New->getFriendObjectKind() == Decl::FOK_None)) { 652 // C++11 [dcl.fcn.spec]p4: 653 // If the definition of a function appears in a translation unit before its 654 // first declaration as inline, the program is ill-formed. 655 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 656 Diag(Def->getLocation(), diag::note_previous_definition); 657 Invalid = true; 658 } 659 660 // C++17 [temp.deduct.guide]p3: 661 // Two deduction guide declarations in the same translation unit 662 // for the same class template shall not have equivalent 663 // parameter-declaration-clauses. 664 if (isa<CXXDeductionGuideDecl>(New) && 665 !New->isFunctionTemplateSpecialization()) { 666 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 667 Diag(Old->getLocation(), diag::note_previous_declaration); 668 } 669 670 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 671 // argument expression, that declaration shall be a definition and shall be 672 // the only declaration of the function or function template in the 673 // translation unit. 674 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 675 functionDeclHasDefaultArgument(Old)) { 676 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 677 Diag(Old->getLocation(), diag::note_previous_declaration); 678 Invalid = true; 679 } 680 681 return Invalid; 682 } 683 684 NamedDecl * 685 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 686 MultiTemplateParamsArg TemplateParamLists) { 687 assert(D.isDecompositionDeclarator()); 688 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 689 690 // The syntax only allows a decomposition declarator as a simple-declaration, 691 // a for-range-declaration, or a condition in Clang, but we parse it in more 692 // cases than that. 693 if (!D.mayHaveDecompositionDeclarator()) { 694 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 695 << Decomp.getSourceRange(); 696 return nullptr; 697 } 698 699 if (!TemplateParamLists.empty()) { 700 // FIXME: There's no rule against this, but there are also no rules that 701 // would actually make it usable, so we reject it for now. 702 Diag(TemplateParamLists.front()->getTemplateLoc(), 703 diag::err_decomp_decl_template); 704 return nullptr; 705 } 706 707 Diag(Decomp.getLSquareLoc(), 708 !getLangOpts().CPlusPlus17 709 ? diag::ext_decomp_decl 710 : D.getContext() == DeclaratorContext::ConditionContext 711 ? diag::ext_decomp_decl_cond 712 : diag::warn_cxx14_compat_decomp_decl) 713 << Decomp.getSourceRange(); 714 715 // The semantic context is always just the current context. 716 DeclContext *const DC = CurContext; 717 718 // C++17 [dcl.dcl]/8: 719 // The decl-specifier-seq shall contain only the type-specifier auto 720 // and cv-qualifiers. 721 // C++2a [dcl.dcl]/8: 722 // If decl-specifier-seq contains any decl-specifier other than static, 723 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 724 auto &DS = D.getDeclSpec(); 725 { 726 SmallVector<StringRef, 8> BadSpecifiers; 727 SmallVector<SourceLocation, 8> BadSpecifierLocs; 728 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 729 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 730 if (auto SCS = DS.getStorageClassSpec()) { 731 if (SCS == DeclSpec::SCS_static) { 732 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 733 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 734 } else { 735 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 736 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 737 } 738 } 739 if (auto TSCS = DS.getThreadStorageClassSpec()) { 740 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 741 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 742 } 743 if (DS.isConstexprSpecified()) { 744 BadSpecifiers.push_back("constexpr"); 745 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 746 } 747 if (DS.isInlineSpecified()) { 748 BadSpecifiers.push_back("inline"); 749 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 750 } 751 if (!BadSpecifiers.empty()) { 752 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 753 Err << (int)BadSpecifiers.size() 754 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 755 // Don't add FixItHints to remove the specifiers; we do still respect 756 // them when building the underlying variable. 757 for (auto Loc : BadSpecifierLocs) 758 Err << SourceRange(Loc, Loc); 759 } else if (!CPlusPlus20Specifiers.empty()) { 760 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 761 getLangOpts().CPlusPlus2a 762 ? diag::warn_cxx17_compat_decomp_decl_spec 763 : diag::ext_decomp_decl_spec); 764 Warn << (int)CPlusPlus20Specifiers.size() 765 << llvm::join(CPlusPlus20Specifiers.begin(), 766 CPlusPlus20Specifiers.end(), " "); 767 for (auto Loc : CPlusPlus20SpecifierLocs) 768 Warn << SourceRange(Loc, Loc); 769 } 770 // We can't recover from it being declared as a typedef. 771 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 772 return nullptr; 773 } 774 775 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 776 QualType R = TInfo->getType(); 777 778 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 779 UPPC_DeclarationType)) 780 D.setInvalidType(); 781 782 // The syntax only allows a single ref-qualifier prior to the decomposition 783 // declarator. No other declarator chunks are permitted. Also check the type 784 // specifier here. 785 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 786 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 787 (D.getNumTypeObjects() == 1 && 788 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 789 Diag(Decomp.getLSquareLoc(), 790 (D.hasGroupingParens() || 791 (D.getNumTypeObjects() && 792 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 793 ? diag::err_decomp_decl_parens 794 : diag::err_decomp_decl_type) 795 << R; 796 797 // In most cases, there's no actual problem with an explicitly-specified 798 // type, but a function type won't work here, and ActOnVariableDeclarator 799 // shouldn't be called for such a type. 800 if (R->isFunctionType()) 801 D.setInvalidType(); 802 } 803 804 // Build the BindingDecls. 805 SmallVector<BindingDecl*, 8> Bindings; 806 807 // Build the BindingDecls. 808 for (auto &B : D.getDecompositionDeclarator().bindings()) { 809 // Check for name conflicts. 810 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 811 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 812 ForVisibleRedeclaration); 813 LookupName(Previous, S, 814 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 815 816 // It's not permitted to shadow a template parameter name. 817 if (Previous.isSingleResult() && 818 Previous.getFoundDecl()->isTemplateParameter()) { 819 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 820 Previous.getFoundDecl()); 821 Previous.clear(); 822 } 823 824 bool ConsiderLinkage = DC->isFunctionOrMethod() && 825 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 826 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 827 /*AllowInlineNamespace*/false); 828 if (!Previous.empty()) { 829 auto *Old = Previous.getRepresentativeDecl(); 830 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 831 Diag(Old->getLocation(), diag::note_previous_definition); 832 } 833 834 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 835 PushOnScopeChains(BD, S, true); 836 Bindings.push_back(BD); 837 ParsingInitForAutoVars.insert(BD); 838 } 839 840 // There are no prior lookup results for the variable itself, because it 841 // is unnamed. 842 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 843 Decomp.getLSquareLoc()); 844 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 845 ForVisibleRedeclaration); 846 847 // Build the variable that holds the non-decomposed object. 848 bool AddToScope = true; 849 NamedDecl *New = 850 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 851 MultiTemplateParamsArg(), AddToScope, Bindings); 852 if (AddToScope) { 853 S->AddDecl(New); 854 CurContext->addHiddenDecl(New); 855 } 856 857 if (isInOpenMPDeclareTargetContext()) 858 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 859 860 return New; 861 } 862 863 static bool checkSimpleDecomposition( 864 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 865 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 866 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 867 if ((int64_t)Bindings.size() != NumElems) { 868 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 869 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 870 << (NumElems < Bindings.size()); 871 return true; 872 } 873 874 unsigned I = 0; 875 for (auto *B : Bindings) { 876 SourceLocation Loc = B->getLocation(); 877 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 878 if (E.isInvalid()) 879 return true; 880 E = GetInit(Loc, E.get(), I++); 881 if (E.isInvalid()) 882 return true; 883 B->setBinding(ElemType, E.get()); 884 } 885 886 return false; 887 } 888 889 static bool checkArrayLikeDecomposition(Sema &S, 890 ArrayRef<BindingDecl *> Bindings, 891 ValueDecl *Src, QualType DecompType, 892 const llvm::APSInt &NumElems, 893 QualType ElemType) { 894 return checkSimpleDecomposition( 895 S, Bindings, Src, DecompType, NumElems, ElemType, 896 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 897 ExprResult E = S.ActOnIntegerConstant(Loc, I); 898 if (E.isInvalid()) 899 return ExprError(); 900 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 901 }); 902 } 903 904 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 905 ValueDecl *Src, QualType DecompType, 906 const ConstantArrayType *CAT) { 907 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 908 llvm::APSInt(CAT->getSize()), 909 CAT->getElementType()); 910 } 911 912 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 913 ValueDecl *Src, QualType DecompType, 914 const VectorType *VT) { 915 return checkArrayLikeDecomposition( 916 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 917 S.Context.getQualifiedType(VT->getElementType(), 918 DecompType.getQualifiers())); 919 } 920 921 static bool checkComplexDecomposition(Sema &S, 922 ArrayRef<BindingDecl *> Bindings, 923 ValueDecl *Src, QualType DecompType, 924 const ComplexType *CT) { 925 return checkSimpleDecomposition( 926 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 927 S.Context.getQualifiedType(CT->getElementType(), 928 DecompType.getQualifiers()), 929 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 930 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 931 }); 932 } 933 934 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 935 TemplateArgumentListInfo &Args) { 936 SmallString<128> SS; 937 llvm::raw_svector_ostream OS(SS); 938 bool First = true; 939 for (auto &Arg : Args.arguments()) { 940 if (!First) 941 OS << ", "; 942 Arg.getArgument().print(PrintingPolicy, OS); 943 First = false; 944 } 945 return OS.str(); 946 } 947 948 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 949 SourceLocation Loc, StringRef Trait, 950 TemplateArgumentListInfo &Args, 951 unsigned DiagID) { 952 auto DiagnoseMissing = [&] { 953 if (DiagID) 954 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 955 Args); 956 return true; 957 }; 958 959 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 960 NamespaceDecl *Std = S.getStdNamespace(); 961 if (!Std) 962 return DiagnoseMissing(); 963 964 // Look up the trait itself, within namespace std. We can diagnose various 965 // problems with this lookup even if we've been asked to not diagnose a 966 // missing specialization, because this can only fail if the user has been 967 // declaring their own names in namespace std or we don't support the 968 // standard library implementation in use. 969 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 970 Loc, Sema::LookupOrdinaryName); 971 if (!S.LookupQualifiedName(Result, Std)) 972 return DiagnoseMissing(); 973 if (Result.isAmbiguous()) 974 return true; 975 976 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 977 if (!TraitTD) { 978 Result.suppressDiagnostics(); 979 NamedDecl *Found = *Result.begin(); 980 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 981 S.Diag(Found->getLocation(), diag::note_declared_at); 982 return true; 983 } 984 985 // Build the template-id. 986 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 987 if (TraitTy.isNull()) 988 return true; 989 if (!S.isCompleteType(Loc, TraitTy)) { 990 if (DiagID) 991 S.RequireCompleteType( 992 Loc, TraitTy, DiagID, 993 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 994 return true; 995 } 996 997 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 998 assert(RD && "specialization of class template is not a class?"); 999 1000 // Look up the member of the trait type. 1001 S.LookupQualifiedName(TraitMemberLookup, RD); 1002 return TraitMemberLookup.isAmbiguous(); 1003 } 1004 1005 static TemplateArgumentLoc 1006 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1007 uint64_t I) { 1008 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1009 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1010 } 1011 1012 static TemplateArgumentLoc 1013 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1014 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1015 } 1016 1017 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1018 1019 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1020 llvm::APSInt &Size) { 1021 EnterExpressionEvaluationContext ContextRAII( 1022 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1023 1024 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1025 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1026 1027 // Form template argument list for tuple_size<T>. 1028 TemplateArgumentListInfo Args(Loc, Loc); 1029 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1030 1031 // If there's no tuple_size specialization, it's not tuple-like. 1032 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1033 return IsTupleLike::NotTupleLike; 1034 1035 // If we get this far, we've committed to the tuple interpretation, but 1036 // we can still fail if there actually isn't a usable ::value. 1037 1038 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1039 LookupResult &R; 1040 TemplateArgumentListInfo &Args; 1041 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1042 : R(R), Args(Args) {} 1043 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1044 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1045 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1046 } 1047 } Diagnoser(R, Args); 1048 1049 if (R.empty()) { 1050 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1051 return IsTupleLike::Error; 1052 } 1053 1054 ExprResult E = 1055 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1056 if (E.isInvalid()) 1057 return IsTupleLike::Error; 1058 1059 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1060 if (E.isInvalid()) 1061 return IsTupleLike::Error; 1062 1063 return IsTupleLike::TupleLike; 1064 } 1065 1066 /// \return std::tuple_element<I, T>::type. 1067 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1068 unsigned I, QualType T) { 1069 // Form template argument list for tuple_element<I, T>. 1070 TemplateArgumentListInfo Args(Loc, Loc); 1071 Args.addArgument( 1072 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1073 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1074 1075 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1076 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1077 if (lookupStdTypeTraitMember( 1078 S, R, Loc, "tuple_element", Args, 1079 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1080 return QualType(); 1081 1082 auto *TD = R.getAsSingle<TypeDecl>(); 1083 if (!TD) { 1084 R.suppressDiagnostics(); 1085 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1086 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1087 if (!R.empty()) 1088 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1089 return QualType(); 1090 } 1091 1092 return S.Context.getTypeDeclType(TD); 1093 } 1094 1095 namespace { 1096 struct BindingDiagnosticTrap { 1097 Sema &S; 1098 DiagnosticErrorTrap Trap; 1099 BindingDecl *BD; 1100 1101 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1102 : S(S), Trap(S.Diags), BD(BD) {} 1103 ~BindingDiagnosticTrap() { 1104 if (Trap.hasErrorOccurred()) 1105 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1106 } 1107 }; 1108 } 1109 1110 static bool checkTupleLikeDecomposition(Sema &S, 1111 ArrayRef<BindingDecl *> Bindings, 1112 VarDecl *Src, QualType DecompType, 1113 const llvm::APSInt &TupleSize) { 1114 if ((int64_t)Bindings.size() != TupleSize) { 1115 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1116 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1117 << (TupleSize < Bindings.size()); 1118 return true; 1119 } 1120 1121 if (Bindings.empty()) 1122 return false; 1123 1124 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1125 1126 // [dcl.decomp]p3: 1127 // The unqualified-id get is looked up in the scope of E by class member 1128 // access lookup ... 1129 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1130 bool UseMemberGet = false; 1131 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1132 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1133 S.LookupQualifiedName(MemberGet, RD); 1134 if (MemberGet.isAmbiguous()) 1135 return true; 1136 // ... and if that finds at least one declaration that is a function 1137 // template whose first template parameter is a non-type parameter ... 1138 for (NamedDecl *D : MemberGet) { 1139 if (FunctionTemplateDecl *FTD = 1140 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1141 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1142 if (TPL->size() != 0 && 1143 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1144 // ... the initializer is e.get<i>(). 1145 UseMemberGet = true; 1146 break; 1147 } 1148 } 1149 } 1150 } 1151 1152 unsigned I = 0; 1153 for (auto *B : Bindings) { 1154 BindingDiagnosticTrap Trap(S, B); 1155 SourceLocation Loc = B->getLocation(); 1156 1157 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1158 if (E.isInvalid()) 1159 return true; 1160 1161 // e is an lvalue if the type of the entity is an lvalue reference and 1162 // an xvalue otherwise 1163 if (!Src->getType()->isLValueReferenceType()) 1164 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1165 E.get(), nullptr, VK_XValue); 1166 1167 TemplateArgumentListInfo Args(Loc, Loc); 1168 Args.addArgument( 1169 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1170 1171 if (UseMemberGet) { 1172 // if [lookup of member get] finds at least one declaration, the 1173 // initializer is e.get<i-1>(). 1174 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1175 CXXScopeSpec(), SourceLocation(), nullptr, 1176 MemberGet, &Args, nullptr); 1177 if (E.isInvalid()) 1178 return true; 1179 1180 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1181 } else { 1182 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1183 // in the associated namespaces. 1184 Expr *Get = UnresolvedLookupExpr::Create( 1185 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1186 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1187 UnresolvedSetIterator(), UnresolvedSetIterator()); 1188 1189 Expr *Arg = E.get(); 1190 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1191 } 1192 if (E.isInvalid()) 1193 return true; 1194 Expr *Init = E.get(); 1195 1196 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1197 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1198 if (T.isNull()) 1199 return true; 1200 1201 // each vi is a variable of type "reference to T" initialized with the 1202 // initializer, where the reference is an lvalue reference if the 1203 // initializer is an lvalue and an rvalue reference otherwise 1204 QualType RefType = 1205 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1206 if (RefType.isNull()) 1207 return true; 1208 auto *RefVD = VarDecl::Create( 1209 S.Context, Src->getDeclContext(), Loc, Loc, 1210 B->getDeclName().getAsIdentifierInfo(), RefType, 1211 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1212 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1213 RefVD->setTSCSpec(Src->getTSCSpec()); 1214 RefVD->setImplicit(); 1215 if (Src->isInlineSpecified()) 1216 RefVD->setInlineSpecified(); 1217 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1218 1219 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1220 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1221 InitializationSequence Seq(S, Entity, Kind, Init); 1222 E = Seq.Perform(S, Entity, Kind, Init); 1223 if (E.isInvalid()) 1224 return true; 1225 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1226 if (E.isInvalid()) 1227 return true; 1228 RefVD->setInit(E.get()); 1229 RefVD->checkInitIsICE(); 1230 1231 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1232 DeclarationNameInfo(B->getDeclName(), Loc), 1233 RefVD); 1234 if (E.isInvalid()) 1235 return true; 1236 1237 B->setBinding(T, E.get()); 1238 I++; 1239 } 1240 1241 return false; 1242 } 1243 1244 /// Find the base class to decompose in a built-in decomposition of a class type. 1245 /// This base class search is, unfortunately, not quite like any other that we 1246 /// perform anywhere else in C++. 1247 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1248 const CXXRecordDecl *RD, 1249 CXXCastPath &BasePath) { 1250 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1251 CXXBasePath &Path) { 1252 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1253 }; 1254 1255 const CXXRecordDecl *ClassWithFields = nullptr; 1256 AccessSpecifier AS = AS_public; 1257 if (RD->hasDirectFields()) 1258 // [dcl.decomp]p4: 1259 // Otherwise, all of E's non-static data members shall be public direct 1260 // members of E ... 1261 ClassWithFields = RD; 1262 else { 1263 // ... or of ... 1264 CXXBasePaths Paths; 1265 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1266 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1267 // If no classes have fields, just decompose RD itself. (This will work 1268 // if and only if zero bindings were provided.) 1269 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1270 } 1271 1272 CXXBasePath *BestPath = nullptr; 1273 for (auto &P : Paths) { 1274 if (!BestPath) 1275 BestPath = &P; 1276 else if (!S.Context.hasSameType(P.back().Base->getType(), 1277 BestPath->back().Base->getType())) { 1278 // ... the same ... 1279 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1280 << false << RD << BestPath->back().Base->getType() 1281 << P.back().Base->getType(); 1282 return DeclAccessPair(); 1283 } else if (P.Access < BestPath->Access) { 1284 BestPath = &P; 1285 } 1286 } 1287 1288 // ... unambiguous ... 1289 QualType BaseType = BestPath->back().Base->getType(); 1290 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1291 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1292 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1293 return DeclAccessPair(); 1294 } 1295 1296 // ... [accessible, implied by other rules] base class of E. 1297 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1298 *BestPath, diag::err_decomp_decl_inaccessible_base); 1299 AS = BestPath->Access; 1300 1301 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1302 S.BuildBasePathArray(Paths, BasePath); 1303 } 1304 1305 // The above search did not check whether the selected class itself has base 1306 // classes with fields, so check that now. 1307 CXXBasePaths Paths; 1308 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1309 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1310 << (ClassWithFields == RD) << RD << ClassWithFields 1311 << Paths.front().back().Base->getType(); 1312 return DeclAccessPair(); 1313 } 1314 1315 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1316 } 1317 1318 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1319 ValueDecl *Src, QualType DecompType, 1320 const CXXRecordDecl *OrigRD) { 1321 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1322 diag::err_incomplete_type)) 1323 return true; 1324 1325 CXXCastPath BasePath; 1326 DeclAccessPair BasePair = 1327 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1328 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1329 if (!RD) 1330 return true; 1331 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1332 DecompType.getQualifiers()); 1333 1334 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1335 unsigned NumFields = 1336 std::count_if(RD->field_begin(), RD->field_end(), 1337 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1338 assert(Bindings.size() != NumFields); 1339 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1340 << DecompType << (unsigned)Bindings.size() << NumFields 1341 << (NumFields < Bindings.size()); 1342 return true; 1343 }; 1344 1345 // all of E's non-static data members shall be [...] well-formed 1346 // when named as e.name in the context of the structured binding, 1347 // E shall not have an anonymous union member, ... 1348 unsigned I = 0; 1349 for (auto *FD : RD->fields()) { 1350 if (FD->isUnnamedBitfield()) 1351 continue; 1352 1353 if (FD->isAnonymousStructOrUnion()) { 1354 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1355 << DecompType << FD->getType()->isUnionType(); 1356 S.Diag(FD->getLocation(), diag::note_declared_at); 1357 return true; 1358 } 1359 1360 // We have a real field to bind. 1361 if (I >= Bindings.size()) 1362 return DiagnoseBadNumberOfBindings(); 1363 auto *B = Bindings[I++]; 1364 SourceLocation Loc = B->getLocation(); 1365 1366 // The field must be accessible in the context of the structured binding. 1367 // We already checked that the base class is accessible. 1368 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1369 // const_cast here. 1370 S.CheckStructuredBindingMemberAccess( 1371 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1372 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1373 BasePair.getAccess(), FD->getAccess()))); 1374 1375 // Initialize the binding to Src.FD. 1376 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1377 if (E.isInvalid()) 1378 return true; 1379 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1380 VK_LValue, &BasePath); 1381 if (E.isInvalid()) 1382 return true; 1383 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1384 CXXScopeSpec(), FD, 1385 DeclAccessPair::make(FD, FD->getAccess()), 1386 DeclarationNameInfo(FD->getDeclName(), Loc)); 1387 if (E.isInvalid()) 1388 return true; 1389 1390 // If the type of the member is T, the referenced type is cv T, where cv is 1391 // the cv-qualification of the decomposition expression. 1392 // 1393 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1394 // 'const' to the type of the field. 1395 Qualifiers Q = DecompType.getQualifiers(); 1396 if (FD->isMutable()) 1397 Q.removeConst(); 1398 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1399 } 1400 1401 if (I != Bindings.size()) 1402 return DiagnoseBadNumberOfBindings(); 1403 1404 return false; 1405 } 1406 1407 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1408 QualType DecompType = DD->getType(); 1409 1410 // If the type of the decomposition is dependent, then so is the type of 1411 // each binding. 1412 if (DecompType->isDependentType()) { 1413 for (auto *B : DD->bindings()) 1414 B->setType(Context.DependentTy); 1415 return; 1416 } 1417 1418 DecompType = DecompType.getNonReferenceType(); 1419 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1420 1421 // C++1z [dcl.decomp]/2: 1422 // If E is an array type [...] 1423 // As an extension, we also support decomposition of built-in complex and 1424 // vector types. 1425 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1426 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1427 DD->setInvalidDecl(); 1428 return; 1429 } 1430 if (auto *VT = DecompType->getAs<VectorType>()) { 1431 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1432 DD->setInvalidDecl(); 1433 return; 1434 } 1435 if (auto *CT = DecompType->getAs<ComplexType>()) { 1436 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1437 DD->setInvalidDecl(); 1438 return; 1439 } 1440 1441 // C++1z [dcl.decomp]/3: 1442 // if the expression std::tuple_size<E>::value is a well-formed integral 1443 // constant expression, [...] 1444 llvm::APSInt TupleSize(32); 1445 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1446 case IsTupleLike::Error: 1447 DD->setInvalidDecl(); 1448 return; 1449 1450 case IsTupleLike::TupleLike: 1451 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1452 DD->setInvalidDecl(); 1453 return; 1454 1455 case IsTupleLike::NotTupleLike: 1456 break; 1457 } 1458 1459 // C++1z [dcl.dcl]/8: 1460 // [E shall be of array or non-union class type] 1461 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1462 if (!RD || RD->isUnion()) { 1463 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1464 << DD << !RD << DecompType; 1465 DD->setInvalidDecl(); 1466 return; 1467 } 1468 1469 // C++1z [dcl.decomp]/4: 1470 // all of E's non-static data members shall be [...] direct members of 1471 // E or of the same unambiguous public base class of E, ... 1472 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1473 DD->setInvalidDecl(); 1474 } 1475 1476 /// Merge the exception specifications of two variable declarations. 1477 /// 1478 /// This is called when there's a redeclaration of a VarDecl. The function 1479 /// checks if the redeclaration might have an exception specification and 1480 /// validates compatibility and merges the specs if necessary. 1481 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1482 // Shortcut if exceptions are disabled. 1483 if (!getLangOpts().CXXExceptions) 1484 return; 1485 1486 assert(Context.hasSameType(New->getType(), Old->getType()) && 1487 "Should only be called if types are otherwise the same."); 1488 1489 QualType NewType = New->getType(); 1490 QualType OldType = Old->getType(); 1491 1492 // We're only interested in pointers and references to functions, as well 1493 // as pointers to member functions. 1494 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1495 NewType = R->getPointeeType(); 1496 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1497 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1498 NewType = P->getPointeeType(); 1499 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1500 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1501 NewType = M->getPointeeType(); 1502 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1503 } 1504 1505 if (!NewType->isFunctionProtoType()) 1506 return; 1507 1508 // There's lots of special cases for functions. For function pointers, system 1509 // libraries are hopefully not as broken so that we don't need these 1510 // workarounds. 1511 if (CheckEquivalentExceptionSpec( 1512 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1513 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1514 New->setInvalidDecl(); 1515 } 1516 } 1517 1518 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1519 /// function declaration are well-formed according to C++ 1520 /// [dcl.fct.default]. 1521 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1522 unsigned NumParams = FD->getNumParams(); 1523 unsigned p; 1524 1525 // Find first parameter with a default argument 1526 for (p = 0; p < NumParams; ++p) { 1527 ParmVarDecl *Param = FD->getParamDecl(p); 1528 if (Param->hasDefaultArg()) 1529 break; 1530 } 1531 1532 // C++11 [dcl.fct.default]p4: 1533 // In a given function declaration, each parameter subsequent to a parameter 1534 // with a default argument shall have a default argument supplied in this or 1535 // a previous declaration or shall be a function parameter pack. A default 1536 // argument shall not be redefined by a later declaration (not even to the 1537 // same value). 1538 unsigned LastMissingDefaultArg = 0; 1539 for (; p < NumParams; ++p) { 1540 ParmVarDecl *Param = FD->getParamDecl(p); 1541 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1542 if (Param->isInvalidDecl()) 1543 /* We already complained about this parameter. */; 1544 else if (Param->getIdentifier()) 1545 Diag(Param->getLocation(), 1546 diag::err_param_default_argument_missing_name) 1547 << Param->getIdentifier(); 1548 else 1549 Diag(Param->getLocation(), 1550 diag::err_param_default_argument_missing); 1551 1552 LastMissingDefaultArg = p; 1553 } 1554 } 1555 1556 if (LastMissingDefaultArg > 0) { 1557 // Some default arguments were missing. Clear out all of the 1558 // default arguments up to (and including) the last missing 1559 // default argument, so that we leave the function parameters 1560 // in a semantically valid state. 1561 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1562 ParmVarDecl *Param = FD->getParamDecl(p); 1563 if (Param->hasDefaultArg()) { 1564 Param->setDefaultArg(nullptr); 1565 } 1566 } 1567 } 1568 } 1569 1570 // CheckConstexprParameterTypes - Check whether a function's parameter types 1571 // are all literal types. If so, return true. If not, produce a suitable 1572 // diagnostic and return false. 1573 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1574 const FunctionDecl *FD) { 1575 unsigned ArgIndex = 0; 1576 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1577 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1578 e = FT->param_type_end(); 1579 i != e; ++i, ++ArgIndex) { 1580 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1581 SourceLocation ParamLoc = PD->getLocation(); 1582 if (!(*i)->isDependentType() && 1583 SemaRef.RequireLiteralType(ParamLoc, *i, 1584 diag::err_constexpr_non_literal_param, 1585 ArgIndex+1, PD->getSourceRange(), 1586 isa<CXXConstructorDecl>(FD))) 1587 return false; 1588 } 1589 return true; 1590 } 1591 1592 /// Get diagnostic %select index for tag kind for 1593 /// record diagnostic message. 1594 /// WARNING: Indexes apply to particular diagnostics only! 1595 /// 1596 /// \returns diagnostic %select index. 1597 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1598 switch (Tag) { 1599 case TTK_Struct: return 0; 1600 case TTK_Interface: return 1; 1601 case TTK_Class: return 2; 1602 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1603 } 1604 } 1605 1606 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1607 // the requirements of a constexpr function definition or a constexpr 1608 // constructor definition. If so, return true. If not, produce appropriate 1609 // diagnostics and return false. 1610 // 1611 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1612 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1613 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1614 if (MD && MD->isInstance()) { 1615 // C++11 [dcl.constexpr]p4: 1616 // The definition of a constexpr constructor shall satisfy the following 1617 // constraints: 1618 // - the class shall not have any virtual base classes; 1619 // 1620 // FIXME: This only applies to constructors, not arbitrary member 1621 // functions. 1622 const CXXRecordDecl *RD = MD->getParent(); 1623 if (RD->getNumVBases()) { 1624 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1625 << isa<CXXConstructorDecl>(NewFD) 1626 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1627 for (const auto &I : RD->vbases()) 1628 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1629 << I.getSourceRange(); 1630 return false; 1631 } 1632 } 1633 1634 if (!isa<CXXConstructorDecl>(NewFD)) { 1635 // C++11 [dcl.constexpr]p3: 1636 // The definition of a constexpr function shall satisfy the following 1637 // constraints: 1638 // - it shall not be virtual; (removed in C++20) 1639 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1640 if (Method && Method->isVirtual()) { 1641 if (getLangOpts().CPlusPlus2a) { 1642 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1643 } else { 1644 Method = Method->getCanonicalDecl(); 1645 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1646 1647 // If it's not obvious why this function is virtual, find an overridden 1648 // function which uses the 'virtual' keyword. 1649 const CXXMethodDecl *WrittenVirtual = Method; 1650 while (!WrittenVirtual->isVirtualAsWritten()) 1651 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1652 if (WrittenVirtual != Method) 1653 Diag(WrittenVirtual->getLocation(), 1654 diag::note_overridden_virtual_function); 1655 return false; 1656 } 1657 } 1658 1659 // - its return type shall be a literal type; 1660 QualType RT = NewFD->getReturnType(); 1661 if (!RT->isDependentType() && 1662 RequireLiteralType(NewFD->getLocation(), RT, 1663 diag::err_constexpr_non_literal_return)) 1664 return false; 1665 } 1666 1667 // - each of its parameter types shall be a literal type; 1668 if (!CheckConstexprParameterTypes(*this, NewFD)) 1669 return false; 1670 1671 return true; 1672 } 1673 1674 /// Check the given declaration statement is legal within a constexpr function 1675 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1676 /// 1677 /// \return true if the body is OK (maybe only as an extension), false if we 1678 /// have diagnosed a problem. 1679 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1680 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1681 // C++11 [dcl.constexpr]p3 and p4: 1682 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1683 // contain only 1684 for (const auto *DclIt : DS->decls()) { 1685 switch (DclIt->getKind()) { 1686 case Decl::StaticAssert: 1687 case Decl::Using: 1688 case Decl::UsingShadow: 1689 case Decl::UsingDirective: 1690 case Decl::UnresolvedUsingTypename: 1691 case Decl::UnresolvedUsingValue: 1692 // - static_assert-declarations 1693 // - using-declarations, 1694 // - using-directives, 1695 continue; 1696 1697 case Decl::Typedef: 1698 case Decl::TypeAlias: { 1699 // - typedef declarations and alias-declarations that do not define 1700 // classes or enumerations, 1701 const auto *TN = cast<TypedefNameDecl>(DclIt); 1702 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1703 // Don't allow variably-modified types in constexpr functions. 1704 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1705 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1706 << TL.getSourceRange() << TL.getType() 1707 << isa<CXXConstructorDecl>(Dcl); 1708 return false; 1709 } 1710 continue; 1711 } 1712 1713 case Decl::Enum: 1714 case Decl::CXXRecord: 1715 // C++1y allows types to be defined, not just declared. 1716 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1717 SemaRef.Diag(DS->getBeginLoc(), 1718 SemaRef.getLangOpts().CPlusPlus14 1719 ? diag::warn_cxx11_compat_constexpr_type_definition 1720 : diag::ext_constexpr_type_definition) 1721 << isa<CXXConstructorDecl>(Dcl); 1722 continue; 1723 1724 case Decl::EnumConstant: 1725 case Decl::IndirectField: 1726 case Decl::ParmVar: 1727 // These can only appear with other declarations which are banned in 1728 // C++11 and permitted in C++1y, so ignore them. 1729 continue; 1730 1731 case Decl::Var: 1732 case Decl::Decomposition: { 1733 // C++1y [dcl.constexpr]p3 allows anything except: 1734 // a definition of a variable of non-literal type or of static or 1735 // thread storage duration or for which no initialization is performed. 1736 const auto *VD = cast<VarDecl>(DclIt); 1737 if (VD->isThisDeclarationADefinition()) { 1738 if (VD->isStaticLocal()) { 1739 SemaRef.Diag(VD->getLocation(), 1740 diag::err_constexpr_local_var_static) 1741 << isa<CXXConstructorDecl>(Dcl) 1742 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1743 return false; 1744 } 1745 if (!VD->getType()->isDependentType() && 1746 SemaRef.RequireLiteralType( 1747 VD->getLocation(), VD->getType(), 1748 diag::err_constexpr_local_var_non_literal_type, 1749 isa<CXXConstructorDecl>(Dcl))) 1750 return false; 1751 if (!VD->getType()->isDependentType() && 1752 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1753 SemaRef.Diag(VD->getLocation(), 1754 diag::err_constexpr_local_var_no_init) 1755 << isa<CXXConstructorDecl>(Dcl); 1756 return false; 1757 } 1758 } 1759 SemaRef.Diag(VD->getLocation(), 1760 SemaRef.getLangOpts().CPlusPlus14 1761 ? diag::warn_cxx11_compat_constexpr_local_var 1762 : diag::ext_constexpr_local_var) 1763 << isa<CXXConstructorDecl>(Dcl); 1764 continue; 1765 } 1766 1767 case Decl::NamespaceAlias: 1768 case Decl::Function: 1769 // These are disallowed in C++11 and permitted in C++1y. Allow them 1770 // everywhere as an extension. 1771 if (!Cxx1yLoc.isValid()) 1772 Cxx1yLoc = DS->getBeginLoc(); 1773 continue; 1774 1775 default: 1776 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1777 << isa<CXXConstructorDecl>(Dcl); 1778 return false; 1779 } 1780 } 1781 1782 return true; 1783 } 1784 1785 /// Check that the given field is initialized within a constexpr constructor. 1786 /// 1787 /// \param Dcl The constexpr constructor being checked. 1788 /// \param Field The field being checked. This may be a member of an anonymous 1789 /// struct or union nested within the class being checked. 1790 /// \param Inits All declarations, including anonymous struct/union members and 1791 /// indirect members, for which any initialization was provided. 1792 /// \param Diagnosed Set to true if an error is produced. 1793 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1794 const FunctionDecl *Dcl, 1795 FieldDecl *Field, 1796 llvm::SmallSet<Decl*, 16> &Inits, 1797 bool &Diagnosed) { 1798 if (Field->isInvalidDecl()) 1799 return; 1800 1801 if (Field->isUnnamedBitfield()) 1802 return; 1803 1804 // Anonymous unions with no variant members and empty anonymous structs do not 1805 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1806 // indirect fields don't need initializing. 1807 if (Field->isAnonymousStructOrUnion() && 1808 (Field->getType()->isUnionType() 1809 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1810 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1811 return; 1812 1813 if (!Inits.count(Field)) { 1814 if (!Diagnosed) { 1815 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1816 Diagnosed = true; 1817 } 1818 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1819 } else if (Field->isAnonymousStructOrUnion()) { 1820 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1821 for (auto *I : RD->fields()) 1822 // If an anonymous union contains an anonymous struct of which any member 1823 // is initialized, all members must be initialized. 1824 if (!RD->isUnion() || Inits.count(I)) 1825 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1826 } 1827 } 1828 1829 /// Check the provided statement is allowed in a constexpr function 1830 /// definition. 1831 static bool 1832 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1833 SmallVectorImpl<SourceLocation> &ReturnStmts, 1834 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) { 1835 // - its function-body shall be [...] a compound-statement that contains only 1836 switch (S->getStmtClass()) { 1837 case Stmt::NullStmtClass: 1838 // - null statements, 1839 return true; 1840 1841 case Stmt::DeclStmtClass: 1842 // - static_assert-declarations 1843 // - using-declarations, 1844 // - using-directives, 1845 // - typedef declarations and alias-declarations that do not define 1846 // classes or enumerations, 1847 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1848 return false; 1849 return true; 1850 1851 case Stmt::ReturnStmtClass: 1852 // - and exactly one return statement; 1853 if (isa<CXXConstructorDecl>(Dcl)) { 1854 // C++1y allows return statements in constexpr constructors. 1855 if (!Cxx1yLoc.isValid()) 1856 Cxx1yLoc = S->getBeginLoc(); 1857 return true; 1858 } 1859 1860 ReturnStmts.push_back(S->getBeginLoc()); 1861 return true; 1862 1863 case Stmt::CompoundStmtClass: { 1864 // C++1y allows compound-statements. 1865 if (!Cxx1yLoc.isValid()) 1866 Cxx1yLoc = S->getBeginLoc(); 1867 1868 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1869 for (auto *BodyIt : CompStmt->body()) { 1870 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1871 Cxx1yLoc, Cxx2aLoc)) 1872 return false; 1873 } 1874 return true; 1875 } 1876 1877 case Stmt::AttributedStmtClass: 1878 if (!Cxx1yLoc.isValid()) 1879 Cxx1yLoc = S->getBeginLoc(); 1880 return true; 1881 1882 case Stmt::IfStmtClass: { 1883 // C++1y allows if-statements. 1884 if (!Cxx1yLoc.isValid()) 1885 Cxx1yLoc = S->getBeginLoc(); 1886 1887 IfStmt *If = cast<IfStmt>(S); 1888 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1889 Cxx1yLoc, Cxx2aLoc)) 1890 return false; 1891 if (If->getElse() && 1892 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1893 Cxx1yLoc, Cxx2aLoc)) 1894 return false; 1895 return true; 1896 } 1897 1898 case Stmt::WhileStmtClass: 1899 case Stmt::DoStmtClass: 1900 case Stmt::ForStmtClass: 1901 case Stmt::CXXForRangeStmtClass: 1902 case Stmt::ContinueStmtClass: 1903 // C++1y allows all of these. We don't allow them as extensions in C++11, 1904 // because they don't make sense without variable mutation. 1905 if (!SemaRef.getLangOpts().CPlusPlus14) 1906 break; 1907 if (!Cxx1yLoc.isValid()) 1908 Cxx1yLoc = S->getBeginLoc(); 1909 for (Stmt *SubStmt : S->children()) 1910 if (SubStmt && 1911 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1912 Cxx1yLoc, Cxx2aLoc)) 1913 return false; 1914 return true; 1915 1916 case Stmt::SwitchStmtClass: 1917 case Stmt::CaseStmtClass: 1918 case Stmt::DefaultStmtClass: 1919 case Stmt::BreakStmtClass: 1920 // C++1y allows switch-statements, and since they don't need variable 1921 // mutation, we can reasonably allow them in C++11 as an extension. 1922 if (!Cxx1yLoc.isValid()) 1923 Cxx1yLoc = S->getBeginLoc(); 1924 for (Stmt *SubStmt : S->children()) 1925 if (SubStmt && 1926 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1927 Cxx1yLoc, Cxx2aLoc)) 1928 return false; 1929 return true; 1930 1931 case Stmt::CXXTryStmtClass: 1932 if (Cxx2aLoc.isInvalid()) 1933 Cxx2aLoc = S->getBeginLoc(); 1934 for (Stmt *SubStmt : S->children()) { 1935 if (SubStmt && 1936 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1937 Cxx1yLoc, Cxx2aLoc)) 1938 return false; 1939 } 1940 return true; 1941 1942 case Stmt::CXXCatchStmtClass: 1943 // Do not bother checking the language mode (already covered by the 1944 // try block check). 1945 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 1946 cast<CXXCatchStmt>(S)->getHandlerBlock(), 1947 ReturnStmts, Cxx1yLoc, Cxx2aLoc)) 1948 return false; 1949 return true; 1950 1951 default: 1952 if (!isa<Expr>(S)) 1953 break; 1954 1955 // C++1y allows expression-statements. 1956 if (!Cxx1yLoc.isValid()) 1957 Cxx1yLoc = S->getBeginLoc(); 1958 return true; 1959 } 1960 1961 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1962 << isa<CXXConstructorDecl>(Dcl); 1963 return false; 1964 } 1965 1966 /// Check the body for the given constexpr function declaration only contains 1967 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1968 /// 1969 /// \return true if the body is OK, false if we have diagnosed a problem. 1970 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1971 SmallVector<SourceLocation, 4> ReturnStmts; 1972 1973 if (isa<CXXTryStmt>(Body)) { 1974 // C++11 [dcl.constexpr]p3: 1975 // The definition of a constexpr function shall satisfy the following 1976 // constraints: [...] 1977 // - its function-body shall be = delete, = default, or a 1978 // compound-statement 1979 // 1980 // C++11 [dcl.constexpr]p4: 1981 // In the definition of a constexpr constructor, [...] 1982 // - its function-body shall not be a function-try-block; 1983 // 1984 // This restriction is lifted in C++2a, as long as inner statements also 1985 // apply the general constexpr rules. 1986 Diag(Body->getBeginLoc(), 1987 !getLangOpts().CPlusPlus2a 1988 ? diag::ext_constexpr_function_try_block_cxx2a 1989 : diag::warn_cxx17_compat_constexpr_function_try_block) 1990 << isa<CXXConstructorDecl>(Dcl); 1991 } 1992 1993 // - its function-body shall be [...] a compound-statement that contains only 1994 // [... list of cases ...] 1995 // 1996 // Note that walking the children here is enough to properly check for 1997 // CompoundStmt and CXXTryStmt body. 1998 SourceLocation Cxx1yLoc, Cxx2aLoc; 1999 for (Stmt *SubStmt : Body->children()) { 2000 if (SubStmt && 2001 !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts, 2002 Cxx1yLoc, Cxx2aLoc)) 2003 return false; 2004 } 2005 2006 if (Cxx2aLoc.isValid()) 2007 Diag(Cxx2aLoc, 2008 getLangOpts().CPlusPlus2a 2009 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2010 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 2011 << isa<CXXConstructorDecl>(Dcl); 2012 if (Cxx1yLoc.isValid()) 2013 Diag(Cxx1yLoc, 2014 getLangOpts().CPlusPlus14 2015 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2016 : diag::ext_constexpr_body_invalid_stmt) 2017 << isa<CXXConstructorDecl>(Dcl); 2018 2019 if (const CXXConstructorDecl *Constructor 2020 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2021 const CXXRecordDecl *RD = Constructor->getParent(); 2022 // DR1359: 2023 // - every non-variant non-static data member and base class sub-object 2024 // shall be initialized; 2025 // DR1460: 2026 // - if the class is a union having variant members, exactly one of them 2027 // shall be initialized; 2028 if (RD->isUnion()) { 2029 if (Constructor->getNumCtorInitializers() == 0 && 2030 RD->hasVariantMembers()) { 2031 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 2032 return false; 2033 } 2034 } else if (!Constructor->isDependentContext() && 2035 !Constructor->isDelegatingConstructor()) { 2036 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2037 2038 // Skip detailed checking if we have enough initializers, and we would 2039 // allow at most one initializer per member. 2040 bool AnyAnonStructUnionMembers = false; 2041 unsigned Fields = 0; 2042 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2043 E = RD->field_end(); I != E; ++I, ++Fields) { 2044 if (I->isAnonymousStructOrUnion()) { 2045 AnyAnonStructUnionMembers = true; 2046 break; 2047 } 2048 } 2049 // DR1460: 2050 // - if the class is a union-like class, but is not a union, for each of 2051 // its anonymous union members having variant members, exactly one of 2052 // them shall be initialized; 2053 if (AnyAnonStructUnionMembers || 2054 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2055 // Check initialization of non-static data members. Base classes are 2056 // always initialized so do not need to be checked. Dependent bases 2057 // might not have initializers in the member initializer list. 2058 llvm::SmallSet<Decl*, 16> Inits; 2059 for (const auto *I: Constructor->inits()) { 2060 if (FieldDecl *FD = I->getMember()) 2061 Inits.insert(FD); 2062 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2063 Inits.insert(ID->chain_begin(), ID->chain_end()); 2064 } 2065 2066 bool Diagnosed = false; 2067 for (auto *I : RD->fields()) 2068 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2069 if (Diagnosed) 2070 return false; 2071 } 2072 } 2073 } else { 2074 if (ReturnStmts.empty()) { 2075 // C++1y doesn't require constexpr functions to contain a 'return' 2076 // statement. We still do, unless the return type might be void, because 2077 // otherwise if there's no return statement, the function cannot 2078 // be used in a core constant expression. 2079 bool OK = getLangOpts().CPlusPlus14 && 2080 (Dcl->getReturnType()->isVoidType() || 2081 Dcl->getReturnType()->isDependentType()); 2082 Diag(Dcl->getLocation(), 2083 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2084 : diag::err_constexpr_body_no_return); 2085 if (!OK) 2086 return false; 2087 } else if (ReturnStmts.size() > 1) { 2088 Diag(ReturnStmts.back(), 2089 getLangOpts().CPlusPlus14 2090 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2091 : diag::ext_constexpr_body_multiple_return); 2092 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2093 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2094 } 2095 } 2096 2097 // C++11 [dcl.constexpr]p5: 2098 // if no function argument values exist such that the function invocation 2099 // substitution would produce a constant expression, the program is 2100 // ill-formed; no diagnostic required. 2101 // C++11 [dcl.constexpr]p3: 2102 // - every constructor call and implicit conversion used in initializing the 2103 // return value shall be one of those allowed in a constant expression. 2104 // C++11 [dcl.constexpr]p4: 2105 // - every constructor involved in initializing non-static data members and 2106 // base class sub-objects shall be a constexpr constructor. 2107 SmallVector<PartialDiagnosticAt, 8> Diags; 2108 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2109 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2110 << isa<CXXConstructorDecl>(Dcl); 2111 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2112 Diag(Diags[I].first, Diags[I].second); 2113 // Don't return false here: we allow this for compatibility in 2114 // system headers. 2115 } 2116 2117 return true; 2118 } 2119 2120 /// Get the class that is directly named by the current context. This is the 2121 /// class for which an unqualified-id in this scope could name a constructor 2122 /// or destructor. 2123 /// 2124 /// If the scope specifier denotes a class, this will be that class. 2125 /// If the scope specifier is empty, this will be the class whose 2126 /// member-specification we are currently within. Otherwise, there 2127 /// is no such class. 2128 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2129 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2130 2131 if (SS && SS->isInvalid()) 2132 return nullptr; 2133 2134 if (SS && SS->isNotEmpty()) { 2135 DeclContext *DC = computeDeclContext(*SS, true); 2136 return dyn_cast_or_null<CXXRecordDecl>(DC); 2137 } 2138 2139 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2140 } 2141 2142 /// isCurrentClassName - Determine whether the identifier II is the 2143 /// name of the class type currently being defined. In the case of 2144 /// nested classes, this will only return true if II is the name of 2145 /// the innermost class. 2146 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2147 const CXXScopeSpec *SS) { 2148 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2149 return CurDecl && &II == CurDecl->getIdentifier(); 2150 } 2151 2152 /// Determine whether the identifier II is a typo for the name of 2153 /// the class type currently being defined. If so, update it to the identifier 2154 /// that should have been used. 2155 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2156 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2157 2158 if (!getLangOpts().SpellChecking) 2159 return false; 2160 2161 CXXRecordDecl *CurDecl; 2162 if (SS && SS->isSet() && !SS->isInvalid()) { 2163 DeclContext *DC = computeDeclContext(*SS, true); 2164 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2165 } else 2166 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2167 2168 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2169 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2170 < II->getLength()) { 2171 II = CurDecl->getIdentifier(); 2172 return true; 2173 } 2174 2175 return false; 2176 } 2177 2178 /// Determine whether the given class is a base class of the given 2179 /// class, including looking at dependent bases. 2180 static bool findCircularInheritance(const CXXRecordDecl *Class, 2181 const CXXRecordDecl *Current) { 2182 SmallVector<const CXXRecordDecl*, 8> Queue; 2183 2184 Class = Class->getCanonicalDecl(); 2185 while (true) { 2186 for (const auto &I : Current->bases()) { 2187 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2188 if (!Base) 2189 continue; 2190 2191 Base = Base->getDefinition(); 2192 if (!Base) 2193 continue; 2194 2195 if (Base->getCanonicalDecl() == Class) 2196 return true; 2197 2198 Queue.push_back(Base); 2199 } 2200 2201 if (Queue.empty()) 2202 return false; 2203 2204 Current = Queue.pop_back_val(); 2205 } 2206 2207 return false; 2208 } 2209 2210 /// Check the validity of a C++ base class specifier. 2211 /// 2212 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2213 /// and returns NULL otherwise. 2214 CXXBaseSpecifier * 2215 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2216 SourceRange SpecifierRange, 2217 bool Virtual, AccessSpecifier Access, 2218 TypeSourceInfo *TInfo, 2219 SourceLocation EllipsisLoc) { 2220 QualType BaseType = TInfo->getType(); 2221 2222 // C++ [class.union]p1: 2223 // A union shall not have base classes. 2224 if (Class->isUnion()) { 2225 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2226 << SpecifierRange; 2227 return nullptr; 2228 } 2229 2230 if (EllipsisLoc.isValid() && 2231 !TInfo->getType()->containsUnexpandedParameterPack()) { 2232 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2233 << TInfo->getTypeLoc().getSourceRange(); 2234 EllipsisLoc = SourceLocation(); 2235 } 2236 2237 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2238 2239 if (BaseType->isDependentType()) { 2240 // Make sure that we don't have circular inheritance among our dependent 2241 // bases. For non-dependent bases, the check for completeness below handles 2242 // this. 2243 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2244 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2245 ((BaseDecl = BaseDecl->getDefinition()) && 2246 findCircularInheritance(Class, BaseDecl))) { 2247 Diag(BaseLoc, diag::err_circular_inheritance) 2248 << BaseType << Context.getTypeDeclType(Class); 2249 2250 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2251 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2252 << BaseType; 2253 2254 return nullptr; 2255 } 2256 } 2257 2258 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2259 Class->getTagKind() == TTK_Class, 2260 Access, TInfo, EllipsisLoc); 2261 } 2262 2263 // Base specifiers must be record types. 2264 if (!BaseType->isRecordType()) { 2265 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2266 return nullptr; 2267 } 2268 2269 // C++ [class.union]p1: 2270 // A union shall not be used as a base class. 2271 if (BaseType->isUnionType()) { 2272 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2273 return nullptr; 2274 } 2275 2276 // For the MS ABI, propagate DLL attributes to base class templates. 2277 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2278 if (Attr *ClassAttr = getDLLAttr(Class)) { 2279 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2280 BaseType->getAsCXXRecordDecl())) { 2281 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2282 BaseLoc); 2283 } 2284 } 2285 } 2286 2287 // C++ [class.derived]p2: 2288 // The class-name in a base-specifier shall not be an incompletely 2289 // defined class. 2290 if (RequireCompleteType(BaseLoc, BaseType, 2291 diag::err_incomplete_base_class, SpecifierRange)) { 2292 Class->setInvalidDecl(); 2293 return nullptr; 2294 } 2295 2296 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2297 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2298 assert(BaseDecl && "Record type has no declaration"); 2299 BaseDecl = BaseDecl->getDefinition(); 2300 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2301 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2302 assert(CXXBaseDecl && "Base type is not a C++ type"); 2303 2304 // Microsoft docs say: 2305 // "If a base-class has a code_seg attribute, derived classes must have the 2306 // same attribute." 2307 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2308 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2309 if ((DerivedCSA || BaseCSA) && 2310 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2311 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2312 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2313 << CXXBaseDecl; 2314 return nullptr; 2315 } 2316 2317 // A class which contains a flexible array member is not suitable for use as a 2318 // base class: 2319 // - If the layout determines that a base comes before another base, 2320 // the flexible array member would index into the subsequent base. 2321 // - If the layout determines that base comes before the derived class, 2322 // the flexible array member would index into the derived class. 2323 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2324 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2325 << CXXBaseDecl->getDeclName(); 2326 return nullptr; 2327 } 2328 2329 // C++ [class]p3: 2330 // If a class is marked final and it appears as a base-type-specifier in 2331 // base-clause, the program is ill-formed. 2332 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2333 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2334 << CXXBaseDecl->getDeclName() 2335 << FA->isSpelledAsSealed(); 2336 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2337 << CXXBaseDecl->getDeclName() << FA->getRange(); 2338 return nullptr; 2339 } 2340 2341 if (BaseDecl->isInvalidDecl()) 2342 Class->setInvalidDecl(); 2343 2344 // Create the base specifier. 2345 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2346 Class->getTagKind() == TTK_Class, 2347 Access, TInfo, EllipsisLoc); 2348 } 2349 2350 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2351 /// one entry in the base class list of a class specifier, for 2352 /// example: 2353 /// class foo : public bar, virtual private baz { 2354 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2355 BaseResult 2356 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2357 ParsedAttributes &Attributes, 2358 bool Virtual, AccessSpecifier Access, 2359 ParsedType basetype, SourceLocation BaseLoc, 2360 SourceLocation EllipsisLoc) { 2361 if (!classdecl) 2362 return true; 2363 2364 AdjustDeclIfTemplate(classdecl); 2365 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2366 if (!Class) 2367 return true; 2368 2369 // We haven't yet attached the base specifiers. 2370 Class->setIsParsingBaseSpecifiers(); 2371 2372 // We do not support any C++11 attributes on base-specifiers yet. 2373 // Diagnose any attributes we see. 2374 for (const ParsedAttr &AL : Attributes) { 2375 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2376 continue; 2377 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2378 ? (unsigned)diag::warn_unknown_attribute_ignored 2379 : (unsigned)diag::err_base_specifier_attribute) 2380 << AL.getName(); 2381 } 2382 2383 TypeSourceInfo *TInfo = nullptr; 2384 GetTypeFromParser(basetype, &TInfo); 2385 2386 if (EllipsisLoc.isInvalid() && 2387 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2388 UPPC_BaseType)) 2389 return true; 2390 2391 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2392 Virtual, Access, TInfo, 2393 EllipsisLoc)) 2394 return BaseSpec; 2395 else 2396 Class->setInvalidDecl(); 2397 2398 return true; 2399 } 2400 2401 /// Use small set to collect indirect bases. As this is only used 2402 /// locally, there's no need to abstract the small size parameter. 2403 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2404 2405 /// Recursively add the bases of Type. Don't add Type itself. 2406 static void 2407 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2408 const QualType &Type) 2409 { 2410 // Even though the incoming type is a base, it might not be 2411 // a class -- it could be a template parm, for instance. 2412 if (auto Rec = Type->getAs<RecordType>()) { 2413 auto Decl = Rec->getAsCXXRecordDecl(); 2414 2415 // Iterate over its bases. 2416 for (const auto &BaseSpec : Decl->bases()) { 2417 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2418 .getUnqualifiedType(); 2419 if (Set.insert(Base).second) 2420 // If we've not already seen it, recurse. 2421 NoteIndirectBases(Context, Set, Base); 2422 } 2423 } 2424 } 2425 2426 /// Performs the actual work of attaching the given base class 2427 /// specifiers to a C++ class. 2428 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2429 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2430 if (Bases.empty()) 2431 return false; 2432 2433 // Used to keep track of which base types we have already seen, so 2434 // that we can properly diagnose redundant direct base types. Note 2435 // that the key is always the unqualified canonical type of the base 2436 // class. 2437 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2438 2439 // Used to track indirect bases so we can see if a direct base is 2440 // ambiguous. 2441 IndirectBaseSet IndirectBaseTypes; 2442 2443 // Copy non-redundant base specifiers into permanent storage. 2444 unsigned NumGoodBases = 0; 2445 bool Invalid = false; 2446 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2447 QualType NewBaseType 2448 = Context.getCanonicalType(Bases[idx]->getType()); 2449 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2450 2451 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2452 if (KnownBase) { 2453 // C++ [class.mi]p3: 2454 // A class shall not be specified as a direct base class of a 2455 // derived class more than once. 2456 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2457 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2458 2459 // Delete the duplicate base class specifier; we're going to 2460 // overwrite its pointer later. 2461 Context.Deallocate(Bases[idx]); 2462 2463 Invalid = true; 2464 } else { 2465 // Okay, add this new base class. 2466 KnownBase = Bases[idx]; 2467 Bases[NumGoodBases++] = Bases[idx]; 2468 2469 // Note this base's direct & indirect bases, if there could be ambiguity. 2470 if (Bases.size() > 1) 2471 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2472 2473 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2474 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2475 if (Class->isInterface() && 2476 (!RD->isInterfaceLike() || 2477 KnownBase->getAccessSpecifier() != AS_public)) { 2478 // The Microsoft extension __interface does not permit bases that 2479 // are not themselves public interfaces. 2480 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2481 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2482 << RD->getSourceRange(); 2483 Invalid = true; 2484 } 2485 if (RD->hasAttr<WeakAttr>()) 2486 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2487 } 2488 } 2489 } 2490 2491 // Attach the remaining base class specifiers to the derived class. 2492 Class->setBases(Bases.data(), NumGoodBases); 2493 2494 // Check that the only base classes that are duplicate are virtual. 2495 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2496 // Check whether this direct base is inaccessible due to ambiguity. 2497 QualType BaseType = Bases[idx]->getType(); 2498 2499 // Skip all dependent types in templates being used as base specifiers. 2500 // Checks below assume that the base specifier is a CXXRecord. 2501 if (BaseType->isDependentType()) 2502 continue; 2503 2504 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2505 .getUnqualifiedType(); 2506 2507 if (IndirectBaseTypes.count(CanonicalBase)) { 2508 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2509 /*DetectVirtual=*/true); 2510 bool found 2511 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2512 assert(found); 2513 (void)found; 2514 2515 if (Paths.isAmbiguous(CanonicalBase)) 2516 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2517 << BaseType << getAmbiguousPathsDisplayString(Paths) 2518 << Bases[idx]->getSourceRange(); 2519 else 2520 assert(Bases[idx]->isVirtual()); 2521 } 2522 2523 // Delete the base class specifier, since its data has been copied 2524 // into the CXXRecordDecl. 2525 Context.Deallocate(Bases[idx]); 2526 } 2527 2528 return Invalid; 2529 } 2530 2531 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2532 /// class, after checking whether there are any duplicate base 2533 /// classes. 2534 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2535 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2536 if (!ClassDecl || Bases.empty()) 2537 return; 2538 2539 AdjustDeclIfTemplate(ClassDecl); 2540 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2541 } 2542 2543 /// Determine whether the type \p Derived is a C++ class that is 2544 /// derived from the type \p Base. 2545 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2546 if (!getLangOpts().CPlusPlus) 2547 return false; 2548 2549 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2550 if (!DerivedRD) 2551 return false; 2552 2553 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2554 if (!BaseRD) 2555 return false; 2556 2557 // If either the base or the derived type is invalid, don't try to 2558 // check whether one is derived from the other. 2559 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2560 return false; 2561 2562 // FIXME: In a modules build, do we need the entire path to be visible for us 2563 // to be able to use the inheritance relationship? 2564 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2565 return false; 2566 2567 return DerivedRD->isDerivedFrom(BaseRD); 2568 } 2569 2570 /// Determine whether the type \p Derived is a C++ class that is 2571 /// derived from the type \p Base. 2572 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2573 CXXBasePaths &Paths) { 2574 if (!getLangOpts().CPlusPlus) 2575 return false; 2576 2577 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2578 if (!DerivedRD) 2579 return false; 2580 2581 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2582 if (!BaseRD) 2583 return false; 2584 2585 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2586 return false; 2587 2588 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2589 } 2590 2591 static void BuildBasePathArray(const CXXBasePath &Path, 2592 CXXCastPath &BasePathArray) { 2593 // We first go backward and check if we have a virtual base. 2594 // FIXME: It would be better if CXXBasePath had the base specifier for 2595 // the nearest virtual base. 2596 unsigned Start = 0; 2597 for (unsigned I = Path.size(); I != 0; --I) { 2598 if (Path[I - 1].Base->isVirtual()) { 2599 Start = I - 1; 2600 break; 2601 } 2602 } 2603 2604 // Now add all bases. 2605 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2606 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2607 } 2608 2609 2610 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2611 CXXCastPath &BasePathArray) { 2612 assert(BasePathArray.empty() && "Base path array must be empty!"); 2613 assert(Paths.isRecordingPaths() && "Must record paths!"); 2614 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2615 } 2616 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2617 /// conversion (where Derived and Base are class types) is 2618 /// well-formed, meaning that the conversion is unambiguous (and 2619 /// that all of the base classes are accessible). Returns true 2620 /// and emits a diagnostic if the code is ill-formed, returns false 2621 /// otherwise. Loc is the location where this routine should point to 2622 /// if there is an error, and Range is the source range to highlight 2623 /// if there is an error. 2624 /// 2625 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2626 /// diagnostic for the respective type of error will be suppressed, but the 2627 /// check for ill-formed code will still be performed. 2628 bool 2629 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2630 unsigned InaccessibleBaseID, 2631 unsigned AmbigiousBaseConvID, 2632 SourceLocation Loc, SourceRange Range, 2633 DeclarationName Name, 2634 CXXCastPath *BasePath, 2635 bool IgnoreAccess) { 2636 // First, determine whether the path from Derived to Base is 2637 // ambiguous. This is slightly more expensive than checking whether 2638 // the Derived to Base conversion exists, because here we need to 2639 // explore multiple paths to determine if there is an ambiguity. 2640 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2641 /*DetectVirtual=*/false); 2642 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2643 if (!DerivationOkay) 2644 return true; 2645 2646 const CXXBasePath *Path = nullptr; 2647 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2648 Path = &Paths.front(); 2649 2650 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2651 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2652 // user to access such bases. 2653 if (!Path && getLangOpts().MSVCCompat) { 2654 for (const CXXBasePath &PossiblePath : Paths) { 2655 if (PossiblePath.size() == 1) { 2656 Path = &PossiblePath; 2657 if (AmbigiousBaseConvID) 2658 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2659 << Base << Derived << Range; 2660 break; 2661 } 2662 } 2663 } 2664 2665 if (Path) { 2666 if (!IgnoreAccess) { 2667 // Check that the base class can be accessed. 2668 switch ( 2669 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2670 case AR_inaccessible: 2671 return true; 2672 case AR_accessible: 2673 case AR_dependent: 2674 case AR_delayed: 2675 break; 2676 } 2677 } 2678 2679 // Build a base path if necessary. 2680 if (BasePath) 2681 ::BuildBasePathArray(*Path, *BasePath); 2682 return false; 2683 } 2684 2685 if (AmbigiousBaseConvID) { 2686 // We know that the derived-to-base conversion is ambiguous, and 2687 // we're going to produce a diagnostic. Perform the derived-to-base 2688 // search just one more time to compute all of the possible paths so 2689 // that we can print them out. This is more expensive than any of 2690 // the previous derived-to-base checks we've done, but at this point 2691 // performance isn't as much of an issue. 2692 Paths.clear(); 2693 Paths.setRecordingPaths(true); 2694 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2695 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2696 (void)StillOkay; 2697 2698 // Build up a textual representation of the ambiguous paths, e.g., 2699 // D -> B -> A, that will be used to illustrate the ambiguous 2700 // conversions in the diagnostic. We only print one of the paths 2701 // to each base class subobject. 2702 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2703 2704 Diag(Loc, AmbigiousBaseConvID) 2705 << Derived << Base << PathDisplayStr << Range << Name; 2706 } 2707 return true; 2708 } 2709 2710 bool 2711 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2712 SourceLocation Loc, SourceRange Range, 2713 CXXCastPath *BasePath, 2714 bool IgnoreAccess) { 2715 return CheckDerivedToBaseConversion( 2716 Derived, Base, diag::err_upcast_to_inaccessible_base, 2717 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2718 BasePath, IgnoreAccess); 2719 } 2720 2721 2722 /// Builds a string representing ambiguous paths from a 2723 /// specific derived class to different subobjects of the same base 2724 /// class. 2725 /// 2726 /// This function builds a string that can be used in error messages 2727 /// to show the different paths that one can take through the 2728 /// inheritance hierarchy to go from the derived class to different 2729 /// subobjects of a base class. The result looks something like this: 2730 /// @code 2731 /// struct D -> struct B -> struct A 2732 /// struct D -> struct C -> struct A 2733 /// @endcode 2734 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2735 std::string PathDisplayStr; 2736 std::set<unsigned> DisplayedPaths; 2737 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2738 Path != Paths.end(); ++Path) { 2739 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2740 // We haven't displayed a path to this particular base 2741 // class subobject yet. 2742 PathDisplayStr += "\n "; 2743 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2744 for (CXXBasePath::const_iterator Element = Path->begin(); 2745 Element != Path->end(); ++Element) 2746 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2747 } 2748 } 2749 2750 return PathDisplayStr; 2751 } 2752 2753 //===----------------------------------------------------------------------===// 2754 // C++ class member Handling 2755 //===----------------------------------------------------------------------===// 2756 2757 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2758 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2759 SourceLocation ColonLoc, 2760 const ParsedAttributesView &Attrs) { 2761 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2762 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2763 ASLoc, ColonLoc); 2764 CurContext->addHiddenDecl(ASDecl); 2765 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2766 } 2767 2768 /// CheckOverrideControl - Check C++11 override control semantics. 2769 void Sema::CheckOverrideControl(NamedDecl *D) { 2770 if (D->isInvalidDecl()) 2771 return; 2772 2773 // We only care about "override" and "final" declarations. 2774 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2775 return; 2776 2777 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2778 2779 // We can't check dependent instance methods. 2780 if (MD && MD->isInstance() && 2781 (MD->getParent()->hasAnyDependentBases() || 2782 MD->getType()->isDependentType())) 2783 return; 2784 2785 if (MD && !MD->isVirtual()) { 2786 // If we have a non-virtual method, check if if hides a virtual method. 2787 // (In that case, it's most likely the method has the wrong type.) 2788 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2789 FindHiddenVirtualMethods(MD, OverloadedMethods); 2790 2791 if (!OverloadedMethods.empty()) { 2792 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2793 Diag(OA->getLocation(), 2794 diag::override_keyword_hides_virtual_member_function) 2795 << "override" << (OverloadedMethods.size() > 1); 2796 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2797 Diag(FA->getLocation(), 2798 diag::override_keyword_hides_virtual_member_function) 2799 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2800 << (OverloadedMethods.size() > 1); 2801 } 2802 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2803 MD->setInvalidDecl(); 2804 return; 2805 } 2806 // Fall through into the general case diagnostic. 2807 // FIXME: We might want to attempt typo correction here. 2808 } 2809 2810 if (!MD || !MD->isVirtual()) { 2811 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2812 Diag(OA->getLocation(), 2813 diag::override_keyword_only_allowed_on_virtual_member_functions) 2814 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2815 D->dropAttr<OverrideAttr>(); 2816 } 2817 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2818 Diag(FA->getLocation(), 2819 diag::override_keyword_only_allowed_on_virtual_member_functions) 2820 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2821 << FixItHint::CreateRemoval(FA->getLocation()); 2822 D->dropAttr<FinalAttr>(); 2823 } 2824 return; 2825 } 2826 2827 // C++11 [class.virtual]p5: 2828 // If a function is marked with the virt-specifier override and 2829 // does not override a member function of a base class, the program is 2830 // ill-formed. 2831 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2832 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2833 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2834 << MD->getDeclName(); 2835 } 2836 2837 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2838 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2839 return; 2840 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2841 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2842 return; 2843 2844 SourceLocation Loc = MD->getLocation(); 2845 SourceLocation SpellingLoc = Loc; 2846 if (getSourceManager().isMacroArgExpansion(Loc)) 2847 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2848 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2849 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2850 return; 2851 2852 if (MD->size_overridden_methods() > 0) { 2853 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2854 ? diag::warn_destructor_marked_not_override_overriding 2855 : diag::warn_function_marked_not_override_overriding; 2856 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2857 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2858 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2859 } 2860 } 2861 2862 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2863 /// function overrides a virtual member function marked 'final', according to 2864 /// C++11 [class.virtual]p4. 2865 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2866 const CXXMethodDecl *Old) { 2867 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2868 if (!FA) 2869 return false; 2870 2871 Diag(New->getLocation(), diag::err_final_function_overridden) 2872 << New->getDeclName() 2873 << FA->isSpelledAsSealed(); 2874 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2875 return true; 2876 } 2877 2878 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2879 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2880 // FIXME: Destruction of ObjC lifetime types has side-effects. 2881 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2882 return !RD->isCompleteDefinition() || 2883 !RD->hasTrivialDefaultConstructor() || 2884 !RD->hasTrivialDestructor(); 2885 return false; 2886 } 2887 2888 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 2889 ParsedAttributesView::const_iterator Itr = 2890 llvm::find_if(list, [](const ParsedAttr &AL) { 2891 return AL.isDeclspecPropertyAttribute(); 2892 }); 2893 if (Itr != list.end()) 2894 return &*Itr; 2895 return nullptr; 2896 } 2897 2898 // Check if there is a field shadowing. 2899 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2900 DeclarationName FieldName, 2901 const CXXRecordDecl *RD, 2902 bool DeclIsField) { 2903 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2904 return; 2905 2906 // To record a shadowed field in a base 2907 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2908 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2909 CXXBasePath &Path) { 2910 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2911 // Record an ambiguous path directly 2912 if (Bases.find(Base) != Bases.end()) 2913 return true; 2914 for (const auto Field : Base->lookup(FieldName)) { 2915 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2916 Field->getAccess() != AS_private) { 2917 assert(Field->getAccess() != AS_none); 2918 assert(Bases.find(Base) == Bases.end()); 2919 Bases[Base] = Field; 2920 return true; 2921 } 2922 } 2923 return false; 2924 }; 2925 2926 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2927 /*DetectVirtual=*/true); 2928 if (!RD->lookupInBases(FieldShadowed, Paths)) 2929 return; 2930 2931 for (const auto &P : Paths) { 2932 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2933 auto It = Bases.find(Base); 2934 // Skip duplicated bases 2935 if (It == Bases.end()) 2936 continue; 2937 auto BaseField = It->second; 2938 assert(BaseField->getAccess() != AS_private); 2939 if (AS_none != 2940 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2941 Diag(Loc, diag::warn_shadow_field) 2942 << FieldName << RD << Base << DeclIsField; 2943 Diag(BaseField->getLocation(), diag::note_shadow_field); 2944 Bases.erase(It); 2945 } 2946 } 2947 } 2948 2949 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2950 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2951 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2952 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2953 /// present (but parsing it has been deferred). 2954 NamedDecl * 2955 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2956 MultiTemplateParamsArg TemplateParameterLists, 2957 Expr *BW, const VirtSpecifiers &VS, 2958 InClassInitStyle InitStyle) { 2959 const DeclSpec &DS = D.getDeclSpec(); 2960 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2961 DeclarationName Name = NameInfo.getName(); 2962 SourceLocation Loc = NameInfo.getLoc(); 2963 2964 // For anonymous bitfields, the location should point to the type. 2965 if (Loc.isInvalid()) 2966 Loc = D.getBeginLoc(); 2967 2968 Expr *BitWidth = static_cast<Expr*>(BW); 2969 2970 assert(isa<CXXRecordDecl>(CurContext)); 2971 assert(!DS.isFriendSpecified()); 2972 2973 bool isFunc = D.isDeclarationOfFunction(); 2974 const ParsedAttr *MSPropertyAttr = 2975 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 2976 2977 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2978 // The Microsoft extension __interface only permits public member functions 2979 // and prohibits constructors, destructors, operators, non-public member 2980 // functions, static methods and data members. 2981 unsigned InvalidDecl; 2982 bool ShowDeclName = true; 2983 if (!isFunc && 2984 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2985 InvalidDecl = 0; 2986 else if (!isFunc) 2987 InvalidDecl = 1; 2988 else if (AS != AS_public) 2989 InvalidDecl = 2; 2990 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2991 InvalidDecl = 3; 2992 else switch (Name.getNameKind()) { 2993 case DeclarationName::CXXConstructorName: 2994 InvalidDecl = 4; 2995 ShowDeclName = false; 2996 break; 2997 2998 case DeclarationName::CXXDestructorName: 2999 InvalidDecl = 5; 3000 ShowDeclName = false; 3001 break; 3002 3003 case DeclarationName::CXXOperatorName: 3004 case DeclarationName::CXXConversionFunctionName: 3005 InvalidDecl = 6; 3006 break; 3007 3008 default: 3009 InvalidDecl = 0; 3010 break; 3011 } 3012 3013 if (InvalidDecl) { 3014 if (ShowDeclName) 3015 Diag(Loc, diag::err_invalid_member_in_interface) 3016 << (InvalidDecl-1) << Name; 3017 else 3018 Diag(Loc, diag::err_invalid_member_in_interface) 3019 << (InvalidDecl-1) << ""; 3020 return nullptr; 3021 } 3022 } 3023 3024 // C++ 9.2p6: A member shall not be declared to have automatic storage 3025 // duration (auto, register) or with the extern storage-class-specifier. 3026 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3027 // data members and cannot be applied to names declared const or static, 3028 // and cannot be applied to reference members. 3029 switch (DS.getStorageClassSpec()) { 3030 case DeclSpec::SCS_unspecified: 3031 case DeclSpec::SCS_typedef: 3032 case DeclSpec::SCS_static: 3033 break; 3034 case DeclSpec::SCS_mutable: 3035 if (isFunc) { 3036 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3037 3038 // FIXME: It would be nicer if the keyword was ignored only for this 3039 // declarator. Otherwise we could get follow-up errors. 3040 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3041 } 3042 break; 3043 default: 3044 Diag(DS.getStorageClassSpecLoc(), 3045 diag::err_storageclass_invalid_for_member); 3046 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3047 break; 3048 } 3049 3050 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3051 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3052 !isFunc); 3053 3054 if (DS.isConstexprSpecified() && isInstField) { 3055 SemaDiagnosticBuilder B = 3056 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3057 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3058 if (InitStyle == ICIS_NoInit) { 3059 B << 0 << 0; 3060 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3061 B << FixItHint::CreateRemoval(ConstexprLoc); 3062 else { 3063 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3064 D.getMutableDeclSpec().ClearConstexprSpec(); 3065 const char *PrevSpec; 3066 unsigned DiagID; 3067 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3068 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3069 (void)Failed; 3070 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3071 } 3072 } else { 3073 B << 1; 3074 const char *PrevSpec; 3075 unsigned DiagID; 3076 if (D.getMutableDeclSpec().SetStorageClassSpec( 3077 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3078 Context.getPrintingPolicy())) { 3079 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3080 "This is the only DeclSpec that should fail to be applied"); 3081 B << 1; 3082 } else { 3083 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3084 isInstField = false; 3085 } 3086 } 3087 } 3088 3089 NamedDecl *Member; 3090 if (isInstField) { 3091 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3092 3093 // Data members must have identifiers for names. 3094 if (!Name.isIdentifier()) { 3095 Diag(Loc, diag::err_bad_variable_name) 3096 << Name; 3097 return nullptr; 3098 } 3099 3100 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3101 3102 // Member field could not be with "template" keyword. 3103 // So TemplateParameterLists should be empty in this case. 3104 if (TemplateParameterLists.size()) { 3105 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3106 if (TemplateParams->size()) { 3107 // There is no such thing as a member field template. 3108 Diag(D.getIdentifierLoc(), diag::err_template_member) 3109 << II 3110 << SourceRange(TemplateParams->getTemplateLoc(), 3111 TemplateParams->getRAngleLoc()); 3112 } else { 3113 // There is an extraneous 'template<>' for this member. 3114 Diag(TemplateParams->getTemplateLoc(), 3115 diag::err_template_member_noparams) 3116 << II 3117 << SourceRange(TemplateParams->getTemplateLoc(), 3118 TemplateParams->getRAngleLoc()); 3119 } 3120 return nullptr; 3121 } 3122 3123 if (SS.isSet() && !SS.isInvalid()) { 3124 // The user provided a superfluous scope specifier inside a class 3125 // definition: 3126 // 3127 // class X { 3128 // int X::member; 3129 // }; 3130 if (DeclContext *DC = computeDeclContext(SS, false)) 3131 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3132 D.getName().getKind() == 3133 UnqualifiedIdKind::IK_TemplateId); 3134 else 3135 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3136 << Name << SS.getRange(); 3137 3138 SS.clear(); 3139 } 3140 3141 if (MSPropertyAttr) { 3142 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3143 BitWidth, InitStyle, AS, *MSPropertyAttr); 3144 if (!Member) 3145 return nullptr; 3146 isInstField = false; 3147 } else { 3148 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3149 BitWidth, InitStyle, AS); 3150 if (!Member) 3151 return nullptr; 3152 } 3153 3154 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3155 } else { 3156 Member = HandleDeclarator(S, D, TemplateParameterLists); 3157 if (!Member) 3158 return nullptr; 3159 3160 // Non-instance-fields can't have a bitfield. 3161 if (BitWidth) { 3162 if (Member->isInvalidDecl()) { 3163 // don't emit another diagnostic. 3164 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3165 // C++ 9.6p3: A bit-field shall not be a static member. 3166 // "static member 'A' cannot be a bit-field" 3167 Diag(Loc, diag::err_static_not_bitfield) 3168 << Name << BitWidth->getSourceRange(); 3169 } else if (isa<TypedefDecl>(Member)) { 3170 // "typedef member 'x' cannot be a bit-field" 3171 Diag(Loc, diag::err_typedef_not_bitfield) 3172 << Name << BitWidth->getSourceRange(); 3173 } else { 3174 // A function typedef ("typedef int f(); f a;"). 3175 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3176 Diag(Loc, diag::err_not_integral_type_bitfield) 3177 << Name << cast<ValueDecl>(Member)->getType() 3178 << BitWidth->getSourceRange(); 3179 } 3180 3181 BitWidth = nullptr; 3182 Member->setInvalidDecl(); 3183 } 3184 3185 NamedDecl *NonTemplateMember = Member; 3186 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3187 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3188 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3189 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3190 3191 Member->setAccess(AS); 3192 3193 // If we have declared a member function template or static data member 3194 // template, set the access of the templated declaration as well. 3195 if (NonTemplateMember != Member) 3196 NonTemplateMember->setAccess(AS); 3197 3198 // C++ [temp.deduct.guide]p3: 3199 // A deduction guide [...] for a member class template [shall be 3200 // declared] with the same access [as the template]. 3201 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3202 auto *TD = DG->getDeducedTemplate(); 3203 // Access specifiers are only meaningful if both the template and the 3204 // deduction guide are from the same scope. 3205 if (AS != TD->getAccess() && 3206 TD->getDeclContext()->getRedeclContext()->Equals( 3207 DG->getDeclContext()->getRedeclContext())) { 3208 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3209 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3210 << TD->getAccess(); 3211 const AccessSpecDecl *LastAccessSpec = nullptr; 3212 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3213 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3214 LastAccessSpec = AccessSpec; 3215 } 3216 assert(LastAccessSpec && "differing access with no access specifier"); 3217 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3218 << AS; 3219 } 3220 } 3221 } 3222 3223 if (VS.isOverrideSpecified()) 3224 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3225 if (VS.isFinalSpecified()) 3226 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3227 VS.isFinalSpelledSealed())); 3228 3229 if (VS.getLastLocation().isValid()) { 3230 // Update the end location of a method that has a virt-specifiers. 3231 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3232 MD->setRangeEnd(VS.getLastLocation()); 3233 } 3234 3235 CheckOverrideControl(Member); 3236 3237 assert((Name || isInstField) && "No identifier for non-field ?"); 3238 3239 if (isInstField) { 3240 FieldDecl *FD = cast<FieldDecl>(Member); 3241 FieldCollector->Add(FD); 3242 3243 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3244 // Remember all explicit private FieldDecls that have a name, no side 3245 // effects and are not part of a dependent type declaration. 3246 if (!FD->isImplicit() && FD->getDeclName() && 3247 FD->getAccess() == AS_private && 3248 !FD->hasAttr<UnusedAttr>() && 3249 !FD->getParent()->isDependentContext() && 3250 !InitializationHasSideEffects(*FD)) 3251 UnusedPrivateFields.insert(FD); 3252 } 3253 } 3254 3255 return Member; 3256 } 3257 3258 namespace { 3259 class UninitializedFieldVisitor 3260 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3261 Sema &S; 3262 // List of Decls to generate a warning on. Also remove Decls that become 3263 // initialized. 3264 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3265 // List of base classes of the record. Classes are removed after their 3266 // initializers. 3267 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3268 // Vector of decls to be removed from the Decl set prior to visiting the 3269 // nodes. These Decls may have been initialized in the prior initializer. 3270 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3271 // If non-null, add a note to the warning pointing back to the constructor. 3272 const CXXConstructorDecl *Constructor; 3273 // Variables to hold state when processing an initializer list. When 3274 // InitList is true, special case initialization of FieldDecls matching 3275 // InitListFieldDecl. 3276 bool InitList; 3277 FieldDecl *InitListFieldDecl; 3278 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3279 3280 public: 3281 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3282 UninitializedFieldVisitor(Sema &S, 3283 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3284 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3285 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3286 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3287 3288 // Returns true if the use of ME is not an uninitialized use. 3289 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3290 bool CheckReferenceOnly) { 3291 llvm::SmallVector<FieldDecl*, 4> Fields; 3292 bool ReferenceField = false; 3293 while (ME) { 3294 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3295 if (!FD) 3296 return false; 3297 Fields.push_back(FD); 3298 if (FD->getType()->isReferenceType()) 3299 ReferenceField = true; 3300 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3301 } 3302 3303 // Binding a reference to an uninitialized field is not an 3304 // uninitialized use. 3305 if (CheckReferenceOnly && !ReferenceField) 3306 return true; 3307 3308 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3309 // Discard the first field since it is the field decl that is being 3310 // initialized. 3311 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3312 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3313 } 3314 3315 for (auto UsedIter = UsedFieldIndex.begin(), 3316 UsedEnd = UsedFieldIndex.end(), 3317 OrigIter = InitFieldIndex.begin(), 3318 OrigEnd = InitFieldIndex.end(); 3319 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3320 if (*UsedIter < *OrigIter) 3321 return true; 3322 if (*UsedIter > *OrigIter) 3323 break; 3324 } 3325 3326 return false; 3327 } 3328 3329 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3330 bool AddressOf) { 3331 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3332 return; 3333 3334 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3335 // or union. 3336 MemberExpr *FieldME = ME; 3337 3338 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3339 3340 Expr *Base = ME; 3341 while (MemberExpr *SubME = 3342 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3343 3344 if (isa<VarDecl>(SubME->getMemberDecl())) 3345 return; 3346 3347 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3348 if (!FD->isAnonymousStructOrUnion()) 3349 FieldME = SubME; 3350 3351 if (!FieldME->getType().isPODType(S.Context)) 3352 AllPODFields = false; 3353 3354 Base = SubME->getBase(); 3355 } 3356 3357 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3358 return; 3359 3360 if (AddressOf && AllPODFields) 3361 return; 3362 3363 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3364 3365 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3366 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3367 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3368 } 3369 3370 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3371 QualType T = BaseCast->getType(); 3372 if (T->isPointerType() && 3373 BaseClasses.count(T->getPointeeType())) { 3374 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3375 << T->getPointeeType() << FoundVD; 3376 } 3377 } 3378 } 3379 3380 if (!Decls.count(FoundVD)) 3381 return; 3382 3383 const bool IsReference = FoundVD->getType()->isReferenceType(); 3384 3385 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3386 // Special checking for initializer lists. 3387 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3388 return; 3389 } 3390 } else { 3391 // Prevent double warnings on use of unbounded references. 3392 if (CheckReferenceOnly && !IsReference) 3393 return; 3394 } 3395 3396 unsigned diag = IsReference 3397 ? diag::warn_reference_field_is_uninit 3398 : diag::warn_field_is_uninit; 3399 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3400 if (Constructor) 3401 S.Diag(Constructor->getLocation(), 3402 diag::note_uninit_in_this_constructor) 3403 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3404 3405 } 3406 3407 void HandleValue(Expr *E, bool AddressOf) { 3408 E = E->IgnoreParens(); 3409 3410 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3411 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3412 AddressOf /*AddressOf*/); 3413 return; 3414 } 3415 3416 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3417 Visit(CO->getCond()); 3418 HandleValue(CO->getTrueExpr(), AddressOf); 3419 HandleValue(CO->getFalseExpr(), AddressOf); 3420 return; 3421 } 3422 3423 if (BinaryConditionalOperator *BCO = 3424 dyn_cast<BinaryConditionalOperator>(E)) { 3425 Visit(BCO->getCond()); 3426 HandleValue(BCO->getFalseExpr(), AddressOf); 3427 return; 3428 } 3429 3430 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3431 HandleValue(OVE->getSourceExpr(), AddressOf); 3432 return; 3433 } 3434 3435 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3436 switch (BO->getOpcode()) { 3437 default: 3438 break; 3439 case(BO_PtrMemD): 3440 case(BO_PtrMemI): 3441 HandleValue(BO->getLHS(), AddressOf); 3442 Visit(BO->getRHS()); 3443 return; 3444 case(BO_Comma): 3445 Visit(BO->getLHS()); 3446 HandleValue(BO->getRHS(), AddressOf); 3447 return; 3448 } 3449 } 3450 3451 Visit(E); 3452 } 3453 3454 void CheckInitListExpr(InitListExpr *ILE) { 3455 InitFieldIndex.push_back(0); 3456 for (auto Child : ILE->children()) { 3457 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3458 CheckInitListExpr(SubList); 3459 } else { 3460 Visit(Child); 3461 } 3462 ++InitFieldIndex.back(); 3463 } 3464 InitFieldIndex.pop_back(); 3465 } 3466 3467 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3468 FieldDecl *Field, const Type *BaseClass) { 3469 // Remove Decls that may have been initialized in the previous 3470 // initializer. 3471 for (ValueDecl* VD : DeclsToRemove) 3472 Decls.erase(VD); 3473 DeclsToRemove.clear(); 3474 3475 Constructor = FieldConstructor; 3476 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3477 3478 if (ILE && Field) { 3479 InitList = true; 3480 InitListFieldDecl = Field; 3481 InitFieldIndex.clear(); 3482 CheckInitListExpr(ILE); 3483 } else { 3484 InitList = false; 3485 Visit(E); 3486 } 3487 3488 if (Field) 3489 Decls.erase(Field); 3490 if (BaseClass) 3491 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3492 } 3493 3494 void VisitMemberExpr(MemberExpr *ME) { 3495 // All uses of unbounded reference fields will warn. 3496 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3497 } 3498 3499 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3500 if (E->getCastKind() == CK_LValueToRValue) { 3501 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3502 return; 3503 } 3504 3505 Inherited::VisitImplicitCastExpr(E); 3506 } 3507 3508 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3509 if (E->getConstructor()->isCopyConstructor()) { 3510 Expr *ArgExpr = E->getArg(0); 3511 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3512 if (ILE->getNumInits() == 1) 3513 ArgExpr = ILE->getInit(0); 3514 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3515 if (ICE->getCastKind() == CK_NoOp) 3516 ArgExpr = ICE->getSubExpr(); 3517 HandleValue(ArgExpr, false /*AddressOf*/); 3518 return; 3519 } 3520 Inherited::VisitCXXConstructExpr(E); 3521 } 3522 3523 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3524 Expr *Callee = E->getCallee(); 3525 if (isa<MemberExpr>(Callee)) { 3526 HandleValue(Callee, false /*AddressOf*/); 3527 for (auto Arg : E->arguments()) 3528 Visit(Arg); 3529 return; 3530 } 3531 3532 Inherited::VisitCXXMemberCallExpr(E); 3533 } 3534 3535 void VisitCallExpr(CallExpr *E) { 3536 // Treat std::move as a use. 3537 if (E->isCallToStdMove()) { 3538 HandleValue(E->getArg(0), /*AddressOf=*/false); 3539 return; 3540 } 3541 3542 Inherited::VisitCallExpr(E); 3543 } 3544 3545 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3546 Expr *Callee = E->getCallee(); 3547 3548 if (isa<UnresolvedLookupExpr>(Callee)) 3549 return Inherited::VisitCXXOperatorCallExpr(E); 3550 3551 Visit(Callee); 3552 for (auto Arg : E->arguments()) 3553 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3554 } 3555 3556 void VisitBinaryOperator(BinaryOperator *E) { 3557 // If a field assignment is detected, remove the field from the 3558 // uninitiailized field set. 3559 if (E->getOpcode() == BO_Assign) 3560 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3561 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3562 if (!FD->getType()->isReferenceType()) 3563 DeclsToRemove.push_back(FD); 3564 3565 if (E->isCompoundAssignmentOp()) { 3566 HandleValue(E->getLHS(), false /*AddressOf*/); 3567 Visit(E->getRHS()); 3568 return; 3569 } 3570 3571 Inherited::VisitBinaryOperator(E); 3572 } 3573 3574 void VisitUnaryOperator(UnaryOperator *E) { 3575 if (E->isIncrementDecrementOp()) { 3576 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3577 return; 3578 } 3579 if (E->getOpcode() == UO_AddrOf) { 3580 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3581 HandleValue(ME->getBase(), true /*AddressOf*/); 3582 return; 3583 } 3584 } 3585 3586 Inherited::VisitUnaryOperator(E); 3587 } 3588 }; 3589 3590 // Diagnose value-uses of fields to initialize themselves, e.g. 3591 // foo(foo) 3592 // where foo is not also a parameter to the constructor. 3593 // Also diagnose across field uninitialized use such as 3594 // x(y), y(x) 3595 // TODO: implement -Wuninitialized and fold this into that framework. 3596 static void DiagnoseUninitializedFields( 3597 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3598 3599 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3600 Constructor->getLocation())) { 3601 return; 3602 } 3603 3604 if (Constructor->isInvalidDecl()) 3605 return; 3606 3607 const CXXRecordDecl *RD = Constructor->getParent(); 3608 3609 if (RD->getDescribedClassTemplate()) 3610 return; 3611 3612 // Holds fields that are uninitialized. 3613 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3614 3615 // At the beginning, all fields are uninitialized. 3616 for (auto *I : RD->decls()) { 3617 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3618 UninitializedFields.insert(FD); 3619 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3620 UninitializedFields.insert(IFD->getAnonField()); 3621 } 3622 } 3623 3624 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3625 for (auto I : RD->bases()) 3626 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3627 3628 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3629 return; 3630 3631 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3632 UninitializedFields, 3633 UninitializedBaseClasses); 3634 3635 for (const auto *FieldInit : Constructor->inits()) { 3636 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3637 break; 3638 3639 Expr *InitExpr = FieldInit->getInit(); 3640 if (!InitExpr) 3641 continue; 3642 3643 if (CXXDefaultInitExpr *Default = 3644 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3645 InitExpr = Default->getExpr(); 3646 if (!InitExpr) 3647 continue; 3648 // In class initializers will point to the constructor. 3649 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3650 FieldInit->getAnyMember(), 3651 FieldInit->getBaseClass()); 3652 } else { 3653 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3654 FieldInit->getAnyMember(), 3655 FieldInit->getBaseClass()); 3656 } 3657 } 3658 } 3659 } // namespace 3660 3661 /// Enter a new C++ default initializer scope. After calling this, the 3662 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3663 /// parsing or instantiating the initializer failed. 3664 void Sema::ActOnStartCXXInClassMemberInitializer() { 3665 // Create a synthetic function scope to represent the call to the constructor 3666 // that notionally surrounds a use of this initializer. 3667 PushFunctionScope(); 3668 } 3669 3670 /// This is invoked after parsing an in-class initializer for a 3671 /// non-static C++ class member, and after instantiating an in-class initializer 3672 /// in a class template. Such actions are deferred until the class is complete. 3673 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3674 SourceLocation InitLoc, 3675 Expr *InitExpr) { 3676 // Pop the notional constructor scope we created earlier. 3677 PopFunctionScopeInfo(nullptr, D); 3678 3679 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3680 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3681 "must set init style when field is created"); 3682 3683 if (!InitExpr) { 3684 D->setInvalidDecl(); 3685 if (FD) 3686 FD->removeInClassInitializer(); 3687 return; 3688 } 3689 3690 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3691 FD->setInvalidDecl(); 3692 FD->removeInClassInitializer(); 3693 return; 3694 } 3695 3696 ExprResult Init = InitExpr; 3697 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3698 InitializedEntity Entity = 3699 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3700 InitializationKind Kind = 3701 FD->getInClassInitStyle() == ICIS_ListInit 3702 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3703 InitExpr->getBeginLoc(), 3704 InitExpr->getEndLoc()) 3705 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3706 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3707 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3708 if (Init.isInvalid()) { 3709 FD->setInvalidDecl(); 3710 return; 3711 } 3712 } 3713 3714 // C++11 [class.base.init]p7: 3715 // The initialization of each base and member constitutes a 3716 // full-expression. 3717 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3718 if (Init.isInvalid()) { 3719 FD->setInvalidDecl(); 3720 return; 3721 } 3722 3723 InitExpr = Init.get(); 3724 3725 FD->setInClassInitializer(InitExpr); 3726 } 3727 3728 /// Find the direct and/or virtual base specifiers that 3729 /// correspond to the given base type, for use in base initialization 3730 /// within a constructor. 3731 static bool FindBaseInitializer(Sema &SemaRef, 3732 CXXRecordDecl *ClassDecl, 3733 QualType BaseType, 3734 const CXXBaseSpecifier *&DirectBaseSpec, 3735 const CXXBaseSpecifier *&VirtualBaseSpec) { 3736 // First, check for a direct base class. 3737 DirectBaseSpec = nullptr; 3738 for (const auto &Base : ClassDecl->bases()) { 3739 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3740 // We found a direct base of this type. That's what we're 3741 // initializing. 3742 DirectBaseSpec = &Base; 3743 break; 3744 } 3745 } 3746 3747 // Check for a virtual base class. 3748 // FIXME: We might be able to short-circuit this if we know in advance that 3749 // there are no virtual bases. 3750 VirtualBaseSpec = nullptr; 3751 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3752 // We haven't found a base yet; search the class hierarchy for a 3753 // virtual base class. 3754 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3755 /*DetectVirtual=*/false); 3756 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3757 SemaRef.Context.getTypeDeclType(ClassDecl), 3758 BaseType, Paths)) { 3759 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3760 Path != Paths.end(); ++Path) { 3761 if (Path->back().Base->isVirtual()) { 3762 VirtualBaseSpec = Path->back().Base; 3763 break; 3764 } 3765 } 3766 } 3767 } 3768 3769 return DirectBaseSpec || VirtualBaseSpec; 3770 } 3771 3772 /// Handle a C++ member initializer using braced-init-list syntax. 3773 MemInitResult 3774 Sema::ActOnMemInitializer(Decl *ConstructorD, 3775 Scope *S, 3776 CXXScopeSpec &SS, 3777 IdentifierInfo *MemberOrBase, 3778 ParsedType TemplateTypeTy, 3779 const DeclSpec &DS, 3780 SourceLocation IdLoc, 3781 Expr *InitList, 3782 SourceLocation EllipsisLoc) { 3783 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3784 DS, IdLoc, InitList, 3785 EllipsisLoc); 3786 } 3787 3788 /// Handle a C++ member initializer using parentheses syntax. 3789 MemInitResult 3790 Sema::ActOnMemInitializer(Decl *ConstructorD, 3791 Scope *S, 3792 CXXScopeSpec &SS, 3793 IdentifierInfo *MemberOrBase, 3794 ParsedType TemplateTypeTy, 3795 const DeclSpec &DS, 3796 SourceLocation IdLoc, 3797 SourceLocation LParenLoc, 3798 ArrayRef<Expr *> Args, 3799 SourceLocation RParenLoc, 3800 SourceLocation EllipsisLoc) { 3801 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 3802 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3803 DS, IdLoc, List, EllipsisLoc); 3804 } 3805 3806 namespace { 3807 3808 // Callback to only accept typo corrections that can be a valid C++ member 3809 // intializer: either a non-static field member or a base class. 3810 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 3811 public: 3812 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3813 : ClassDecl(ClassDecl) {} 3814 3815 bool ValidateCandidate(const TypoCorrection &candidate) override { 3816 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3817 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3818 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3819 return isa<TypeDecl>(ND); 3820 } 3821 return false; 3822 } 3823 3824 std::unique_ptr<CorrectionCandidateCallback> clone() override { 3825 return llvm::make_unique<MemInitializerValidatorCCC>(*this); 3826 } 3827 3828 private: 3829 CXXRecordDecl *ClassDecl; 3830 }; 3831 3832 } 3833 3834 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 3835 CXXScopeSpec &SS, 3836 ParsedType TemplateTypeTy, 3837 IdentifierInfo *MemberOrBase) { 3838 if (SS.getScopeRep() || TemplateTypeTy) 3839 return nullptr; 3840 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3841 if (Result.empty()) 3842 return nullptr; 3843 ValueDecl *Member; 3844 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3845 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 3846 return Member; 3847 return nullptr; 3848 } 3849 3850 /// Handle a C++ member initializer. 3851 MemInitResult 3852 Sema::BuildMemInitializer(Decl *ConstructorD, 3853 Scope *S, 3854 CXXScopeSpec &SS, 3855 IdentifierInfo *MemberOrBase, 3856 ParsedType TemplateTypeTy, 3857 const DeclSpec &DS, 3858 SourceLocation IdLoc, 3859 Expr *Init, 3860 SourceLocation EllipsisLoc) { 3861 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3862 if (!Res.isUsable()) 3863 return true; 3864 Init = Res.get(); 3865 3866 if (!ConstructorD) 3867 return true; 3868 3869 AdjustDeclIfTemplate(ConstructorD); 3870 3871 CXXConstructorDecl *Constructor 3872 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3873 if (!Constructor) { 3874 // The user wrote a constructor initializer on a function that is 3875 // not a C++ constructor. Ignore the error for now, because we may 3876 // have more member initializers coming; we'll diagnose it just 3877 // once in ActOnMemInitializers. 3878 return true; 3879 } 3880 3881 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3882 3883 // C++ [class.base.init]p2: 3884 // Names in a mem-initializer-id are looked up in the scope of the 3885 // constructor's class and, if not found in that scope, are looked 3886 // up in the scope containing the constructor's definition. 3887 // [Note: if the constructor's class contains a member with the 3888 // same name as a direct or virtual base class of the class, a 3889 // mem-initializer-id naming the member or base class and composed 3890 // of a single identifier refers to the class member. A 3891 // mem-initializer-id for the hidden base class may be specified 3892 // using a qualified name. ] 3893 3894 // Look for a member, first. 3895 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 3896 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 3897 if (EllipsisLoc.isValid()) 3898 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3899 << MemberOrBase 3900 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3901 3902 return BuildMemberInitializer(Member, Init, IdLoc); 3903 } 3904 // It didn't name a member, so see if it names a class. 3905 QualType BaseType; 3906 TypeSourceInfo *TInfo = nullptr; 3907 3908 if (TemplateTypeTy) { 3909 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3910 if (BaseType.isNull()) 3911 return true; 3912 } else if (DS.getTypeSpecType() == TST_decltype) { 3913 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3914 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3915 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3916 return true; 3917 } else { 3918 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3919 LookupParsedName(R, S, &SS); 3920 3921 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3922 if (!TyD) { 3923 if (R.isAmbiguous()) return true; 3924 3925 // We don't want access-control diagnostics here. 3926 R.suppressDiagnostics(); 3927 3928 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3929 bool NotUnknownSpecialization = false; 3930 DeclContext *DC = computeDeclContext(SS, false); 3931 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3932 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3933 3934 if (!NotUnknownSpecialization) { 3935 // When the scope specifier can refer to a member of an unknown 3936 // specialization, we take it as a type name. 3937 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3938 SS.getWithLocInContext(Context), 3939 *MemberOrBase, IdLoc); 3940 if (BaseType.isNull()) 3941 return true; 3942 3943 TInfo = Context.CreateTypeSourceInfo(BaseType); 3944 DependentNameTypeLoc TL = 3945 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3946 if (!TL.isNull()) { 3947 TL.setNameLoc(IdLoc); 3948 TL.setElaboratedKeywordLoc(SourceLocation()); 3949 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3950 } 3951 3952 R.clear(); 3953 R.setLookupName(MemberOrBase); 3954 } 3955 } 3956 3957 // If no results were found, try to correct typos. 3958 TypoCorrection Corr; 3959 MemInitializerValidatorCCC CCC(ClassDecl); 3960 if (R.empty() && BaseType.isNull() && 3961 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3962 CCC, CTK_ErrorRecovery, ClassDecl))) { 3963 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3964 // We have found a non-static data member with a similar 3965 // name to what was typed; complain and initialize that 3966 // member. 3967 diagnoseTypo(Corr, 3968 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3969 << MemberOrBase << true); 3970 return BuildMemberInitializer(Member, Init, IdLoc); 3971 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3972 const CXXBaseSpecifier *DirectBaseSpec; 3973 const CXXBaseSpecifier *VirtualBaseSpec; 3974 if (FindBaseInitializer(*this, ClassDecl, 3975 Context.getTypeDeclType(Type), 3976 DirectBaseSpec, VirtualBaseSpec)) { 3977 // We have found a direct or virtual base class with a 3978 // similar name to what was typed; complain and initialize 3979 // that base class. 3980 diagnoseTypo(Corr, 3981 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3982 << MemberOrBase << false, 3983 PDiag() /*Suppress note, we provide our own.*/); 3984 3985 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3986 : VirtualBaseSpec; 3987 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 3988 << BaseSpec->getType() << BaseSpec->getSourceRange(); 3989 3990 TyD = Type; 3991 } 3992 } 3993 } 3994 3995 if (!TyD && BaseType.isNull()) { 3996 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3997 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3998 return true; 3999 } 4000 } 4001 4002 if (BaseType.isNull()) { 4003 BaseType = Context.getTypeDeclType(TyD); 4004 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4005 if (SS.isSet()) { 4006 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4007 BaseType); 4008 TInfo = Context.CreateTypeSourceInfo(BaseType); 4009 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4010 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4011 TL.setElaboratedKeywordLoc(SourceLocation()); 4012 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4013 } 4014 } 4015 } 4016 4017 if (!TInfo) 4018 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4019 4020 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4021 } 4022 4023 MemInitResult 4024 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4025 SourceLocation IdLoc) { 4026 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4027 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4028 assert((DirectMember || IndirectMember) && 4029 "Member must be a FieldDecl or IndirectFieldDecl"); 4030 4031 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4032 return true; 4033 4034 if (Member->isInvalidDecl()) 4035 return true; 4036 4037 MultiExprArg Args; 4038 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4039 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4040 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4041 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4042 } else { 4043 // Template instantiation doesn't reconstruct ParenListExprs for us. 4044 Args = Init; 4045 } 4046 4047 SourceRange InitRange = Init->getSourceRange(); 4048 4049 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4050 // Can't check initialization for a member of dependent type or when 4051 // any of the arguments are type-dependent expressions. 4052 DiscardCleanupsInEvaluationContext(); 4053 } else { 4054 bool InitList = false; 4055 if (isa<InitListExpr>(Init)) { 4056 InitList = true; 4057 Args = Init; 4058 } 4059 4060 // Initialize the member. 4061 InitializedEntity MemberEntity = 4062 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4063 : InitializedEntity::InitializeMember(IndirectMember, 4064 nullptr); 4065 InitializationKind Kind = 4066 InitList ? InitializationKind::CreateDirectList( 4067 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4068 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4069 InitRange.getEnd()); 4070 4071 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4072 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4073 nullptr); 4074 if (MemberInit.isInvalid()) 4075 return true; 4076 4077 // C++11 [class.base.init]p7: 4078 // The initialization of each base and member constitutes a 4079 // full-expression. 4080 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4081 /*DiscardedValue*/ false); 4082 if (MemberInit.isInvalid()) 4083 return true; 4084 4085 Init = MemberInit.get(); 4086 } 4087 4088 if (DirectMember) { 4089 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4090 InitRange.getBegin(), Init, 4091 InitRange.getEnd()); 4092 } else { 4093 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4094 InitRange.getBegin(), Init, 4095 InitRange.getEnd()); 4096 } 4097 } 4098 4099 MemInitResult 4100 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4101 CXXRecordDecl *ClassDecl) { 4102 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4103 if (!LangOpts.CPlusPlus11) 4104 return Diag(NameLoc, diag::err_delegating_ctor) 4105 << TInfo->getTypeLoc().getLocalSourceRange(); 4106 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4107 4108 bool InitList = true; 4109 MultiExprArg Args = Init; 4110 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4111 InitList = false; 4112 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4113 } 4114 4115 SourceRange InitRange = Init->getSourceRange(); 4116 // Initialize the object. 4117 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4118 QualType(ClassDecl->getTypeForDecl(), 0)); 4119 InitializationKind Kind = 4120 InitList ? InitializationKind::CreateDirectList( 4121 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4122 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4123 InitRange.getEnd()); 4124 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4125 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4126 Args, nullptr); 4127 if (DelegationInit.isInvalid()) 4128 return true; 4129 4130 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4131 "Delegating constructor with no target?"); 4132 4133 // C++11 [class.base.init]p7: 4134 // The initialization of each base and member constitutes a 4135 // full-expression. 4136 DelegationInit = ActOnFinishFullExpr( 4137 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4138 if (DelegationInit.isInvalid()) 4139 return true; 4140 4141 // If we are in a dependent context, template instantiation will 4142 // perform this type-checking again. Just save the arguments that we 4143 // received in a ParenListExpr. 4144 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4145 // of the information that we have about the base 4146 // initializer. However, deconstructing the ASTs is a dicey process, 4147 // and this approach is far more likely to get the corner cases right. 4148 if (CurContext->isDependentContext()) 4149 DelegationInit = Init; 4150 4151 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4152 DelegationInit.getAs<Expr>(), 4153 InitRange.getEnd()); 4154 } 4155 4156 MemInitResult 4157 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4158 Expr *Init, CXXRecordDecl *ClassDecl, 4159 SourceLocation EllipsisLoc) { 4160 SourceLocation BaseLoc 4161 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4162 4163 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4164 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4165 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4166 4167 // C++ [class.base.init]p2: 4168 // [...] Unless the mem-initializer-id names a nonstatic data 4169 // member of the constructor's class or a direct or virtual base 4170 // of that class, the mem-initializer is ill-formed. A 4171 // mem-initializer-list can initialize a base class using any 4172 // name that denotes that base class type. 4173 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4174 4175 SourceRange InitRange = Init->getSourceRange(); 4176 if (EllipsisLoc.isValid()) { 4177 // This is a pack expansion. 4178 if (!BaseType->containsUnexpandedParameterPack()) { 4179 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4180 << SourceRange(BaseLoc, InitRange.getEnd()); 4181 4182 EllipsisLoc = SourceLocation(); 4183 } 4184 } else { 4185 // Check for any unexpanded parameter packs. 4186 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4187 return true; 4188 4189 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4190 return true; 4191 } 4192 4193 // Check for direct and virtual base classes. 4194 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4195 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4196 if (!Dependent) { 4197 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4198 BaseType)) 4199 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4200 4201 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4202 VirtualBaseSpec); 4203 4204 // C++ [base.class.init]p2: 4205 // Unless the mem-initializer-id names a nonstatic data member of the 4206 // constructor's class or a direct or virtual base of that class, the 4207 // mem-initializer is ill-formed. 4208 if (!DirectBaseSpec && !VirtualBaseSpec) { 4209 // If the class has any dependent bases, then it's possible that 4210 // one of those types will resolve to the same type as 4211 // BaseType. Therefore, just treat this as a dependent base 4212 // class initialization. FIXME: Should we try to check the 4213 // initialization anyway? It seems odd. 4214 if (ClassDecl->hasAnyDependentBases()) 4215 Dependent = true; 4216 else 4217 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4218 << BaseType << Context.getTypeDeclType(ClassDecl) 4219 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4220 } 4221 } 4222 4223 if (Dependent) { 4224 DiscardCleanupsInEvaluationContext(); 4225 4226 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4227 /*IsVirtual=*/false, 4228 InitRange.getBegin(), Init, 4229 InitRange.getEnd(), EllipsisLoc); 4230 } 4231 4232 // C++ [base.class.init]p2: 4233 // If a mem-initializer-id is ambiguous because it designates both 4234 // a direct non-virtual base class and an inherited virtual base 4235 // class, the mem-initializer is ill-formed. 4236 if (DirectBaseSpec && VirtualBaseSpec) 4237 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4238 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4239 4240 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4241 if (!BaseSpec) 4242 BaseSpec = VirtualBaseSpec; 4243 4244 // Initialize the base. 4245 bool InitList = true; 4246 MultiExprArg Args = Init; 4247 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4248 InitList = false; 4249 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4250 } 4251 4252 InitializedEntity BaseEntity = 4253 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4254 InitializationKind Kind = 4255 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4256 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4257 InitRange.getEnd()); 4258 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4259 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4260 if (BaseInit.isInvalid()) 4261 return true; 4262 4263 // C++11 [class.base.init]p7: 4264 // The initialization of each base and member constitutes a 4265 // full-expression. 4266 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4267 /*DiscardedValue*/ false); 4268 if (BaseInit.isInvalid()) 4269 return true; 4270 4271 // If we are in a dependent context, template instantiation will 4272 // perform this type-checking again. Just save the arguments that we 4273 // received in a ParenListExpr. 4274 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4275 // of the information that we have about the base 4276 // initializer. However, deconstructing the ASTs is a dicey process, 4277 // and this approach is far more likely to get the corner cases right. 4278 if (CurContext->isDependentContext()) 4279 BaseInit = Init; 4280 4281 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4282 BaseSpec->isVirtual(), 4283 InitRange.getBegin(), 4284 BaseInit.getAs<Expr>(), 4285 InitRange.getEnd(), EllipsisLoc); 4286 } 4287 4288 // Create a static_cast\<T&&>(expr). 4289 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4290 if (T.isNull()) T = E->getType(); 4291 QualType TargetType = SemaRef.BuildReferenceType( 4292 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4293 SourceLocation ExprLoc = E->getBeginLoc(); 4294 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4295 TargetType, ExprLoc); 4296 4297 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4298 SourceRange(ExprLoc, ExprLoc), 4299 E->getSourceRange()).get(); 4300 } 4301 4302 /// ImplicitInitializerKind - How an implicit base or member initializer should 4303 /// initialize its base or member. 4304 enum ImplicitInitializerKind { 4305 IIK_Default, 4306 IIK_Copy, 4307 IIK_Move, 4308 IIK_Inherit 4309 }; 4310 4311 static bool 4312 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4313 ImplicitInitializerKind ImplicitInitKind, 4314 CXXBaseSpecifier *BaseSpec, 4315 bool IsInheritedVirtualBase, 4316 CXXCtorInitializer *&CXXBaseInit) { 4317 InitializedEntity InitEntity 4318 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4319 IsInheritedVirtualBase); 4320 4321 ExprResult BaseInit; 4322 4323 switch (ImplicitInitKind) { 4324 case IIK_Inherit: 4325 case IIK_Default: { 4326 InitializationKind InitKind 4327 = InitializationKind::CreateDefault(Constructor->getLocation()); 4328 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4329 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4330 break; 4331 } 4332 4333 case IIK_Move: 4334 case IIK_Copy: { 4335 bool Moving = ImplicitInitKind == IIK_Move; 4336 ParmVarDecl *Param = Constructor->getParamDecl(0); 4337 QualType ParamType = Param->getType().getNonReferenceType(); 4338 4339 Expr *CopyCtorArg = 4340 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4341 SourceLocation(), Param, false, 4342 Constructor->getLocation(), ParamType, 4343 VK_LValue, nullptr); 4344 4345 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4346 4347 // Cast to the base class to avoid ambiguities. 4348 QualType ArgTy = 4349 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4350 ParamType.getQualifiers()); 4351 4352 if (Moving) { 4353 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4354 } 4355 4356 CXXCastPath BasePath; 4357 BasePath.push_back(BaseSpec); 4358 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4359 CK_UncheckedDerivedToBase, 4360 Moving ? VK_XValue : VK_LValue, 4361 &BasePath).get(); 4362 4363 InitializationKind InitKind 4364 = InitializationKind::CreateDirect(Constructor->getLocation(), 4365 SourceLocation(), SourceLocation()); 4366 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4367 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4368 break; 4369 } 4370 } 4371 4372 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4373 if (BaseInit.isInvalid()) 4374 return true; 4375 4376 CXXBaseInit = 4377 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4378 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4379 SourceLocation()), 4380 BaseSpec->isVirtual(), 4381 SourceLocation(), 4382 BaseInit.getAs<Expr>(), 4383 SourceLocation(), 4384 SourceLocation()); 4385 4386 return false; 4387 } 4388 4389 static bool RefersToRValueRef(Expr *MemRef) { 4390 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4391 return Referenced->getType()->isRValueReferenceType(); 4392 } 4393 4394 static bool 4395 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4396 ImplicitInitializerKind ImplicitInitKind, 4397 FieldDecl *Field, IndirectFieldDecl *Indirect, 4398 CXXCtorInitializer *&CXXMemberInit) { 4399 if (Field->isInvalidDecl()) 4400 return true; 4401 4402 SourceLocation Loc = Constructor->getLocation(); 4403 4404 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4405 bool Moving = ImplicitInitKind == IIK_Move; 4406 ParmVarDecl *Param = Constructor->getParamDecl(0); 4407 QualType ParamType = Param->getType().getNonReferenceType(); 4408 4409 // Suppress copying zero-width bitfields. 4410 if (Field->isZeroLengthBitField(SemaRef.Context)) 4411 return false; 4412 4413 Expr *MemberExprBase = 4414 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4415 SourceLocation(), Param, false, 4416 Loc, ParamType, VK_LValue, nullptr); 4417 4418 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4419 4420 if (Moving) { 4421 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4422 } 4423 4424 // Build a reference to this field within the parameter. 4425 CXXScopeSpec SS; 4426 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4427 Sema::LookupMemberName); 4428 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4429 : cast<ValueDecl>(Field), AS_public); 4430 MemberLookup.resolveKind(); 4431 ExprResult CtorArg 4432 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4433 ParamType, Loc, 4434 /*IsArrow=*/false, 4435 SS, 4436 /*TemplateKWLoc=*/SourceLocation(), 4437 /*FirstQualifierInScope=*/nullptr, 4438 MemberLookup, 4439 /*TemplateArgs=*/nullptr, 4440 /*S*/nullptr); 4441 if (CtorArg.isInvalid()) 4442 return true; 4443 4444 // C++11 [class.copy]p15: 4445 // - if a member m has rvalue reference type T&&, it is direct-initialized 4446 // with static_cast<T&&>(x.m); 4447 if (RefersToRValueRef(CtorArg.get())) { 4448 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4449 } 4450 4451 InitializedEntity Entity = 4452 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4453 /*Implicit*/ true) 4454 : InitializedEntity::InitializeMember(Field, nullptr, 4455 /*Implicit*/ true); 4456 4457 // Direct-initialize to use the copy constructor. 4458 InitializationKind InitKind = 4459 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4460 4461 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4462 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4463 ExprResult MemberInit = 4464 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4465 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4466 if (MemberInit.isInvalid()) 4467 return true; 4468 4469 if (Indirect) 4470 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4471 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4472 else 4473 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4474 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4475 return false; 4476 } 4477 4478 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4479 "Unhandled implicit init kind!"); 4480 4481 QualType FieldBaseElementType = 4482 SemaRef.Context.getBaseElementType(Field->getType()); 4483 4484 if (FieldBaseElementType->isRecordType()) { 4485 InitializedEntity InitEntity = 4486 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4487 /*Implicit*/ true) 4488 : InitializedEntity::InitializeMember(Field, nullptr, 4489 /*Implicit*/ true); 4490 InitializationKind InitKind = 4491 InitializationKind::CreateDefault(Loc); 4492 4493 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4494 ExprResult MemberInit = 4495 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4496 4497 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4498 if (MemberInit.isInvalid()) 4499 return true; 4500 4501 if (Indirect) 4502 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4503 Indirect, Loc, 4504 Loc, 4505 MemberInit.get(), 4506 Loc); 4507 else 4508 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4509 Field, Loc, Loc, 4510 MemberInit.get(), 4511 Loc); 4512 return false; 4513 } 4514 4515 if (!Field->getParent()->isUnion()) { 4516 if (FieldBaseElementType->isReferenceType()) { 4517 SemaRef.Diag(Constructor->getLocation(), 4518 diag::err_uninitialized_member_in_ctor) 4519 << (int)Constructor->isImplicit() 4520 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4521 << 0 << Field->getDeclName(); 4522 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4523 return true; 4524 } 4525 4526 if (FieldBaseElementType.isConstQualified()) { 4527 SemaRef.Diag(Constructor->getLocation(), 4528 diag::err_uninitialized_member_in_ctor) 4529 << (int)Constructor->isImplicit() 4530 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4531 << 1 << Field->getDeclName(); 4532 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4533 return true; 4534 } 4535 } 4536 4537 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4538 // ARC and Weak: 4539 // Default-initialize Objective-C pointers to NULL. 4540 CXXMemberInit 4541 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4542 Loc, Loc, 4543 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4544 Loc); 4545 return false; 4546 } 4547 4548 // Nothing to initialize. 4549 CXXMemberInit = nullptr; 4550 return false; 4551 } 4552 4553 namespace { 4554 struct BaseAndFieldInfo { 4555 Sema &S; 4556 CXXConstructorDecl *Ctor; 4557 bool AnyErrorsInInits; 4558 ImplicitInitializerKind IIK; 4559 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4560 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4561 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4562 4563 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4564 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4565 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4566 if (Ctor->getInheritedConstructor()) 4567 IIK = IIK_Inherit; 4568 else if (Generated && Ctor->isCopyConstructor()) 4569 IIK = IIK_Copy; 4570 else if (Generated && Ctor->isMoveConstructor()) 4571 IIK = IIK_Move; 4572 else 4573 IIK = IIK_Default; 4574 } 4575 4576 bool isImplicitCopyOrMove() const { 4577 switch (IIK) { 4578 case IIK_Copy: 4579 case IIK_Move: 4580 return true; 4581 4582 case IIK_Default: 4583 case IIK_Inherit: 4584 return false; 4585 } 4586 4587 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4588 } 4589 4590 bool addFieldInitializer(CXXCtorInitializer *Init) { 4591 AllToInit.push_back(Init); 4592 4593 // Check whether this initializer makes the field "used". 4594 if (Init->getInit()->HasSideEffects(S.Context)) 4595 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4596 4597 return false; 4598 } 4599 4600 bool isInactiveUnionMember(FieldDecl *Field) { 4601 RecordDecl *Record = Field->getParent(); 4602 if (!Record->isUnion()) 4603 return false; 4604 4605 if (FieldDecl *Active = 4606 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4607 return Active != Field->getCanonicalDecl(); 4608 4609 // In an implicit copy or move constructor, ignore any in-class initializer. 4610 if (isImplicitCopyOrMove()) 4611 return true; 4612 4613 // If there's no explicit initialization, the field is active only if it 4614 // has an in-class initializer... 4615 if (Field->hasInClassInitializer()) 4616 return false; 4617 // ... or it's an anonymous struct or union whose class has an in-class 4618 // initializer. 4619 if (!Field->isAnonymousStructOrUnion()) 4620 return true; 4621 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4622 return !FieldRD->hasInClassInitializer(); 4623 } 4624 4625 /// Determine whether the given field is, or is within, a union member 4626 /// that is inactive (because there was an initializer given for a different 4627 /// member of the union, or because the union was not initialized at all). 4628 bool isWithinInactiveUnionMember(FieldDecl *Field, 4629 IndirectFieldDecl *Indirect) { 4630 if (!Indirect) 4631 return isInactiveUnionMember(Field); 4632 4633 for (auto *C : Indirect->chain()) { 4634 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4635 if (Field && isInactiveUnionMember(Field)) 4636 return true; 4637 } 4638 return false; 4639 } 4640 }; 4641 } 4642 4643 /// Determine whether the given type is an incomplete or zero-lenfgth 4644 /// array type. 4645 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4646 if (T->isIncompleteArrayType()) 4647 return true; 4648 4649 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4650 if (!ArrayT->getSize()) 4651 return true; 4652 4653 T = ArrayT->getElementType(); 4654 } 4655 4656 return false; 4657 } 4658 4659 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4660 FieldDecl *Field, 4661 IndirectFieldDecl *Indirect = nullptr) { 4662 if (Field->isInvalidDecl()) 4663 return false; 4664 4665 // Overwhelmingly common case: we have a direct initializer for this field. 4666 if (CXXCtorInitializer *Init = 4667 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4668 return Info.addFieldInitializer(Init); 4669 4670 // C++11 [class.base.init]p8: 4671 // if the entity is a non-static data member that has a 4672 // brace-or-equal-initializer and either 4673 // -- the constructor's class is a union and no other variant member of that 4674 // union is designated by a mem-initializer-id or 4675 // -- the constructor's class is not a union, and, if the entity is a member 4676 // of an anonymous union, no other member of that union is designated by 4677 // a mem-initializer-id, 4678 // the entity is initialized as specified in [dcl.init]. 4679 // 4680 // We also apply the same rules to handle anonymous structs within anonymous 4681 // unions. 4682 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4683 return false; 4684 4685 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4686 ExprResult DIE = 4687 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4688 if (DIE.isInvalid()) 4689 return true; 4690 4691 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4692 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4693 4694 CXXCtorInitializer *Init; 4695 if (Indirect) 4696 Init = new (SemaRef.Context) 4697 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4698 SourceLocation(), DIE.get(), SourceLocation()); 4699 else 4700 Init = new (SemaRef.Context) 4701 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4702 SourceLocation(), DIE.get(), SourceLocation()); 4703 return Info.addFieldInitializer(Init); 4704 } 4705 4706 // Don't initialize incomplete or zero-length arrays. 4707 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4708 return false; 4709 4710 // Don't try to build an implicit initializer if there were semantic 4711 // errors in any of the initializers (and therefore we might be 4712 // missing some that the user actually wrote). 4713 if (Info.AnyErrorsInInits) 4714 return false; 4715 4716 CXXCtorInitializer *Init = nullptr; 4717 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4718 Indirect, Init)) 4719 return true; 4720 4721 if (!Init) 4722 return false; 4723 4724 return Info.addFieldInitializer(Init); 4725 } 4726 4727 bool 4728 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4729 CXXCtorInitializer *Initializer) { 4730 assert(Initializer->isDelegatingInitializer()); 4731 Constructor->setNumCtorInitializers(1); 4732 CXXCtorInitializer **initializer = 4733 new (Context) CXXCtorInitializer*[1]; 4734 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4735 Constructor->setCtorInitializers(initializer); 4736 4737 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4738 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4739 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4740 } 4741 4742 DelegatingCtorDecls.push_back(Constructor); 4743 4744 DiagnoseUninitializedFields(*this, Constructor); 4745 4746 return false; 4747 } 4748 4749 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4750 ArrayRef<CXXCtorInitializer *> Initializers) { 4751 if (Constructor->isDependentContext()) { 4752 // Just store the initializers as written, they will be checked during 4753 // instantiation. 4754 if (!Initializers.empty()) { 4755 Constructor->setNumCtorInitializers(Initializers.size()); 4756 CXXCtorInitializer **baseOrMemberInitializers = 4757 new (Context) CXXCtorInitializer*[Initializers.size()]; 4758 memcpy(baseOrMemberInitializers, Initializers.data(), 4759 Initializers.size() * sizeof(CXXCtorInitializer*)); 4760 Constructor->setCtorInitializers(baseOrMemberInitializers); 4761 } 4762 4763 // Let template instantiation know whether we had errors. 4764 if (AnyErrors) 4765 Constructor->setInvalidDecl(); 4766 4767 return false; 4768 } 4769 4770 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4771 4772 // We need to build the initializer AST according to order of construction 4773 // and not what user specified in the Initializers list. 4774 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4775 if (!ClassDecl) 4776 return true; 4777 4778 bool HadError = false; 4779 4780 for (unsigned i = 0; i < Initializers.size(); i++) { 4781 CXXCtorInitializer *Member = Initializers[i]; 4782 4783 if (Member->isBaseInitializer()) 4784 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4785 else { 4786 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4787 4788 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4789 for (auto *C : F->chain()) { 4790 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4791 if (FD && FD->getParent()->isUnion()) 4792 Info.ActiveUnionMember.insert(std::make_pair( 4793 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4794 } 4795 } else if (FieldDecl *FD = Member->getMember()) { 4796 if (FD->getParent()->isUnion()) 4797 Info.ActiveUnionMember.insert(std::make_pair( 4798 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4799 } 4800 } 4801 } 4802 4803 // Keep track of the direct virtual bases. 4804 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4805 for (auto &I : ClassDecl->bases()) { 4806 if (I.isVirtual()) 4807 DirectVBases.insert(&I); 4808 } 4809 4810 // Push virtual bases before others. 4811 for (auto &VBase : ClassDecl->vbases()) { 4812 if (CXXCtorInitializer *Value 4813 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4814 // [class.base.init]p7, per DR257: 4815 // A mem-initializer where the mem-initializer-id names a virtual base 4816 // class is ignored during execution of a constructor of any class that 4817 // is not the most derived class. 4818 if (ClassDecl->isAbstract()) { 4819 // FIXME: Provide a fixit to remove the base specifier. This requires 4820 // tracking the location of the associated comma for a base specifier. 4821 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4822 << VBase.getType() << ClassDecl; 4823 DiagnoseAbstractType(ClassDecl); 4824 } 4825 4826 Info.AllToInit.push_back(Value); 4827 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4828 // [class.base.init]p8, per DR257: 4829 // If a given [...] base class is not named by a mem-initializer-id 4830 // [...] and the entity is not a virtual base class of an abstract 4831 // class, then [...] the entity is default-initialized. 4832 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4833 CXXCtorInitializer *CXXBaseInit; 4834 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4835 &VBase, IsInheritedVirtualBase, 4836 CXXBaseInit)) { 4837 HadError = true; 4838 continue; 4839 } 4840 4841 Info.AllToInit.push_back(CXXBaseInit); 4842 } 4843 } 4844 4845 // Non-virtual bases. 4846 for (auto &Base : ClassDecl->bases()) { 4847 // Virtuals are in the virtual base list and already constructed. 4848 if (Base.isVirtual()) 4849 continue; 4850 4851 if (CXXCtorInitializer *Value 4852 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4853 Info.AllToInit.push_back(Value); 4854 } else if (!AnyErrors) { 4855 CXXCtorInitializer *CXXBaseInit; 4856 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4857 &Base, /*IsInheritedVirtualBase=*/false, 4858 CXXBaseInit)) { 4859 HadError = true; 4860 continue; 4861 } 4862 4863 Info.AllToInit.push_back(CXXBaseInit); 4864 } 4865 } 4866 4867 // Fields. 4868 for (auto *Mem : ClassDecl->decls()) { 4869 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4870 // C++ [class.bit]p2: 4871 // A declaration for a bit-field that omits the identifier declares an 4872 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4873 // initialized. 4874 if (F->isUnnamedBitfield()) 4875 continue; 4876 4877 // If we're not generating the implicit copy/move constructor, then we'll 4878 // handle anonymous struct/union fields based on their individual 4879 // indirect fields. 4880 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4881 continue; 4882 4883 if (CollectFieldInitializer(*this, Info, F)) 4884 HadError = true; 4885 continue; 4886 } 4887 4888 // Beyond this point, we only consider default initialization. 4889 if (Info.isImplicitCopyOrMove()) 4890 continue; 4891 4892 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4893 if (F->getType()->isIncompleteArrayType()) { 4894 assert(ClassDecl->hasFlexibleArrayMember() && 4895 "Incomplete array type is not valid"); 4896 continue; 4897 } 4898 4899 // Initialize each field of an anonymous struct individually. 4900 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4901 HadError = true; 4902 4903 continue; 4904 } 4905 } 4906 4907 unsigned NumInitializers = Info.AllToInit.size(); 4908 if (NumInitializers > 0) { 4909 Constructor->setNumCtorInitializers(NumInitializers); 4910 CXXCtorInitializer **baseOrMemberInitializers = 4911 new (Context) CXXCtorInitializer*[NumInitializers]; 4912 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4913 NumInitializers * sizeof(CXXCtorInitializer*)); 4914 Constructor->setCtorInitializers(baseOrMemberInitializers); 4915 4916 // Constructors implicitly reference the base and member 4917 // destructors. 4918 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4919 Constructor->getParent()); 4920 } 4921 4922 return HadError; 4923 } 4924 4925 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4926 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4927 const RecordDecl *RD = RT->getDecl(); 4928 if (RD->isAnonymousStructOrUnion()) { 4929 for (auto *Field : RD->fields()) 4930 PopulateKeysForFields(Field, IdealInits); 4931 return; 4932 } 4933 } 4934 IdealInits.push_back(Field->getCanonicalDecl()); 4935 } 4936 4937 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4938 return Context.getCanonicalType(BaseType).getTypePtr(); 4939 } 4940 4941 static const void *GetKeyForMember(ASTContext &Context, 4942 CXXCtorInitializer *Member) { 4943 if (!Member->isAnyMemberInitializer()) 4944 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4945 4946 return Member->getAnyMember()->getCanonicalDecl(); 4947 } 4948 4949 static void DiagnoseBaseOrMemInitializerOrder( 4950 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4951 ArrayRef<CXXCtorInitializer *> Inits) { 4952 if (Constructor->getDeclContext()->isDependentContext()) 4953 return; 4954 4955 // Don't check initializers order unless the warning is enabled at the 4956 // location of at least one initializer. 4957 bool ShouldCheckOrder = false; 4958 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4959 CXXCtorInitializer *Init = Inits[InitIndex]; 4960 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4961 Init->getSourceLocation())) { 4962 ShouldCheckOrder = true; 4963 break; 4964 } 4965 } 4966 if (!ShouldCheckOrder) 4967 return; 4968 4969 // Build the list of bases and members in the order that they'll 4970 // actually be initialized. The explicit initializers should be in 4971 // this same order but may be missing things. 4972 SmallVector<const void*, 32> IdealInitKeys; 4973 4974 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4975 4976 // 1. Virtual bases. 4977 for (const auto &VBase : ClassDecl->vbases()) 4978 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4979 4980 // 2. Non-virtual bases. 4981 for (const auto &Base : ClassDecl->bases()) { 4982 if (Base.isVirtual()) 4983 continue; 4984 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4985 } 4986 4987 // 3. Direct fields. 4988 for (auto *Field : ClassDecl->fields()) { 4989 if (Field->isUnnamedBitfield()) 4990 continue; 4991 4992 PopulateKeysForFields(Field, IdealInitKeys); 4993 } 4994 4995 unsigned NumIdealInits = IdealInitKeys.size(); 4996 unsigned IdealIndex = 0; 4997 4998 CXXCtorInitializer *PrevInit = nullptr; 4999 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5000 CXXCtorInitializer *Init = Inits[InitIndex]; 5001 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5002 5003 // Scan forward to try to find this initializer in the idealized 5004 // initializers list. 5005 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5006 if (InitKey == IdealInitKeys[IdealIndex]) 5007 break; 5008 5009 // If we didn't find this initializer, it must be because we 5010 // scanned past it on a previous iteration. That can only 5011 // happen if we're out of order; emit a warning. 5012 if (IdealIndex == NumIdealInits && PrevInit) { 5013 Sema::SemaDiagnosticBuilder D = 5014 SemaRef.Diag(PrevInit->getSourceLocation(), 5015 diag::warn_initializer_out_of_order); 5016 5017 if (PrevInit->isAnyMemberInitializer()) 5018 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5019 else 5020 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5021 5022 if (Init->isAnyMemberInitializer()) 5023 D << 0 << Init->getAnyMember()->getDeclName(); 5024 else 5025 D << 1 << Init->getTypeSourceInfo()->getType(); 5026 5027 // Move back to the initializer's location in the ideal list. 5028 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5029 if (InitKey == IdealInitKeys[IdealIndex]) 5030 break; 5031 5032 assert(IdealIndex < NumIdealInits && 5033 "initializer not found in initializer list"); 5034 } 5035 5036 PrevInit = Init; 5037 } 5038 } 5039 5040 namespace { 5041 bool CheckRedundantInit(Sema &S, 5042 CXXCtorInitializer *Init, 5043 CXXCtorInitializer *&PrevInit) { 5044 if (!PrevInit) { 5045 PrevInit = Init; 5046 return false; 5047 } 5048 5049 if (FieldDecl *Field = Init->getAnyMember()) 5050 S.Diag(Init->getSourceLocation(), 5051 diag::err_multiple_mem_initialization) 5052 << Field->getDeclName() 5053 << Init->getSourceRange(); 5054 else { 5055 const Type *BaseClass = Init->getBaseClass(); 5056 assert(BaseClass && "neither field nor base"); 5057 S.Diag(Init->getSourceLocation(), 5058 diag::err_multiple_base_initialization) 5059 << QualType(BaseClass, 0) 5060 << Init->getSourceRange(); 5061 } 5062 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5063 << 0 << PrevInit->getSourceRange(); 5064 5065 return true; 5066 } 5067 5068 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5069 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5070 5071 bool CheckRedundantUnionInit(Sema &S, 5072 CXXCtorInitializer *Init, 5073 RedundantUnionMap &Unions) { 5074 FieldDecl *Field = Init->getAnyMember(); 5075 RecordDecl *Parent = Field->getParent(); 5076 NamedDecl *Child = Field; 5077 5078 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5079 if (Parent->isUnion()) { 5080 UnionEntry &En = Unions[Parent]; 5081 if (En.first && En.first != Child) { 5082 S.Diag(Init->getSourceLocation(), 5083 diag::err_multiple_mem_union_initialization) 5084 << Field->getDeclName() 5085 << Init->getSourceRange(); 5086 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5087 << 0 << En.second->getSourceRange(); 5088 return true; 5089 } 5090 if (!En.first) { 5091 En.first = Child; 5092 En.second = Init; 5093 } 5094 if (!Parent->isAnonymousStructOrUnion()) 5095 return false; 5096 } 5097 5098 Child = Parent; 5099 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5100 } 5101 5102 return false; 5103 } 5104 } 5105 5106 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5107 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5108 SourceLocation ColonLoc, 5109 ArrayRef<CXXCtorInitializer*> MemInits, 5110 bool AnyErrors) { 5111 if (!ConstructorDecl) 5112 return; 5113 5114 AdjustDeclIfTemplate(ConstructorDecl); 5115 5116 CXXConstructorDecl *Constructor 5117 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5118 5119 if (!Constructor) { 5120 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5121 return; 5122 } 5123 5124 // Mapping for the duplicate initializers check. 5125 // For member initializers, this is keyed with a FieldDecl*. 5126 // For base initializers, this is keyed with a Type*. 5127 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5128 5129 // Mapping for the inconsistent anonymous-union initializers check. 5130 RedundantUnionMap MemberUnions; 5131 5132 bool HadError = false; 5133 for (unsigned i = 0; i < MemInits.size(); i++) { 5134 CXXCtorInitializer *Init = MemInits[i]; 5135 5136 // Set the source order index. 5137 Init->setSourceOrder(i); 5138 5139 if (Init->isAnyMemberInitializer()) { 5140 const void *Key = GetKeyForMember(Context, Init); 5141 if (CheckRedundantInit(*this, Init, Members[Key]) || 5142 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5143 HadError = true; 5144 } else if (Init->isBaseInitializer()) { 5145 const void *Key = GetKeyForMember(Context, Init); 5146 if (CheckRedundantInit(*this, Init, Members[Key])) 5147 HadError = true; 5148 } else { 5149 assert(Init->isDelegatingInitializer()); 5150 // This must be the only initializer 5151 if (MemInits.size() != 1) { 5152 Diag(Init->getSourceLocation(), 5153 diag::err_delegating_initializer_alone) 5154 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5155 // We will treat this as being the only initializer. 5156 } 5157 SetDelegatingInitializer(Constructor, MemInits[i]); 5158 // Return immediately as the initializer is set. 5159 return; 5160 } 5161 } 5162 5163 if (HadError) 5164 return; 5165 5166 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5167 5168 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5169 5170 DiagnoseUninitializedFields(*this, Constructor); 5171 } 5172 5173 void 5174 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5175 CXXRecordDecl *ClassDecl) { 5176 // Ignore dependent contexts. Also ignore unions, since their members never 5177 // have destructors implicitly called. 5178 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5179 return; 5180 5181 // FIXME: all the access-control diagnostics are positioned on the 5182 // field/base declaration. That's probably good; that said, the 5183 // user might reasonably want to know why the destructor is being 5184 // emitted, and we currently don't say. 5185 5186 // Non-static data members. 5187 for (auto *Field : ClassDecl->fields()) { 5188 if (Field->isInvalidDecl()) 5189 continue; 5190 5191 // Don't destroy incomplete or zero-length arrays. 5192 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5193 continue; 5194 5195 QualType FieldType = Context.getBaseElementType(Field->getType()); 5196 5197 const RecordType* RT = FieldType->getAs<RecordType>(); 5198 if (!RT) 5199 continue; 5200 5201 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5202 if (FieldClassDecl->isInvalidDecl()) 5203 continue; 5204 if (FieldClassDecl->hasIrrelevantDestructor()) 5205 continue; 5206 // The destructor for an implicit anonymous union member is never invoked. 5207 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5208 continue; 5209 5210 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5211 assert(Dtor && "No dtor found for FieldClassDecl!"); 5212 CheckDestructorAccess(Field->getLocation(), Dtor, 5213 PDiag(diag::err_access_dtor_field) 5214 << Field->getDeclName() 5215 << FieldType); 5216 5217 MarkFunctionReferenced(Location, Dtor); 5218 DiagnoseUseOfDecl(Dtor, Location); 5219 } 5220 5221 // We only potentially invoke the destructors of potentially constructed 5222 // subobjects. 5223 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5224 5225 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5226 5227 // Bases. 5228 for (const auto &Base : ClassDecl->bases()) { 5229 // Bases are always records in a well-formed non-dependent class. 5230 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5231 5232 // Remember direct virtual bases. 5233 if (Base.isVirtual()) { 5234 if (!VisitVirtualBases) 5235 continue; 5236 DirectVirtualBases.insert(RT); 5237 } 5238 5239 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5240 // If our base class is invalid, we probably can't get its dtor anyway. 5241 if (BaseClassDecl->isInvalidDecl()) 5242 continue; 5243 if (BaseClassDecl->hasIrrelevantDestructor()) 5244 continue; 5245 5246 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5247 assert(Dtor && "No dtor found for BaseClassDecl!"); 5248 5249 // FIXME: caret should be on the start of the class name 5250 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5251 PDiag(diag::err_access_dtor_base) 5252 << Base.getType() << Base.getSourceRange(), 5253 Context.getTypeDeclType(ClassDecl)); 5254 5255 MarkFunctionReferenced(Location, Dtor); 5256 DiagnoseUseOfDecl(Dtor, Location); 5257 } 5258 5259 if (!VisitVirtualBases) 5260 return; 5261 5262 // Virtual bases. 5263 for (const auto &VBase : ClassDecl->vbases()) { 5264 // Bases are always records in a well-formed non-dependent class. 5265 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5266 5267 // Ignore direct virtual bases. 5268 if (DirectVirtualBases.count(RT)) 5269 continue; 5270 5271 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5272 // If our base class is invalid, we probably can't get its dtor anyway. 5273 if (BaseClassDecl->isInvalidDecl()) 5274 continue; 5275 if (BaseClassDecl->hasIrrelevantDestructor()) 5276 continue; 5277 5278 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5279 assert(Dtor && "No dtor found for BaseClassDecl!"); 5280 if (CheckDestructorAccess( 5281 ClassDecl->getLocation(), Dtor, 5282 PDiag(diag::err_access_dtor_vbase) 5283 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5284 Context.getTypeDeclType(ClassDecl)) == 5285 AR_accessible) { 5286 CheckDerivedToBaseConversion( 5287 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5288 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5289 SourceRange(), DeclarationName(), nullptr); 5290 } 5291 5292 MarkFunctionReferenced(Location, Dtor); 5293 DiagnoseUseOfDecl(Dtor, Location); 5294 } 5295 } 5296 5297 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5298 if (!CDtorDecl) 5299 return; 5300 5301 if (CXXConstructorDecl *Constructor 5302 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5303 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5304 DiagnoseUninitializedFields(*this, Constructor); 5305 } 5306 } 5307 5308 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5309 if (!getLangOpts().CPlusPlus) 5310 return false; 5311 5312 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5313 if (!RD) 5314 return false; 5315 5316 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5317 // class template specialization here, but doing so breaks a lot of code. 5318 5319 // We can't answer whether something is abstract until it has a 5320 // definition. If it's currently being defined, we'll walk back 5321 // over all the declarations when we have a full definition. 5322 const CXXRecordDecl *Def = RD->getDefinition(); 5323 if (!Def || Def->isBeingDefined()) 5324 return false; 5325 5326 return RD->isAbstract(); 5327 } 5328 5329 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5330 TypeDiagnoser &Diagnoser) { 5331 if (!isAbstractType(Loc, T)) 5332 return false; 5333 5334 T = Context.getBaseElementType(T); 5335 Diagnoser.diagnose(*this, Loc, T); 5336 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5337 return true; 5338 } 5339 5340 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5341 // Check if we've already emitted the list of pure virtual functions 5342 // for this class. 5343 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5344 return; 5345 5346 // If the diagnostic is suppressed, don't emit the notes. We're only 5347 // going to emit them once, so try to attach them to a diagnostic we're 5348 // actually going to show. 5349 if (Diags.isLastDiagnosticIgnored()) 5350 return; 5351 5352 CXXFinalOverriderMap FinalOverriders; 5353 RD->getFinalOverriders(FinalOverriders); 5354 5355 // Keep a set of seen pure methods so we won't diagnose the same method 5356 // more than once. 5357 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5358 5359 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5360 MEnd = FinalOverriders.end(); 5361 M != MEnd; 5362 ++M) { 5363 for (OverridingMethods::iterator SO = M->second.begin(), 5364 SOEnd = M->second.end(); 5365 SO != SOEnd; ++SO) { 5366 // C++ [class.abstract]p4: 5367 // A class is abstract if it contains or inherits at least one 5368 // pure virtual function for which the final overrider is pure 5369 // virtual. 5370 5371 // 5372 if (SO->second.size() != 1) 5373 continue; 5374 5375 if (!SO->second.front().Method->isPure()) 5376 continue; 5377 5378 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5379 continue; 5380 5381 Diag(SO->second.front().Method->getLocation(), 5382 diag::note_pure_virtual_function) 5383 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5384 } 5385 } 5386 5387 if (!PureVirtualClassDiagSet) 5388 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5389 PureVirtualClassDiagSet->insert(RD); 5390 } 5391 5392 namespace { 5393 struct AbstractUsageInfo { 5394 Sema &S; 5395 CXXRecordDecl *Record; 5396 CanQualType AbstractType; 5397 bool Invalid; 5398 5399 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5400 : S(S), Record(Record), 5401 AbstractType(S.Context.getCanonicalType( 5402 S.Context.getTypeDeclType(Record))), 5403 Invalid(false) {} 5404 5405 void DiagnoseAbstractType() { 5406 if (Invalid) return; 5407 S.DiagnoseAbstractType(Record); 5408 Invalid = true; 5409 } 5410 5411 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5412 }; 5413 5414 struct CheckAbstractUsage { 5415 AbstractUsageInfo &Info; 5416 const NamedDecl *Ctx; 5417 5418 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5419 : Info(Info), Ctx(Ctx) {} 5420 5421 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5422 switch (TL.getTypeLocClass()) { 5423 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5424 #define TYPELOC(CLASS, PARENT) \ 5425 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5426 #include "clang/AST/TypeLocNodes.def" 5427 } 5428 } 5429 5430 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5431 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5432 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5433 if (!TL.getParam(I)) 5434 continue; 5435 5436 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5437 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5438 } 5439 } 5440 5441 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5442 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5443 } 5444 5445 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5446 // Visit the type parameters from a permissive context. 5447 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5448 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5449 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5450 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5451 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5452 // TODO: other template argument types? 5453 } 5454 } 5455 5456 // Visit pointee types from a permissive context. 5457 #define CheckPolymorphic(Type) \ 5458 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5459 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5460 } 5461 CheckPolymorphic(PointerTypeLoc) 5462 CheckPolymorphic(ReferenceTypeLoc) 5463 CheckPolymorphic(MemberPointerTypeLoc) 5464 CheckPolymorphic(BlockPointerTypeLoc) 5465 CheckPolymorphic(AtomicTypeLoc) 5466 5467 /// Handle all the types we haven't given a more specific 5468 /// implementation for above. 5469 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5470 // Every other kind of type that we haven't called out already 5471 // that has an inner type is either (1) sugar or (2) contains that 5472 // inner type in some way as a subobject. 5473 if (TypeLoc Next = TL.getNextTypeLoc()) 5474 return Visit(Next, Sel); 5475 5476 // If there's no inner type and we're in a permissive context, 5477 // don't diagnose. 5478 if (Sel == Sema::AbstractNone) return; 5479 5480 // Check whether the type matches the abstract type. 5481 QualType T = TL.getType(); 5482 if (T->isArrayType()) { 5483 Sel = Sema::AbstractArrayType; 5484 T = Info.S.Context.getBaseElementType(T); 5485 } 5486 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5487 if (CT != Info.AbstractType) return; 5488 5489 // It matched; do some magic. 5490 if (Sel == Sema::AbstractArrayType) { 5491 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5492 << T << TL.getSourceRange(); 5493 } else { 5494 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5495 << Sel << T << TL.getSourceRange(); 5496 } 5497 Info.DiagnoseAbstractType(); 5498 } 5499 }; 5500 5501 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5502 Sema::AbstractDiagSelID Sel) { 5503 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5504 } 5505 5506 } 5507 5508 /// Check for invalid uses of an abstract type in a method declaration. 5509 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5510 CXXMethodDecl *MD) { 5511 // No need to do the check on definitions, which require that 5512 // the return/param types be complete. 5513 if (MD->doesThisDeclarationHaveABody()) 5514 return; 5515 5516 // For safety's sake, just ignore it if we don't have type source 5517 // information. This should never happen for non-implicit methods, 5518 // but... 5519 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5520 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5521 } 5522 5523 /// Check for invalid uses of an abstract type within a class definition. 5524 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5525 CXXRecordDecl *RD) { 5526 for (auto *D : RD->decls()) { 5527 if (D->isImplicit()) continue; 5528 5529 // Methods and method templates. 5530 if (isa<CXXMethodDecl>(D)) { 5531 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5532 } else if (isa<FunctionTemplateDecl>(D)) { 5533 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5534 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5535 5536 // Fields and static variables. 5537 } else if (isa<FieldDecl>(D)) { 5538 FieldDecl *FD = cast<FieldDecl>(D); 5539 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5540 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5541 } else if (isa<VarDecl>(D)) { 5542 VarDecl *VD = cast<VarDecl>(D); 5543 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5544 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5545 5546 // Nested classes and class templates. 5547 } else if (isa<CXXRecordDecl>(D)) { 5548 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5549 } else if (isa<ClassTemplateDecl>(D)) { 5550 CheckAbstractClassUsage(Info, 5551 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5552 } 5553 } 5554 } 5555 5556 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5557 Attr *ClassAttr = getDLLAttr(Class); 5558 if (!ClassAttr) 5559 return; 5560 5561 assert(ClassAttr->getKind() == attr::DLLExport); 5562 5563 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5564 5565 if (TSK == TSK_ExplicitInstantiationDeclaration) 5566 // Don't go any further if this is just an explicit instantiation 5567 // declaration. 5568 return; 5569 5570 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5571 S.MarkVTableUsed(Class->getLocation(), Class, true); 5572 5573 for (Decl *Member : Class->decls()) { 5574 // Defined static variables that are members of an exported base 5575 // class must be marked export too. 5576 auto *VD = dyn_cast<VarDecl>(Member); 5577 if (VD && Member->getAttr<DLLExportAttr>() && 5578 VD->getStorageClass() == SC_Static && 5579 TSK == TSK_ImplicitInstantiation) 5580 S.MarkVariableReferenced(VD->getLocation(), VD); 5581 5582 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5583 if (!MD) 5584 continue; 5585 5586 if (Member->getAttr<DLLExportAttr>()) { 5587 if (MD->isUserProvided()) { 5588 // Instantiate non-default class member functions ... 5589 5590 // .. except for certain kinds of template specializations. 5591 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5592 continue; 5593 5594 S.MarkFunctionReferenced(Class->getLocation(), MD); 5595 5596 // The function will be passed to the consumer when its definition is 5597 // encountered. 5598 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5599 MD->isCopyAssignmentOperator() || 5600 MD->isMoveAssignmentOperator()) { 5601 // Synthesize and instantiate non-trivial implicit methods, explicitly 5602 // defaulted methods, and the copy and move assignment operators. The 5603 // latter are exported even if they are trivial, because the address of 5604 // an operator can be taken and should compare equal across libraries. 5605 DiagnosticErrorTrap Trap(S.Diags); 5606 S.MarkFunctionReferenced(Class->getLocation(), MD); 5607 if (Trap.hasErrorOccurred()) { 5608 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5609 << Class << !S.getLangOpts().CPlusPlus11; 5610 break; 5611 } 5612 5613 // There is no later point when we will see the definition of this 5614 // function, so pass it to the consumer now. 5615 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5616 } 5617 } 5618 } 5619 } 5620 5621 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5622 CXXRecordDecl *Class) { 5623 // Only the MS ABI has default constructor closures, so we don't need to do 5624 // this semantic checking anywhere else. 5625 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5626 return; 5627 5628 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5629 for (Decl *Member : Class->decls()) { 5630 // Look for exported default constructors. 5631 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5632 if (!CD || !CD->isDefaultConstructor()) 5633 continue; 5634 auto *Attr = CD->getAttr<DLLExportAttr>(); 5635 if (!Attr) 5636 continue; 5637 5638 // If the class is non-dependent, mark the default arguments as ODR-used so 5639 // that we can properly codegen the constructor closure. 5640 if (!Class->isDependentContext()) { 5641 for (ParmVarDecl *PD : CD->parameters()) { 5642 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5643 S.DiscardCleanupsInEvaluationContext(); 5644 } 5645 } 5646 5647 if (LastExportedDefaultCtor) { 5648 S.Diag(LastExportedDefaultCtor->getLocation(), 5649 diag::err_attribute_dll_ambiguous_default_ctor) 5650 << Class; 5651 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5652 << CD->getDeclName(); 5653 return; 5654 } 5655 LastExportedDefaultCtor = CD; 5656 } 5657 } 5658 5659 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5660 // Mark any compiler-generated routines with the implicit code_seg attribute. 5661 for (auto *Method : Class->methods()) { 5662 if (Method->isUserProvided()) 5663 continue; 5664 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5665 Method->addAttr(A); 5666 } 5667 } 5668 5669 /// Check class-level dllimport/dllexport attribute. 5670 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5671 Attr *ClassAttr = getDLLAttr(Class); 5672 5673 // MSVC inherits DLL attributes to partial class template specializations. 5674 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5675 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5676 if (Attr *TemplateAttr = 5677 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5678 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5679 A->setInherited(true); 5680 ClassAttr = A; 5681 } 5682 } 5683 } 5684 5685 if (!ClassAttr) 5686 return; 5687 5688 if (!Class->isExternallyVisible()) { 5689 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5690 << Class << ClassAttr; 5691 return; 5692 } 5693 5694 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5695 !ClassAttr->isInherited()) { 5696 // Diagnose dll attributes on members of class with dll attribute. 5697 for (Decl *Member : Class->decls()) { 5698 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5699 continue; 5700 InheritableAttr *MemberAttr = getDLLAttr(Member); 5701 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5702 continue; 5703 5704 Diag(MemberAttr->getLocation(), 5705 diag::err_attribute_dll_member_of_dll_class) 5706 << MemberAttr << ClassAttr; 5707 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5708 Member->setInvalidDecl(); 5709 } 5710 } 5711 5712 if (Class->getDescribedClassTemplate()) 5713 // Don't inherit dll attribute until the template is instantiated. 5714 return; 5715 5716 // The class is either imported or exported. 5717 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5718 5719 // Check if this was a dllimport attribute propagated from a derived class to 5720 // a base class template specialization. We don't apply these attributes to 5721 // static data members. 5722 const bool PropagatedImport = 5723 !ClassExported && 5724 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5725 5726 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5727 5728 // Ignore explicit dllexport on explicit class template instantiation 5729 // declarations, except in MinGW mode. 5730 if (ClassExported && !ClassAttr->isInherited() && 5731 TSK == TSK_ExplicitInstantiationDeclaration && 5732 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 5733 Class->dropAttr<DLLExportAttr>(); 5734 return; 5735 } 5736 5737 // Force declaration of implicit members so they can inherit the attribute. 5738 ForceDeclarationOfImplicitMembers(Class); 5739 5740 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5741 // seem to be true in practice? 5742 5743 for (Decl *Member : Class->decls()) { 5744 VarDecl *VD = dyn_cast<VarDecl>(Member); 5745 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5746 5747 // Only methods and static fields inherit the attributes. 5748 if (!VD && !MD) 5749 continue; 5750 5751 if (MD) { 5752 // Don't process deleted methods. 5753 if (MD->isDeleted()) 5754 continue; 5755 5756 if (MD->isInlined()) { 5757 // MinGW does not import or export inline methods. But do it for 5758 // template instantiations. 5759 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5760 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 5761 TSK != TSK_ExplicitInstantiationDeclaration && 5762 TSK != TSK_ExplicitInstantiationDefinition) 5763 continue; 5764 5765 // MSVC versions before 2015 don't export the move assignment operators 5766 // and move constructor, so don't attempt to import/export them if 5767 // we have a definition. 5768 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5769 if ((MD->isMoveAssignmentOperator() || 5770 (Ctor && Ctor->isMoveConstructor())) && 5771 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5772 continue; 5773 5774 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5775 // operator is exported anyway. 5776 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5777 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5778 continue; 5779 } 5780 } 5781 5782 // Don't apply dllimport attributes to static data members of class template 5783 // instantiations when the attribute is propagated from a derived class. 5784 if (VD && PropagatedImport) 5785 continue; 5786 5787 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5788 continue; 5789 5790 if (!getDLLAttr(Member)) { 5791 InheritableAttr *NewAttr = nullptr; 5792 5793 // Do not export/import inline function when -fno-dllexport-inlines is 5794 // passed. But add attribute for later local static var check. 5795 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 5796 TSK != TSK_ExplicitInstantiationDeclaration && 5797 TSK != TSK_ExplicitInstantiationDefinition) { 5798 if (ClassExported) { 5799 NewAttr = ::new (getASTContext()) 5800 DLLExportStaticLocalAttr(ClassAttr->getRange(), 5801 getASTContext(), 5802 ClassAttr->getSpellingListIndex()); 5803 } else { 5804 NewAttr = ::new (getASTContext()) 5805 DLLImportStaticLocalAttr(ClassAttr->getRange(), 5806 getASTContext(), 5807 ClassAttr->getSpellingListIndex()); 5808 } 5809 } else { 5810 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5811 } 5812 5813 NewAttr->setInherited(true); 5814 Member->addAttr(NewAttr); 5815 5816 if (MD) { 5817 // Propagate DLLAttr to friend re-declarations of MD that have already 5818 // been constructed. 5819 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5820 FD = FD->getPreviousDecl()) { 5821 if (FD->getFriendObjectKind() == Decl::FOK_None) 5822 continue; 5823 assert(!getDLLAttr(FD) && 5824 "friend re-decl should not already have a DLLAttr"); 5825 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5826 NewAttr->setInherited(true); 5827 FD->addAttr(NewAttr); 5828 } 5829 } 5830 } 5831 } 5832 5833 if (ClassExported) 5834 DelayedDllExportClasses.push_back(Class); 5835 } 5836 5837 /// Perform propagation of DLL attributes from a derived class to a 5838 /// templated base class for MS compatibility. 5839 void Sema::propagateDLLAttrToBaseClassTemplate( 5840 CXXRecordDecl *Class, Attr *ClassAttr, 5841 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5842 if (getDLLAttr( 5843 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5844 // If the base class template has a DLL attribute, don't try to change it. 5845 return; 5846 } 5847 5848 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5849 if (!getDLLAttr(BaseTemplateSpec) && 5850 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5851 TSK == TSK_ImplicitInstantiation)) { 5852 // The template hasn't been instantiated yet (or it has, but only as an 5853 // explicit instantiation declaration or implicit instantiation, which means 5854 // we haven't codegenned any members yet), so propagate the attribute. 5855 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5856 NewAttr->setInherited(true); 5857 BaseTemplateSpec->addAttr(NewAttr); 5858 5859 // If this was an import, mark that we propagated it from a derived class to 5860 // a base class template specialization. 5861 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 5862 ImportAttr->setPropagatedToBaseTemplate(); 5863 5864 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5865 // needs to be run again to work see the new attribute. Otherwise this will 5866 // get run whenever the template is instantiated. 5867 if (TSK != TSK_Undeclared) 5868 checkClassLevelDLLAttribute(BaseTemplateSpec); 5869 5870 return; 5871 } 5872 5873 if (getDLLAttr(BaseTemplateSpec)) { 5874 // The template has already been specialized or instantiated with an 5875 // attribute, explicitly or through propagation. We should not try to change 5876 // it. 5877 return; 5878 } 5879 5880 // The template was previously instantiated or explicitly specialized without 5881 // a dll attribute, It's too late for us to add an attribute, so warn that 5882 // this is unsupported. 5883 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5884 << BaseTemplateSpec->isExplicitSpecialization(); 5885 Diag(ClassAttr->getLocation(), diag::note_attribute); 5886 if (BaseTemplateSpec->isExplicitSpecialization()) { 5887 Diag(BaseTemplateSpec->getLocation(), 5888 diag::note_template_class_explicit_specialization_was_here) 5889 << BaseTemplateSpec; 5890 } else { 5891 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5892 diag::note_template_class_instantiation_was_here) 5893 << BaseTemplateSpec; 5894 } 5895 } 5896 5897 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5898 SourceLocation DefaultLoc) { 5899 switch (S.getSpecialMember(MD)) { 5900 case Sema::CXXDefaultConstructor: 5901 S.DefineImplicitDefaultConstructor(DefaultLoc, 5902 cast<CXXConstructorDecl>(MD)); 5903 break; 5904 case Sema::CXXCopyConstructor: 5905 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5906 break; 5907 case Sema::CXXCopyAssignment: 5908 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5909 break; 5910 case Sema::CXXDestructor: 5911 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5912 break; 5913 case Sema::CXXMoveConstructor: 5914 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5915 break; 5916 case Sema::CXXMoveAssignment: 5917 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5918 break; 5919 case Sema::CXXInvalid: 5920 llvm_unreachable("Invalid special member."); 5921 } 5922 } 5923 5924 /// Determine whether a type is permitted to be passed or returned in 5925 /// registers, per C++ [class.temporary]p3. 5926 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 5927 TargetInfo::CallingConvKind CCK) { 5928 if (D->isDependentType() || D->isInvalidDecl()) 5929 return false; 5930 5931 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 5932 // The PS4 platform ABI follows the behavior of Clang 3.2. 5933 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 5934 return !D->hasNonTrivialDestructorForCall() && 5935 !D->hasNonTrivialCopyConstructorForCall(); 5936 5937 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 5938 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 5939 bool DtorIsTrivialForCall = false; 5940 5941 // If a class has at least one non-deleted, trivial copy constructor, it 5942 // is passed according to the C ABI. Otherwise, it is passed indirectly. 5943 // 5944 // Note: This permits classes with non-trivial copy or move ctors to be 5945 // passed in registers, so long as they *also* have a trivial copy ctor, 5946 // which is non-conforming. 5947 if (D->needsImplicitCopyConstructor()) { 5948 if (!D->defaultedCopyConstructorIsDeleted()) { 5949 if (D->hasTrivialCopyConstructor()) 5950 CopyCtorIsTrivial = true; 5951 if (D->hasTrivialCopyConstructorForCall()) 5952 CopyCtorIsTrivialForCall = true; 5953 } 5954 } else { 5955 for (const CXXConstructorDecl *CD : D->ctors()) { 5956 if (CD->isCopyConstructor() && !CD->isDeleted()) { 5957 if (CD->isTrivial()) 5958 CopyCtorIsTrivial = true; 5959 if (CD->isTrivialForCall()) 5960 CopyCtorIsTrivialForCall = true; 5961 } 5962 } 5963 } 5964 5965 if (D->needsImplicitDestructor()) { 5966 if (!D->defaultedDestructorIsDeleted() && 5967 D->hasTrivialDestructorForCall()) 5968 DtorIsTrivialForCall = true; 5969 } else if (const auto *DD = D->getDestructor()) { 5970 if (!DD->isDeleted() && DD->isTrivialForCall()) 5971 DtorIsTrivialForCall = true; 5972 } 5973 5974 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 5975 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 5976 return true; 5977 5978 // If a class has a destructor, we'd really like to pass it indirectly 5979 // because it allows us to elide copies. Unfortunately, MSVC makes that 5980 // impossible for small types, which it will pass in a single register or 5981 // stack slot. Most objects with dtors are large-ish, so handle that early. 5982 // We can't call out all large objects as being indirect because there are 5983 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 5984 // how we pass large POD types. 5985 5986 // Note: This permits small classes with nontrivial destructors to be 5987 // passed in registers, which is non-conforming. 5988 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 5989 uint64_t TypeSize = isAArch64 ? 128 : 64; 5990 5991 if (CopyCtorIsTrivial && 5992 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 5993 return true; 5994 return false; 5995 } 5996 5997 // Per C++ [class.temporary]p3, the relevant condition is: 5998 // each copy constructor, move constructor, and destructor of X is 5999 // either trivial or deleted, and X has at least one non-deleted copy 6000 // or move constructor 6001 bool HasNonDeletedCopyOrMove = false; 6002 6003 if (D->needsImplicitCopyConstructor() && 6004 !D->defaultedCopyConstructorIsDeleted()) { 6005 if (!D->hasTrivialCopyConstructorForCall()) 6006 return false; 6007 HasNonDeletedCopyOrMove = true; 6008 } 6009 6010 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6011 !D->defaultedMoveConstructorIsDeleted()) { 6012 if (!D->hasTrivialMoveConstructorForCall()) 6013 return false; 6014 HasNonDeletedCopyOrMove = true; 6015 } 6016 6017 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6018 !D->hasTrivialDestructorForCall()) 6019 return false; 6020 6021 for (const CXXMethodDecl *MD : D->methods()) { 6022 if (MD->isDeleted()) 6023 continue; 6024 6025 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6026 if (CD && CD->isCopyOrMoveConstructor()) 6027 HasNonDeletedCopyOrMove = true; 6028 else if (!isa<CXXDestructorDecl>(MD)) 6029 continue; 6030 6031 if (!MD->isTrivialForCall()) 6032 return false; 6033 } 6034 6035 return HasNonDeletedCopyOrMove; 6036 } 6037 6038 /// Perform semantic checks on a class definition that has been 6039 /// completing, introducing implicitly-declared members, checking for 6040 /// abstract types, etc. 6041 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 6042 if (!Record) 6043 return; 6044 6045 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6046 AbstractUsageInfo Info(*this, Record); 6047 CheckAbstractClassUsage(Info, Record); 6048 } 6049 6050 // If this is not an aggregate type and has no user-declared constructor, 6051 // complain about any non-static data members of reference or const scalar 6052 // type, since they will never get initializers. 6053 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6054 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6055 !Record->isLambda()) { 6056 bool Complained = false; 6057 for (const auto *F : Record->fields()) { 6058 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6059 continue; 6060 6061 if (F->getType()->isReferenceType() || 6062 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6063 if (!Complained) { 6064 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6065 << Record->getTagKind() << Record; 6066 Complained = true; 6067 } 6068 6069 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6070 << F->getType()->isReferenceType() 6071 << F->getDeclName(); 6072 } 6073 } 6074 } 6075 6076 if (Record->getIdentifier()) { 6077 // C++ [class.mem]p13: 6078 // If T is the name of a class, then each of the following shall have a 6079 // name different from T: 6080 // - every member of every anonymous union that is a member of class T. 6081 // 6082 // C++ [class.mem]p14: 6083 // In addition, if class T has a user-declared constructor (12.1), every 6084 // non-static data member of class T shall have a name different from T. 6085 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6086 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6087 ++I) { 6088 NamedDecl *D = (*I)->getUnderlyingDecl(); 6089 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6090 Record->hasUserDeclaredConstructor()) || 6091 isa<IndirectFieldDecl>(D)) { 6092 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6093 << D->getDeclName(); 6094 break; 6095 } 6096 } 6097 } 6098 6099 // Warn if the class has virtual methods but non-virtual public destructor. 6100 if (Record->isPolymorphic() && !Record->isDependentType()) { 6101 CXXDestructorDecl *dtor = Record->getDestructor(); 6102 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6103 !Record->hasAttr<FinalAttr>()) 6104 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6105 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6106 } 6107 6108 if (Record->isAbstract()) { 6109 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6110 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6111 << FA->isSpelledAsSealed(); 6112 DiagnoseAbstractType(Record); 6113 } 6114 } 6115 6116 // See if trivial_abi has to be dropped. 6117 if (Record->hasAttr<TrivialABIAttr>()) 6118 checkIllFormedTrivialABIStruct(*Record); 6119 6120 // Set HasTrivialSpecialMemberForCall if the record has attribute 6121 // "trivial_abi". 6122 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6123 6124 if (HasTrivialABI) 6125 Record->setHasTrivialSpecialMemberForCall(); 6126 6127 bool HasMethodWithOverrideControl = false, 6128 HasOverridingMethodWithoutOverrideControl = false; 6129 if (!Record->isDependentType()) { 6130 for (auto *M : Record->methods()) { 6131 // See if a method overloads virtual methods in a base 6132 // class without overriding any. 6133 if (!M->isStatic()) 6134 DiagnoseHiddenVirtualMethods(M); 6135 if (M->hasAttr<OverrideAttr>()) 6136 HasMethodWithOverrideControl = true; 6137 else if (M->size_overridden_methods() > 0) 6138 HasOverridingMethodWithoutOverrideControl = true; 6139 // Check whether the explicitly-defaulted special members are valid. 6140 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6141 CheckExplicitlyDefaultedSpecialMember(M); 6142 6143 // For an explicitly defaulted or deleted special member, we defer 6144 // determining triviality until the class is complete. That time is now! 6145 CXXSpecialMember CSM = getSpecialMember(M); 6146 if (!M->isImplicit() && !M->isUserProvided()) { 6147 if (CSM != CXXInvalid) { 6148 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6149 // Inform the class that we've finished declaring this member. 6150 Record->finishedDefaultedOrDeletedMember(M); 6151 M->setTrivialForCall( 6152 HasTrivialABI || 6153 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6154 Record->setTrivialForCallFlags(M); 6155 } 6156 } 6157 6158 // Set triviality for the purpose of calls if this is a user-provided 6159 // copy/move constructor or destructor. 6160 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6161 CSM == CXXDestructor) && M->isUserProvided()) { 6162 M->setTrivialForCall(HasTrivialABI); 6163 Record->setTrivialForCallFlags(M); 6164 } 6165 6166 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6167 M->hasAttr<DLLExportAttr>()) { 6168 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6169 M->isTrivial() && 6170 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6171 CSM == CXXDestructor)) 6172 M->dropAttr<DLLExportAttr>(); 6173 6174 if (M->hasAttr<DLLExportAttr>()) { 6175 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6176 ActOnFinishInlineFunctionDef(M); 6177 } 6178 } 6179 } 6180 } 6181 6182 if (HasMethodWithOverrideControl && 6183 HasOverridingMethodWithoutOverrideControl) { 6184 // At least one method has the 'override' control declared. 6185 // Diagnose all other overridden methods which do not have 'override' specified on them. 6186 for (auto *M : Record->methods()) 6187 DiagnoseAbsenceOfOverrideControl(M); 6188 } 6189 6190 // ms_struct is a request to use the same ABI rules as MSVC. Check 6191 // whether this class uses any C++ features that are implemented 6192 // completely differently in MSVC, and if so, emit a diagnostic. 6193 // That diagnostic defaults to an error, but we allow projects to 6194 // map it down to a warning (or ignore it). It's a fairly common 6195 // practice among users of the ms_struct pragma to mass-annotate 6196 // headers, sweeping up a bunch of types that the project doesn't 6197 // really rely on MSVC-compatible layout for. We must therefore 6198 // support "ms_struct except for C++ stuff" as a secondary ABI. 6199 if (Record->isMsStruct(Context) && 6200 (Record->isPolymorphic() || Record->getNumBases())) { 6201 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6202 } 6203 6204 checkClassLevelDLLAttribute(Record); 6205 checkClassLevelCodeSegAttribute(Record); 6206 6207 bool ClangABICompat4 = 6208 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6209 TargetInfo::CallingConvKind CCK = 6210 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6211 bool CanPass = canPassInRegisters(*this, Record, CCK); 6212 6213 // Do not change ArgPassingRestrictions if it has already been set to 6214 // APK_CanNeverPassInRegs. 6215 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6216 Record->setArgPassingRestrictions(CanPass 6217 ? RecordDecl::APK_CanPassInRegs 6218 : RecordDecl::APK_CannotPassInRegs); 6219 6220 // If canPassInRegisters returns true despite the record having a non-trivial 6221 // destructor, the record is destructed in the callee. This happens only when 6222 // the record or one of its subobjects has a field annotated with trivial_abi 6223 // or a field qualified with ObjC __strong/__weak. 6224 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6225 Record->setParamDestroyedInCallee(true); 6226 else if (Record->hasNonTrivialDestructor()) 6227 Record->setParamDestroyedInCallee(CanPass); 6228 6229 if (getLangOpts().ForceEmitVTables) { 6230 // If we want to emit all the vtables, we need to mark it as used. This 6231 // is especially required for cases like vtable assumption loads. 6232 MarkVTableUsed(Record->getInnerLocStart(), Record); 6233 } 6234 } 6235 6236 /// Look up the special member function that would be called by a special 6237 /// member function for a subobject of class type. 6238 /// 6239 /// \param Class The class type of the subobject. 6240 /// \param CSM The kind of special member function. 6241 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6242 /// \param ConstRHS True if this is a copy operation with a const object 6243 /// on its RHS, that is, if the argument to the outer special member 6244 /// function is 'const' and this is not a field marked 'mutable'. 6245 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6246 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6247 unsigned FieldQuals, bool ConstRHS) { 6248 unsigned LHSQuals = 0; 6249 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6250 LHSQuals = FieldQuals; 6251 6252 unsigned RHSQuals = FieldQuals; 6253 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6254 RHSQuals = 0; 6255 else if (ConstRHS) 6256 RHSQuals |= Qualifiers::Const; 6257 6258 return S.LookupSpecialMember(Class, CSM, 6259 RHSQuals & Qualifiers::Const, 6260 RHSQuals & Qualifiers::Volatile, 6261 false, 6262 LHSQuals & Qualifiers::Const, 6263 LHSQuals & Qualifiers::Volatile); 6264 } 6265 6266 class Sema::InheritedConstructorInfo { 6267 Sema &S; 6268 SourceLocation UseLoc; 6269 6270 /// A mapping from the base classes through which the constructor was 6271 /// inherited to the using shadow declaration in that base class (or a null 6272 /// pointer if the constructor was declared in that base class). 6273 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6274 InheritedFromBases; 6275 6276 public: 6277 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6278 ConstructorUsingShadowDecl *Shadow) 6279 : S(S), UseLoc(UseLoc) { 6280 bool DiagnosedMultipleConstructedBases = false; 6281 CXXRecordDecl *ConstructedBase = nullptr; 6282 UsingDecl *ConstructedBaseUsing = nullptr; 6283 6284 // Find the set of such base class subobjects and check that there's a 6285 // unique constructed subobject. 6286 for (auto *D : Shadow->redecls()) { 6287 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6288 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6289 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6290 6291 InheritedFromBases.insert( 6292 std::make_pair(DNominatedBase->getCanonicalDecl(), 6293 DShadow->getNominatedBaseClassShadowDecl())); 6294 if (DShadow->constructsVirtualBase()) 6295 InheritedFromBases.insert( 6296 std::make_pair(DConstructedBase->getCanonicalDecl(), 6297 DShadow->getConstructedBaseClassShadowDecl())); 6298 else 6299 assert(DNominatedBase == DConstructedBase); 6300 6301 // [class.inhctor.init]p2: 6302 // If the constructor was inherited from multiple base class subobjects 6303 // of type B, the program is ill-formed. 6304 if (!ConstructedBase) { 6305 ConstructedBase = DConstructedBase; 6306 ConstructedBaseUsing = D->getUsingDecl(); 6307 } else if (ConstructedBase != DConstructedBase && 6308 !Shadow->isInvalidDecl()) { 6309 if (!DiagnosedMultipleConstructedBases) { 6310 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6311 << Shadow->getTargetDecl(); 6312 S.Diag(ConstructedBaseUsing->getLocation(), 6313 diag::note_ambiguous_inherited_constructor_using) 6314 << ConstructedBase; 6315 DiagnosedMultipleConstructedBases = true; 6316 } 6317 S.Diag(D->getUsingDecl()->getLocation(), 6318 diag::note_ambiguous_inherited_constructor_using) 6319 << DConstructedBase; 6320 } 6321 } 6322 6323 if (DiagnosedMultipleConstructedBases) 6324 Shadow->setInvalidDecl(); 6325 } 6326 6327 /// Find the constructor to use for inherited construction of a base class, 6328 /// and whether that base class constructor inherits the constructor from a 6329 /// virtual base class (in which case it won't actually invoke it). 6330 std::pair<CXXConstructorDecl *, bool> 6331 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6332 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6333 if (It == InheritedFromBases.end()) 6334 return std::make_pair(nullptr, false); 6335 6336 // This is an intermediary class. 6337 if (It->second) 6338 return std::make_pair( 6339 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6340 It->second->constructsVirtualBase()); 6341 6342 // This is the base class from which the constructor was inherited. 6343 return std::make_pair(Ctor, false); 6344 } 6345 }; 6346 6347 /// Is the special member function which would be selected to perform the 6348 /// specified operation on the specified class type a constexpr constructor? 6349 static bool 6350 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6351 Sema::CXXSpecialMember CSM, unsigned Quals, 6352 bool ConstRHS, 6353 CXXConstructorDecl *InheritedCtor = nullptr, 6354 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6355 // If we're inheriting a constructor, see if we need to call it for this base 6356 // class. 6357 if (InheritedCtor) { 6358 assert(CSM == Sema::CXXDefaultConstructor); 6359 auto BaseCtor = 6360 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6361 if (BaseCtor) 6362 return BaseCtor->isConstexpr(); 6363 } 6364 6365 if (CSM == Sema::CXXDefaultConstructor) 6366 return ClassDecl->hasConstexprDefaultConstructor(); 6367 6368 Sema::SpecialMemberOverloadResult SMOR = 6369 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6370 if (!SMOR.getMethod()) 6371 // A constructor we wouldn't select can't be "involved in initializing" 6372 // anything. 6373 return true; 6374 return SMOR.getMethod()->isConstexpr(); 6375 } 6376 6377 /// Determine whether the specified special member function would be constexpr 6378 /// if it were implicitly defined. 6379 static bool defaultedSpecialMemberIsConstexpr( 6380 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6381 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6382 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6383 if (!S.getLangOpts().CPlusPlus11) 6384 return false; 6385 6386 // C++11 [dcl.constexpr]p4: 6387 // In the definition of a constexpr constructor [...] 6388 bool Ctor = true; 6389 switch (CSM) { 6390 case Sema::CXXDefaultConstructor: 6391 if (Inherited) 6392 break; 6393 // Since default constructor lookup is essentially trivial (and cannot 6394 // involve, for instance, template instantiation), we compute whether a 6395 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6396 // 6397 // This is important for performance; we need to know whether the default 6398 // constructor is constexpr to determine whether the type is a literal type. 6399 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6400 6401 case Sema::CXXCopyConstructor: 6402 case Sema::CXXMoveConstructor: 6403 // For copy or move constructors, we need to perform overload resolution. 6404 break; 6405 6406 case Sema::CXXCopyAssignment: 6407 case Sema::CXXMoveAssignment: 6408 if (!S.getLangOpts().CPlusPlus14) 6409 return false; 6410 // In C++1y, we need to perform overload resolution. 6411 Ctor = false; 6412 break; 6413 6414 case Sema::CXXDestructor: 6415 case Sema::CXXInvalid: 6416 return false; 6417 } 6418 6419 // -- if the class is a non-empty union, or for each non-empty anonymous 6420 // union member of a non-union class, exactly one non-static data member 6421 // shall be initialized; [DR1359] 6422 // 6423 // If we squint, this is guaranteed, since exactly one non-static data member 6424 // will be initialized (if the constructor isn't deleted), we just don't know 6425 // which one. 6426 if (Ctor && ClassDecl->isUnion()) 6427 return CSM == Sema::CXXDefaultConstructor 6428 ? ClassDecl->hasInClassInitializer() || 6429 !ClassDecl->hasVariantMembers() 6430 : true; 6431 6432 // -- the class shall not have any virtual base classes; 6433 if (Ctor && ClassDecl->getNumVBases()) 6434 return false; 6435 6436 // C++1y [class.copy]p26: 6437 // -- [the class] is a literal type, and 6438 if (!Ctor && !ClassDecl->isLiteral()) 6439 return false; 6440 6441 // -- every constructor involved in initializing [...] base class 6442 // sub-objects shall be a constexpr constructor; 6443 // -- the assignment operator selected to copy/move each direct base 6444 // class is a constexpr function, and 6445 for (const auto &B : ClassDecl->bases()) { 6446 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6447 if (!BaseType) continue; 6448 6449 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6450 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6451 InheritedCtor, Inherited)) 6452 return false; 6453 } 6454 6455 // -- every constructor involved in initializing non-static data members 6456 // [...] shall be a constexpr constructor; 6457 // -- every non-static data member and base class sub-object shall be 6458 // initialized 6459 // -- for each non-static data member of X that is of class type (or array 6460 // thereof), the assignment operator selected to copy/move that member is 6461 // a constexpr function 6462 for (const auto *F : ClassDecl->fields()) { 6463 if (F->isInvalidDecl()) 6464 continue; 6465 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6466 continue; 6467 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6468 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6469 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6470 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6471 BaseType.getCVRQualifiers(), 6472 ConstArg && !F->isMutable())) 6473 return false; 6474 } else if (CSM == Sema::CXXDefaultConstructor) { 6475 return false; 6476 } 6477 } 6478 6479 // All OK, it's constexpr! 6480 return true; 6481 } 6482 6483 static Sema::ImplicitExceptionSpecification 6484 ComputeDefaultedSpecialMemberExceptionSpec( 6485 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6486 Sema::InheritedConstructorInfo *ICI); 6487 6488 static Sema::ImplicitExceptionSpecification 6489 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6490 auto CSM = S.getSpecialMember(MD); 6491 if (CSM != Sema::CXXInvalid) 6492 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6493 6494 auto *CD = cast<CXXConstructorDecl>(MD); 6495 assert(CD->getInheritedConstructor() && 6496 "only special members have implicit exception specs"); 6497 Sema::InheritedConstructorInfo ICI( 6498 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6499 return ComputeDefaultedSpecialMemberExceptionSpec( 6500 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6501 } 6502 6503 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6504 CXXMethodDecl *MD) { 6505 FunctionProtoType::ExtProtoInfo EPI; 6506 6507 // Build an exception specification pointing back at this member. 6508 EPI.ExceptionSpec.Type = EST_Unevaluated; 6509 EPI.ExceptionSpec.SourceDecl = MD; 6510 6511 // Set the calling convention to the default for C++ instance methods. 6512 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6513 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6514 /*IsCXXMethod=*/true)); 6515 return EPI; 6516 } 6517 6518 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6519 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6520 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6521 return; 6522 6523 // Evaluate the exception specification. 6524 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6525 auto ESI = IES.getExceptionSpec(); 6526 6527 // Update the type of the special member to use it. 6528 UpdateExceptionSpec(MD, ESI); 6529 6530 // A user-provided destructor can be defined outside the class. When that 6531 // happens, be sure to update the exception specification on both 6532 // declarations. 6533 const FunctionProtoType *CanonicalFPT = 6534 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6535 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6536 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6537 } 6538 6539 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6540 CXXRecordDecl *RD = MD->getParent(); 6541 CXXSpecialMember CSM = getSpecialMember(MD); 6542 6543 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6544 "not an explicitly-defaulted special member"); 6545 6546 // Whether this was the first-declared instance of the constructor. 6547 // This affects whether we implicitly add an exception spec and constexpr. 6548 bool First = MD == MD->getCanonicalDecl(); 6549 6550 bool HadError = false; 6551 6552 // C++11 [dcl.fct.def.default]p1: 6553 // A function that is explicitly defaulted shall 6554 // -- be a special member function (checked elsewhere), 6555 // -- have the same type (except for ref-qualifiers, and except that a 6556 // copy operation can take a non-const reference) as an implicit 6557 // declaration, and 6558 // -- not have default arguments. 6559 // C++2a changes the second bullet to instead delete the function if it's 6560 // defaulted on its first declaration, unless it's "an assignment operator, 6561 // and its return type differs or its parameter type is not a reference". 6562 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6563 bool ShouldDeleteForTypeMismatch = false; 6564 unsigned ExpectedParams = 1; 6565 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6566 ExpectedParams = 0; 6567 if (MD->getNumParams() != ExpectedParams) { 6568 // This checks for default arguments: a copy or move constructor with a 6569 // default argument is classified as a default constructor, and assignment 6570 // operations and destructors can't have default arguments. 6571 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6572 << CSM << MD->getSourceRange(); 6573 HadError = true; 6574 } else if (MD->isVariadic()) { 6575 if (DeleteOnTypeMismatch) 6576 ShouldDeleteForTypeMismatch = true; 6577 else { 6578 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6579 << CSM << MD->getSourceRange(); 6580 HadError = true; 6581 } 6582 } 6583 6584 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6585 6586 bool CanHaveConstParam = false; 6587 if (CSM == CXXCopyConstructor) 6588 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6589 else if (CSM == CXXCopyAssignment) 6590 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6591 6592 QualType ReturnType = Context.VoidTy; 6593 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6594 // Check for return type matching. 6595 ReturnType = Type->getReturnType(); 6596 6597 QualType DeclType = Context.getTypeDeclType(RD); 6598 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 6599 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6600 6601 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6602 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6603 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6604 HadError = true; 6605 } 6606 6607 // A defaulted special member cannot have cv-qualifiers. 6608 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 6609 if (DeleteOnTypeMismatch) 6610 ShouldDeleteForTypeMismatch = true; 6611 else { 6612 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6613 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6614 HadError = true; 6615 } 6616 } 6617 } 6618 6619 // Check for parameter type matching. 6620 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6621 bool HasConstParam = false; 6622 if (ExpectedParams && ArgType->isReferenceType()) { 6623 // Argument must be reference to possibly-const T. 6624 QualType ReferentType = ArgType->getPointeeType(); 6625 HasConstParam = ReferentType.isConstQualified(); 6626 6627 if (ReferentType.isVolatileQualified()) { 6628 if (DeleteOnTypeMismatch) 6629 ShouldDeleteForTypeMismatch = true; 6630 else { 6631 Diag(MD->getLocation(), 6632 diag::err_defaulted_special_member_volatile_param) << CSM; 6633 HadError = true; 6634 } 6635 } 6636 6637 if (HasConstParam && !CanHaveConstParam) { 6638 if (DeleteOnTypeMismatch) 6639 ShouldDeleteForTypeMismatch = true; 6640 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6641 Diag(MD->getLocation(), 6642 diag::err_defaulted_special_member_copy_const_param) 6643 << (CSM == CXXCopyAssignment); 6644 // FIXME: Explain why this special member can't be const. 6645 HadError = true; 6646 } else { 6647 Diag(MD->getLocation(), 6648 diag::err_defaulted_special_member_move_const_param) 6649 << (CSM == CXXMoveAssignment); 6650 HadError = true; 6651 } 6652 } 6653 } else if (ExpectedParams) { 6654 // A copy assignment operator can take its argument by value, but a 6655 // defaulted one cannot. 6656 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6657 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6658 HadError = true; 6659 } 6660 6661 // C++11 [dcl.fct.def.default]p2: 6662 // An explicitly-defaulted function may be declared constexpr only if it 6663 // would have been implicitly declared as constexpr, 6664 // Do not apply this rule to members of class templates, since core issue 1358 6665 // makes such functions always instantiate to constexpr functions. For 6666 // functions which cannot be constexpr (for non-constructors in C++11 and for 6667 // destructors in C++1y), this is checked elsewhere. 6668 // 6669 // FIXME: This should not apply if the member is deleted. 6670 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6671 HasConstParam); 6672 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6673 : isa<CXXConstructorDecl>(MD)) && 6674 MD->isConstexpr() && !Constexpr && 6675 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6676 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM; 6677 // FIXME: Explain why the special member can't be constexpr. 6678 HadError = true; 6679 } 6680 6681 if (First) { 6682 // C++2a [dcl.fct.def.default]p3: 6683 // If a function is explicitly defaulted on its first declaration, it is 6684 // implicitly considered to be constexpr if the implicit declaration 6685 // would be. 6686 MD->setConstexpr(Constexpr); 6687 6688 if (!Type->hasExceptionSpec()) { 6689 // C++2a [except.spec]p3: 6690 // If a declaration of a function does not have a noexcept-specifier 6691 // [and] is defaulted on its first declaration, [...] the exception 6692 // specification is as specified below 6693 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6694 EPI.ExceptionSpec.Type = EST_Unevaluated; 6695 EPI.ExceptionSpec.SourceDecl = MD; 6696 MD->setType(Context.getFunctionType(ReturnType, 6697 llvm::makeArrayRef(&ArgType, 6698 ExpectedParams), 6699 EPI)); 6700 } 6701 } 6702 6703 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 6704 if (First) { 6705 SetDeclDeleted(MD, MD->getLocation()); 6706 if (!inTemplateInstantiation() && !HadError) { 6707 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 6708 if (ShouldDeleteForTypeMismatch) { 6709 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 6710 } else { 6711 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6712 } 6713 } 6714 if (ShouldDeleteForTypeMismatch && !HadError) { 6715 Diag(MD->getLocation(), 6716 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 6717 } 6718 } else { 6719 // C++11 [dcl.fct.def.default]p4: 6720 // [For a] user-provided explicitly-defaulted function [...] if such a 6721 // function is implicitly defined as deleted, the program is ill-formed. 6722 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6723 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 6724 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6725 HadError = true; 6726 } 6727 } 6728 6729 if (HadError) 6730 MD->setInvalidDecl(); 6731 } 6732 6733 void Sema::CheckDelayedMemberExceptionSpecs() { 6734 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 6735 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 6736 6737 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 6738 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 6739 6740 // Perform any deferred checking of exception specifications for virtual 6741 // destructors. 6742 for (auto &Check : Overriding) 6743 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6744 6745 // Perform any deferred checking of exception specifications for befriended 6746 // special members. 6747 for (auto &Check : Equivalent) 6748 CheckEquivalentExceptionSpec(Check.second, Check.first); 6749 } 6750 6751 namespace { 6752 /// CRTP base class for visiting operations performed by a special member 6753 /// function (or inherited constructor). 6754 template<typename Derived> 6755 struct SpecialMemberVisitor { 6756 Sema &S; 6757 CXXMethodDecl *MD; 6758 Sema::CXXSpecialMember CSM; 6759 Sema::InheritedConstructorInfo *ICI; 6760 6761 // Properties of the special member, computed for convenience. 6762 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6763 6764 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6765 Sema::InheritedConstructorInfo *ICI) 6766 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6767 switch (CSM) { 6768 case Sema::CXXDefaultConstructor: 6769 case Sema::CXXCopyConstructor: 6770 case Sema::CXXMoveConstructor: 6771 IsConstructor = true; 6772 break; 6773 case Sema::CXXCopyAssignment: 6774 case Sema::CXXMoveAssignment: 6775 IsAssignment = true; 6776 break; 6777 case Sema::CXXDestructor: 6778 break; 6779 case Sema::CXXInvalid: 6780 llvm_unreachable("invalid special member kind"); 6781 } 6782 6783 if (MD->getNumParams()) { 6784 if (const ReferenceType *RT = 6785 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6786 ConstArg = RT->getPointeeType().isConstQualified(); 6787 } 6788 } 6789 6790 Derived &getDerived() { return static_cast<Derived&>(*this); } 6791 6792 /// Is this a "move" special member? 6793 bool isMove() const { 6794 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6795 } 6796 6797 /// Look up the corresponding special member in the given class. 6798 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6799 unsigned Quals, bool IsMutable) { 6800 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6801 ConstArg && !IsMutable); 6802 } 6803 6804 /// Look up the constructor for the specified base class to see if it's 6805 /// overridden due to this being an inherited constructor. 6806 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6807 if (!ICI) 6808 return {}; 6809 assert(CSM == Sema::CXXDefaultConstructor); 6810 auto *BaseCtor = 6811 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6812 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6813 return MD; 6814 return {}; 6815 } 6816 6817 /// A base or member subobject. 6818 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6819 6820 /// Get the location to use for a subobject in diagnostics. 6821 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6822 // FIXME: For an indirect virtual base, the direct base leading to 6823 // the indirect virtual base would be a more useful choice. 6824 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6825 return B->getBaseTypeLoc(); 6826 else 6827 return Subobj.get<FieldDecl*>()->getLocation(); 6828 } 6829 6830 enum BasesToVisit { 6831 /// Visit all non-virtual (direct) bases. 6832 VisitNonVirtualBases, 6833 /// Visit all direct bases, virtual or not. 6834 VisitDirectBases, 6835 /// Visit all non-virtual bases, and all virtual bases if the class 6836 /// is not abstract. 6837 VisitPotentiallyConstructedBases, 6838 /// Visit all direct or virtual bases. 6839 VisitAllBases 6840 }; 6841 6842 // Visit the bases and members of the class. 6843 bool visit(BasesToVisit Bases) { 6844 CXXRecordDecl *RD = MD->getParent(); 6845 6846 if (Bases == VisitPotentiallyConstructedBases) 6847 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6848 6849 for (auto &B : RD->bases()) 6850 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6851 getDerived().visitBase(&B)) 6852 return true; 6853 6854 if (Bases == VisitAllBases) 6855 for (auto &B : RD->vbases()) 6856 if (getDerived().visitBase(&B)) 6857 return true; 6858 6859 for (auto *F : RD->fields()) 6860 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6861 getDerived().visitField(F)) 6862 return true; 6863 6864 return false; 6865 } 6866 }; 6867 } 6868 6869 namespace { 6870 struct SpecialMemberDeletionInfo 6871 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6872 bool Diagnose; 6873 6874 SourceLocation Loc; 6875 6876 bool AllFieldsAreConst; 6877 6878 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6879 Sema::CXXSpecialMember CSM, 6880 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6881 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6882 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6883 6884 bool inUnion() const { return MD->getParent()->isUnion(); } 6885 6886 Sema::CXXSpecialMember getEffectiveCSM() { 6887 return ICI ? Sema::CXXInvalid : CSM; 6888 } 6889 6890 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 6891 6892 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6893 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6894 6895 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6896 bool shouldDeleteForField(FieldDecl *FD); 6897 bool shouldDeleteForAllConstMembers(); 6898 6899 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6900 unsigned Quals); 6901 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6902 Sema::SpecialMemberOverloadResult SMOR, 6903 bool IsDtorCallInCtor); 6904 6905 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6906 }; 6907 } 6908 6909 /// Is the given special member inaccessible when used on the given 6910 /// sub-object. 6911 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6912 CXXMethodDecl *target) { 6913 /// If we're operating on a base class, the object type is the 6914 /// type of this special member. 6915 QualType objectTy; 6916 AccessSpecifier access = target->getAccess(); 6917 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6918 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6919 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6920 6921 // If we're operating on a field, the object type is the type of the field. 6922 } else { 6923 objectTy = S.Context.getTypeDeclType(target->getParent()); 6924 } 6925 6926 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6927 } 6928 6929 /// Check whether we should delete a special member due to the implicit 6930 /// definition containing a call to a special member of a subobject. 6931 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6932 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6933 bool IsDtorCallInCtor) { 6934 CXXMethodDecl *Decl = SMOR.getMethod(); 6935 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6936 6937 int DiagKind = -1; 6938 6939 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6940 DiagKind = !Decl ? 0 : 1; 6941 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6942 DiagKind = 2; 6943 else if (!isAccessible(Subobj, Decl)) 6944 DiagKind = 3; 6945 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6946 !Decl->isTrivial()) { 6947 // A member of a union must have a trivial corresponding special member. 6948 // As a weird special case, a destructor call from a union's constructor 6949 // must be accessible and non-deleted, but need not be trivial. Such a 6950 // destructor is never actually called, but is semantically checked as 6951 // if it were. 6952 DiagKind = 4; 6953 } 6954 6955 if (DiagKind == -1) 6956 return false; 6957 6958 if (Diagnose) { 6959 if (Field) { 6960 S.Diag(Field->getLocation(), 6961 diag::note_deleted_special_member_class_subobject) 6962 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6963 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 6964 } else { 6965 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6966 S.Diag(Base->getBeginLoc(), 6967 diag::note_deleted_special_member_class_subobject) 6968 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 6969 << Base->getType() << DiagKind << IsDtorCallInCtor 6970 << /*IsObjCPtr*/false; 6971 } 6972 6973 if (DiagKind == 1) 6974 S.NoteDeletedFunction(Decl); 6975 // FIXME: Explain inaccessibility if DiagKind == 3. 6976 } 6977 6978 return true; 6979 } 6980 6981 /// Check whether we should delete a special member function due to having a 6982 /// direct or virtual base class or non-static data member of class type M. 6983 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6984 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6985 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6986 bool IsMutable = Field && Field->isMutable(); 6987 6988 // C++11 [class.ctor]p5: 6989 // -- any direct or virtual base class, or non-static data member with no 6990 // brace-or-equal-initializer, has class type M (or array thereof) and 6991 // either M has no default constructor or overload resolution as applied 6992 // to M's default constructor results in an ambiguity or in a function 6993 // that is deleted or inaccessible 6994 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6995 // -- a direct or virtual base class B that cannot be copied/moved because 6996 // overload resolution, as applied to B's corresponding special member, 6997 // results in an ambiguity or a function that is deleted or inaccessible 6998 // from the defaulted special member 6999 // C++11 [class.dtor]p5: 7000 // -- any direct or virtual base class [...] has a type with a destructor 7001 // that is deleted or inaccessible 7002 if (!(CSM == Sema::CXXDefaultConstructor && 7003 Field && Field->hasInClassInitializer()) && 7004 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 7005 false)) 7006 return true; 7007 7008 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 7009 // -- any direct or virtual base class or non-static data member has a 7010 // type with a destructor that is deleted or inaccessible 7011 if (IsConstructor) { 7012 Sema::SpecialMemberOverloadResult SMOR = 7013 S.LookupSpecialMember(Class, Sema::CXXDestructor, 7014 false, false, false, false, false); 7015 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 7016 return true; 7017 } 7018 7019 return false; 7020 } 7021 7022 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 7023 FieldDecl *FD, QualType FieldType) { 7024 // The defaulted special functions are defined as deleted if this is a variant 7025 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 7026 // type under ARC. 7027 if (!FieldType.hasNonTrivialObjCLifetime()) 7028 return false; 7029 7030 // Don't make the defaulted default constructor defined as deleted if the 7031 // member has an in-class initializer. 7032 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 7033 return false; 7034 7035 if (Diagnose) { 7036 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 7037 S.Diag(FD->getLocation(), 7038 diag::note_deleted_special_member_class_subobject) 7039 << getEffectiveCSM() << ParentClass << /*IsField*/true 7040 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 7041 } 7042 7043 return true; 7044 } 7045 7046 /// Check whether we should delete a special member function due to the class 7047 /// having a particular direct or virtual base class. 7048 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 7049 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 7050 // If program is correct, BaseClass cannot be null, but if it is, the error 7051 // must be reported elsewhere. 7052 if (!BaseClass) 7053 return false; 7054 // If we have an inheriting constructor, check whether we're calling an 7055 // inherited constructor instead of a default constructor. 7056 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 7057 if (auto *BaseCtor = SMOR.getMethod()) { 7058 // Note that we do not check access along this path; other than that, 7059 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 7060 // FIXME: Check that the base has a usable destructor! Sink this into 7061 // shouldDeleteForClassSubobject. 7062 if (BaseCtor->isDeleted() && Diagnose) { 7063 S.Diag(Base->getBeginLoc(), 7064 diag::note_deleted_special_member_class_subobject) 7065 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7066 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 7067 << /*IsObjCPtr*/false; 7068 S.NoteDeletedFunction(BaseCtor); 7069 } 7070 return BaseCtor->isDeleted(); 7071 } 7072 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 7073 } 7074 7075 /// Check whether we should delete a special member function due to the class 7076 /// having a particular non-static data member. 7077 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 7078 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 7079 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 7080 7081 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 7082 return true; 7083 7084 if (CSM == Sema::CXXDefaultConstructor) { 7085 // For a default constructor, all references must be initialized in-class 7086 // and, if a union, it must have a non-const member. 7087 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 7088 if (Diagnose) 7089 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7090 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 7091 return true; 7092 } 7093 // C++11 [class.ctor]p5: any non-variant non-static data member of 7094 // const-qualified type (or array thereof) with no 7095 // brace-or-equal-initializer does not have a user-provided default 7096 // constructor. 7097 if (!inUnion() && FieldType.isConstQualified() && 7098 !FD->hasInClassInitializer() && 7099 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 7100 if (Diagnose) 7101 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7102 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 7103 return true; 7104 } 7105 7106 if (inUnion() && !FieldType.isConstQualified()) 7107 AllFieldsAreConst = false; 7108 } else if (CSM == Sema::CXXCopyConstructor) { 7109 // For a copy constructor, data members must not be of rvalue reference 7110 // type. 7111 if (FieldType->isRValueReferenceType()) { 7112 if (Diagnose) 7113 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 7114 << MD->getParent() << FD << FieldType; 7115 return true; 7116 } 7117 } else if (IsAssignment) { 7118 // For an assignment operator, data members must not be of reference type. 7119 if (FieldType->isReferenceType()) { 7120 if (Diagnose) 7121 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7122 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 7123 return true; 7124 } 7125 if (!FieldRecord && FieldType.isConstQualified()) { 7126 // C++11 [class.copy]p23: 7127 // -- a non-static data member of const non-class type (or array thereof) 7128 if (Diagnose) 7129 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7130 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7131 return true; 7132 } 7133 } 7134 7135 if (FieldRecord) { 7136 // Some additional restrictions exist on the variant members. 7137 if (!inUnion() && FieldRecord->isUnion() && 7138 FieldRecord->isAnonymousStructOrUnion()) { 7139 bool AllVariantFieldsAreConst = true; 7140 7141 // FIXME: Handle anonymous unions declared within anonymous unions. 7142 for (auto *UI : FieldRecord->fields()) { 7143 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7144 7145 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 7146 return true; 7147 7148 if (!UnionFieldType.isConstQualified()) 7149 AllVariantFieldsAreConst = false; 7150 7151 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7152 if (UnionFieldRecord && 7153 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7154 UnionFieldType.getCVRQualifiers())) 7155 return true; 7156 } 7157 7158 // At least one member in each anonymous union must be non-const 7159 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7160 !FieldRecord->field_empty()) { 7161 if (Diagnose) 7162 S.Diag(FieldRecord->getLocation(), 7163 diag::note_deleted_default_ctor_all_const) 7164 << !!ICI << MD->getParent() << /*anonymous union*/1; 7165 return true; 7166 } 7167 7168 // Don't check the implicit member of the anonymous union type. 7169 // This is technically non-conformant, but sanity demands it. 7170 return false; 7171 } 7172 7173 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7174 FieldType.getCVRQualifiers())) 7175 return true; 7176 } 7177 7178 return false; 7179 } 7180 7181 /// C++11 [class.ctor] p5: 7182 /// A defaulted default constructor for a class X is defined as deleted if 7183 /// X is a union and all of its variant members are of const-qualified type. 7184 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7185 // This is a silly definition, because it gives an empty union a deleted 7186 // default constructor. Don't do that. 7187 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7188 bool AnyFields = false; 7189 for (auto *F : MD->getParent()->fields()) 7190 if ((AnyFields = !F->isUnnamedBitfield())) 7191 break; 7192 if (!AnyFields) 7193 return false; 7194 if (Diagnose) 7195 S.Diag(MD->getParent()->getLocation(), 7196 diag::note_deleted_default_ctor_all_const) 7197 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7198 return true; 7199 } 7200 return false; 7201 } 7202 7203 /// Determine whether a defaulted special member function should be defined as 7204 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7205 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7206 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7207 InheritedConstructorInfo *ICI, 7208 bool Diagnose) { 7209 if (MD->isInvalidDecl()) 7210 return false; 7211 CXXRecordDecl *RD = MD->getParent(); 7212 assert(!RD->isDependentType() && "do deletion after instantiation"); 7213 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7214 return false; 7215 7216 // C++11 [expr.lambda.prim]p19: 7217 // The closure type associated with a lambda-expression has a 7218 // deleted (8.4.3) default constructor and a deleted copy 7219 // assignment operator. 7220 // C++2a adds back these operators if the lambda has no capture-default. 7221 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 7222 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7223 if (Diagnose) 7224 Diag(RD->getLocation(), diag::note_lambda_decl); 7225 return true; 7226 } 7227 7228 // For an anonymous struct or union, the copy and assignment special members 7229 // will never be used, so skip the check. For an anonymous union declared at 7230 // namespace scope, the constructor and destructor are used. 7231 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7232 RD->isAnonymousStructOrUnion()) 7233 return false; 7234 7235 // C++11 [class.copy]p7, p18: 7236 // If the class definition declares a move constructor or move assignment 7237 // operator, an implicitly declared copy constructor or copy assignment 7238 // operator is defined as deleted. 7239 if (MD->isImplicit() && 7240 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7241 CXXMethodDecl *UserDeclaredMove = nullptr; 7242 7243 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7244 // deletion of the corresponding copy operation, not both copy operations. 7245 // MSVC 2015 has adopted the standards conforming behavior. 7246 bool DeletesOnlyMatchingCopy = 7247 getLangOpts().MSVCCompat && 7248 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7249 7250 if (RD->hasUserDeclaredMoveConstructor() && 7251 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7252 if (!Diagnose) return true; 7253 7254 // Find any user-declared move constructor. 7255 for (auto *I : RD->ctors()) { 7256 if (I->isMoveConstructor()) { 7257 UserDeclaredMove = I; 7258 break; 7259 } 7260 } 7261 assert(UserDeclaredMove); 7262 } else if (RD->hasUserDeclaredMoveAssignment() && 7263 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7264 if (!Diagnose) return true; 7265 7266 // Find any user-declared move assignment operator. 7267 for (auto *I : RD->methods()) { 7268 if (I->isMoveAssignmentOperator()) { 7269 UserDeclaredMove = I; 7270 break; 7271 } 7272 } 7273 assert(UserDeclaredMove); 7274 } 7275 7276 if (UserDeclaredMove) { 7277 Diag(UserDeclaredMove->getLocation(), 7278 diag::note_deleted_copy_user_declared_move) 7279 << (CSM == CXXCopyAssignment) << RD 7280 << UserDeclaredMove->isMoveAssignmentOperator(); 7281 return true; 7282 } 7283 } 7284 7285 // Do access control from the special member function 7286 ContextRAII MethodContext(*this, MD); 7287 7288 // C++11 [class.dtor]p5: 7289 // -- for a virtual destructor, lookup of the non-array deallocation function 7290 // results in an ambiguity or in a function that is deleted or inaccessible 7291 if (CSM == CXXDestructor && MD->isVirtual()) { 7292 FunctionDecl *OperatorDelete = nullptr; 7293 DeclarationName Name = 7294 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7295 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7296 OperatorDelete, /*Diagnose*/false)) { 7297 if (Diagnose) 7298 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7299 return true; 7300 } 7301 } 7302 7303 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7304 7305 // Per DR1611, do not consider virtual bases of constructors of abstract 7306 // classes, since we are not going to construct them. 7307 // Per DR1658, do not consider virtual bases of destructors of abstract 7308 // classes either. 7309 // Per DR2180, for assignment operators we only assign (and thus only 7310 // consider) direct bases. 7311 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7312 : SMI.VisitPotentiallyConstructedBases)) 7313 return true; 7314 7315 if (SMI.shouldDeleteForAllConstMembers()) 7316 return true; 7317 7318 if (getLangOpts().CUDA) { 7319 // We should delete the special member in CUDA mode if target inference 7320 // failed. 7321 // For inherited constructors (non-null ICI), CSM may be passed so that MD 7322 // is treated as certain special member, which may not reflect what special 7323 // member MD really is. However inferCUDATargetForImplicitSpecialMember 7324 // expects CSM to match MD, therefore recalculate CSM. 7325 assert(ICI || CSM == getSpecialMember(MD)); 7326 auto RealCSM = CSM; 7327 if (ICI) 7328 RealCSM = getSpecialMember(MD); 7329 7330 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 7331 SMI.ConstArg, Diagnose); 7332 } 7333 7334 return false; 7335 } 7336 7337 /// Perform lookup for a special member of the specified kind, and determine 7338 /// whether it is trivial. If the triviality can be determined without the 7339 /// lookup, skip it. This is intended for use when determining whether a 7340 /// special member of a containing object is trivial, and thus does not ever 7341 /// perform overload resolution for default constructors. 7342 /// 7343 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7344 /// member that was most likely to be intended to be trivial, if any. 7345 /// 7346 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7347 /// determine whether the special member is trivial. 7348 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7349 Sema::CXXSpecialMember CSM, unsigned Quals, 7350 bool ConstRHS, 7351 Sema::TrivialABIHandling TAH, 7352 CXXMethodDecl **Selected) { 7353 if (Selected) 7354 *Selected = nullptr; 7355 7356 switch (CSM) { 7357 case Sema::CXXInvalid: 7358 llvm_unreachable("not a special member"); 7359 7360 case Sema::CXXDefaultConstructor: 7361 // C++11 [class.ctor]p5: 7362 // A default constructor is trivial if: 7363 // - all the [direct subobjects] have trivial default constructors 7364 // 7365 // Note, no overload resolution is performed in this case. 7366 if (RD->hasTrivialDefaultConstructor()) 7367 return true; 7368 7369 if (Selected) { 7370 // If there's a default constructor which could have been trivial, dig it 7371 // out. Otherwise, if there's any user-provided default constructor, point 7372 // to that as an example of why there's not a trivial one. 7373 CXXConstructorDecl *DefCtor = nullptr; 7374 if (RD->needsImplicitDefaultConstructor()) 7375 S.DeclareImplicitDefaultConstructor(RD); 7376 for (auto *CI : RD->ctors()) { 7377 if (!CI->isDefaultConstructor()) 7378 continue; 7379 DefCtor = CI; 7380 if (!DefCtor->isUserProvided()) 7381 break; 7382 } 7383 7384 *Selected = DefCtor; 7385 } 7386 7387 return false; 7388 7389 case Sema::CXXDestructor: 7390 // C++11 [class.dtor]p5: 7391 // A destructor is trivial if: 7392 // - all the direct [subobjects] have trivial destructors 7393 if (RD->hasTrivialDestructor() || 7394 (TAH == Sema::TAH_ConsiderTrivialABI && 7395 RD->hasTrivialDestructorForCall())) 7396 return true; 7397 7398 if (Selected) { 7399 if (RD->needsImplicitDestructor()) 7400 S.DeclareImplicitDestructor(RD); 7401 *Selected = RD->getDestructor(); 7402 } 7403 7404 return false; 7405 7406 case Sema::CXXCopyConstructor: 7407 // C++11 [class.copy]p12: 7408 // A copy constructor is trivial if: 7409 // - the constructor selected to copy each direct [subobject] is trivial 7410 if (RD->hasTrivialCopyConstructor() || 7411 (TAH == Sema::TAH_ConsiderTrivialABI && 7412 RD->hasTrivialCopyConstructorForCall())) { 7413 if (Quals == Qualifiers::Const) 7414 // We must either select the trivial copy constructor or reach an 7415 // ambiguity; no need to actually perform overload resolution. 7416 return true; 7417 } else if (!Selected) { 7418 return false; 7419 } 7420 // In C++98, we are not supposed to perform overload resolution here, but we 7421 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7422 // cases like B as having a non-trivial copy constructor: 7423 // struct A { template<typename T> A(T&); }; 7424 // struct B { mutable A a; }; 7425 goto NeedOverloadResolution; 7426 7427 case Sema::CXXCopyAssignment: 7428 // C++11 [class.copy]p25: 7429 // A copy assignment operator is trivial if: 7430 // - the assignment operator selected to copy each direct [subobject] is 7431 // trivial 7432 if (RD->hasTrivialCopyAssignment()) { 7433 if (Quals == Qualifiers::Const) 7434 return true; 7435 } else if (!Selected) { 7436 return false; 7437 } 7438 // In C++98, we are not supposed to perform overload resolution here, but we 7439 // treat that as a language defect. 7440 goto NeedOverloadResolution; 7441 7442 case Sema::CXXMoveConstructor: 7443 case Sema::CXXMoveAssignment: 7444 NeedOverloadResolution: 7445 Sema::SpecialMemberOverloadResult SMOR = 7446 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7447 7448 // The standard doesn't describe how to behave if the lookup is ambiguous. 7449 // We treat it as not making the member non-trivial, just like the standard 7450 // mandates for the default constructor. This should rarely matter, because 7451 // the member will also be deleted. 7452 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7453 return true; 7454 7455 if (!SMOR.getMethod()) { 7456 assert(SMOR.getKind() == 7457 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7458 return false; 7459 } 7460 7461 // We deliberately don't check if we found a deleted special member. We're 7462 // not supposed to! 7463 if (Selected) 7464 *Selected = SMOR.getMethod(); 7465 7466 if (TAH == Sema::TAH_ConsiderTrivialABI && 7467 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7468 return SMOR.getMethod()->isTrivialForCall(); 7469 return SMOR.getMethod()->isTrivial(); 7470 } 7471 7472 llvm_unreachable("unknown special method kind"); 7473 } 7474 7475 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7476 for (auto *CI : RD->ctors()) 7477 if (!CI->isImplicit()) 7478 return CI; 7479 7480 // Look for constructor templates. 7481 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7482 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7483 if (CXXConstructorDecl *CD = 7484 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7485 return CD; 7486 } 7487 7488 return nullptr; 7489 } 7490 7491 /// The kind of subobject we are checking for triviality. The values of this 7492 /// enumeration are used in diagnostics. 7493 enum TrivialSubobjectKind { 7494 /// The subobject is a base class. 7495 TSK_BaseClass, 7496 /// The subobject is a non-static data member. 7497 TSK_Field, 7498 /// The object is actually the complete object. 7499 TSK_CompleteObject 7500 }; 7501 7502 /// Check whether the special member selected for a given type would be trivial. 7503 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7504 QualType SubType, bool ConstRHS, 7505 Sema::CXXSpecialMember CSM, 7506 TrivialSubobjectKind Kind, 7507 Sema::TrivialABIHandling TAH, bool Diagnose) { 7508 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7509 if (!SubRD) 7510 return true; 7511 7512 CXXMethodDecl *Selected; 7513 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7514 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7515 return true; 7516 7517 if (Diagnose) { 7518 if (ConstRHS) 7519 SubType.addConst(); 7520 7521 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7522 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7523 << Kind << SubType.getUnqualifiedType(); 7524 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7525 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7526 } else if (!Selected) 7527 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7528 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7529 else if (Selected->isUserProvided()) { 7530 if (Kind == TSK_CompleteObject) 7531 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7532 << Kind << SubType.getUnqualifiedType() << CSM; 7533 else { 7534 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7535 << Kind << SubType.getUnqualifiedType() << CSM; 7536 S.Diag(Selected->getLocation(), diag::note_declared_at); 7537 } 7538 } else { 7539 if (Kind != TSK_CompleteObject) 7540 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7541 << Kind << SubType.getUnqualifiedType() << CSM; 7542 7543 // Explain why the defaulted or deleted special member isn't trivial. 7544 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7545 Diagnose); 7546 } 7547 } 7548 7549 return false; 7550 } 7551 7552 /// Check whether the members of a class type allow a special member to be 7553 /// trivial. 7554 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7555 Sema::CXXSpecialMember CSM, 7556 bool ConstArg, 7557 Sema::TrivialABIHandling TAH, 7558 bool Diagnose) { 7559 for (const auto *FI : RD->fields()) { 7560 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7561 continue; 7562 7563 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7564 7565 // Pretend anonymous struct or union members are members of this class. 7566 if (FI->isAnonymousStructOrUnion()) { 7567 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7568 CSM, ConstArg, TAH, Diagnose)) 7569 return false; 7570 continue; 7571 } 7572 7573 // C++11 [class.ctor]p5: 7574 // A default constructor is trivial if [...] 7575 // -- no non-static data member of its class has a 7576 // brace-or-equal-initializer 7577 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7578 if (Diagnose) 7579 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7580 return false; 7581 } 7582 7583 // Objective C ARC 4.3.5: 7584 // [...] nontrivally ownership-qualified types are [...] not trivially 7585 // default constructible, copy constructible, move constructible, copy 7586 // assignable, move assignable, or destructible [...] 7587 if (FieldType.hasNonTrivialObjCLifetime()) { 7588 if (Diagnose) 7589 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7590 << RD << FieldType.getObjCLifetime(); 7591 return false; 7592 } 7593 7594 bool ConstRHS = ConstArg && !FI->isMutable(); 7595 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7596 CSM, TSK_Field, TAH, Diagnose)) 7597 return false; 7598 } 7599 7600 return true; 7601 } 7602 7603 /// Diagnose why the specified class does not have a trivial special member of 7604 /// the given kind. 7605 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7606 QualType Ty = Context.getRecordType(RD); 7607 7608 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7609 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7610 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7611 /*Diagnose*/true); 7612 } 7613 7614 /// Determine whether a defaulted or deleted special member function is trivial, 7615 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7616 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7617 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7618 TrivialABIHandling TAH, bool Diagnose) { 7619 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7620 7621 CXXRecordDecl *RD = MD->getParent(); 7622 7623 bool ConstArg = false; 7624 7625 // C++11 [class.copy]p12, p25: [DR1593] 7626 // A [special member] is trivial if [...] its parameter-type-list is 7627 // equivalent to the parameter-type-list of an implicit declaration [...] 7628 switch (CSM) { 7629 case CXXDefaultConstructor: 7630 case CXXDestructor: 7631 // Trivial default constructors and destructors cannot have parameters. 7632 break; 7633 7634 case CXXCopyConstructor: 7635 case CXXCopyAssignment: { 7636 // Trivial copy operations always have const, non-volatile parameter types. 7637 ConstArg = true; 7638 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7639 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7640 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7641 if (Diagnose) 7642 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7643 << Param0->getSourceRange() << Param0->getType() 7644 << Context.getLValueReferenceType( 7645 Context.getRecordType(RD).withConst()); 7646 return false; 7647 } 7648 break; 7649 } 7650 7651 case CXXMoveConstructor: 7652 case CXXMoveAssignment: { 7653 // Trivial move operations always have non-cv-qualified parameters. 7654 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7655 const RValueReferenceType *RT = 7656 Param0->getType()->getAs<RValueReferenceType>(); 7657 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7658 if (Diagnose) 7659 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7660 << Param0->getSourceRange() << Param0->getType() 7661 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7662 return false; 7663 } 7664 break; 7665 } 7666 7667 case CXXInvalid: 7668 llvm_unreachable("not a special member"); 7669 } 7670 7671 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7672 if (Diagnose) 7673 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7674 diag::note_nontrivial_default_arg) 7675 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7676 return false; 7677 } 7678 if (MD->isVariadic()) { 7679 if (Diagnose) 7680 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7681 return false; 7682 } 7683 7684 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7685 // A copy/move [constructor or assignment operator] is trivial if 7686 // -- the [member] selected to copy/move each direct base class subobject 7687 // is trivial 7688 // 7689 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7690 // A [default constructor or destructor] is trivial if 7691 // -- all the direct base classes have trivial [default constructors or 7692 // destructors] 7693 for (const auto &BI : RD->bases()) 7694 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 7695 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7696 return false; 7697 7698 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7699 // A copy/move [constructor or assignment operator] for a class X is 7700 // trivial if 7701 // -- for each non-static data member of X that is of class type (or array 7702 // thereof), the constructor selected to copy/move that member is 7703 // trivial 7704 // 7705 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7706 // A [default constructor or destructor] is trivial if 7707 // -- for all of the non-static data members of its class that are of class 7708 // type (or array thereof), each such class has a trivial [default 7709 // constructor or destructor] 7710 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7711 return false; 7712 7713 // C++11 [class.dtor]p5: 7714 // A destructor is trivial if [...] 7715 // -- the destructor is not virtual 7716 if (CSM == CXXDestructor && MD->isVirtual()) { 7717 if (Diagnose) 7718 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7719 return false; 7720 } 7721 7722 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7723 // A [special member] for class X is trivial if [...] 7724 // -- class X has no virtual functions and no virtual base classes 7725 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7726 if (!Diagnose) 7727 return false; 7728 7729 if (RD->getNumVBases()) { 7730 // Check for virtual bases. We already know that the corresponding 7731 // member in all bases is trivial, so vbases must all be direct. 7732 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7733 assert(BS.isVirtual()); 7734 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 7735 return false; 7736 } 7737 7738 // Must have a virtual method. 7739 for (const auto *MI : RD->methods()) { 7740 if (MI->isVirtual()) { 7741 SourceLocation MLoc = MI->getBeginLoc(); 7742 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7743 return false; 7744 } 7745 } 7746 7747 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7748 } 7749 7750 // Looks like it's trivial! 7751 return true; 7752 } 7753 7754 namespace { 7755 struct FindHiddenVirtualMethod { 7756 Sema *S; 7757 CXXMethodDecl *Method; 7758 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7759 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7760 7761 private: 7762 /// Check whether any most overridden method from MD in Methods 7763 static bool CheckMostOverridenMethods( 7764 const CXXMethodDecl *MD, 7765 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7766 if (MD->size_overridden_methods() == 0) 7767 return Methods.count(MD->getCanonicalDecl()); 7768 for (const CXXMethodDecl *O : MD->overridden_methods()) 7769 if (CheckMostOverridenMethods(O, Methods)) 7770 return true; 7771 return false; 7772 } 7773 7774 public: 7775 /// Member lookup function that determines whether a given C++ 7776 /// method overloads virtual methods in a base class without overriding any, 7777 /// to be used with CXXRecordDecl::lookupInBases(). 7778 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7779 RecordDecl *BaseRecord = 7780 Specifier->getType()->getAs<RecordType>()->getDecl(); 7781 7782 DeclarationName Name = Method->getDeclName(); 7783 assert(Name.getNameKind() == DeclarationName::Identifier); 7784 7785 bool foundSameNameMethod = false; 7786 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7787 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7788 Path.Decls = Path.Decls.slice(1)) { 7789 NamedDecl *D = Path.Decls.front(); 7790 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7791 MD = MD->getCanonicalDecl(); 7792 foundSameNameMethod = true; 7793 // Interested only in hidden virtual methods. 7794 if (!MD->isVirtual()) 7795 continue; 7796 // If the method we are checking overrides a method from its base 7797 // don't warn about the other overloaded methods. Clang deviates from 7798 // GCC by only diagnosing overloads of inherited virtual functions that 7799 // do not override any other virtual functions in the base. GCC's 7800 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7801 // function from a base class. These cases may be better served by a 7802 // warning (not specific to virtual functions) on call sites when the 7803 // call would select a different function from the base class, were it 7804 // visible. 7805 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7806 if (!S->IsOverload(Method, MD, false)) 7807 return true; 7808 // Collect the overload only if its hidden. 7809 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7810 overloadedMethods.push_back(MD); 7811 } 7812 } 7813 7814 if (foundSameNameMethod) 7815 OverloadedMethods.append(overloadedMethods.begin(), 7816 overloadedMethods.end()); 7817 return foundSameNameMethod; 7818 } 7819 }; 7820 } // end anonymous namespace 7821 7822 /// Add the most overriden methods from MD to Methods 7823 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7824 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7825 if (MD->size_overridden_methods() == 0) 7826 Methods.insert(MD->getCanonicalDecl()); 7827 else 7828 for (const CXXMethodDecl *O : MD->overridden_methods()) 7829 AddMostOverridenMethods(O, Methods); 7830 } 7831 7832 /// Check if a method overloads virtual methods in a base class without 7833 /// overriding any. 7834 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7835 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7836 if (!MD->getDeclName().isIdentifier()) 7837 return; 7838 7839 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7840 /*bool RecordPaths=*/false, 7841 /*bool DetectVirtual=*/false); 7842 FindHiddenVirtualMethod FHVM; 7843 FHVM.Method = MD; 7844 FHVM.S = this; 7845 7846 // Keep the base methods that were overridden or introduced in the subclass 7847 // by 'using' in a set. A base method not in this set is hidden. 7848 CXXRecordDecl *DC = MD->getParent(); 7849 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7850 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7851 NamedDecl *ND = *I; 7852 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7853 ND = shad->getTargetDecl(); 7854 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7855 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7856 } 7857 7858 if (DC->lookupInBases(FHVM, Paths)) 7859 OverloadedMethods = FHVM.OverloadedMethods; 7860 } 7861 7862 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7863 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7864 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7865 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7866 PartialDiagnostic PD = PDiag( 7867 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7868 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7869 Diag(overloadedMD->getLocation(), PD); 7870 } 7871 } 7872 7873 /// Diagnose methods which overload virtual methods in a base class 7874 /// without overriding any. 7875 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7876 if (MD->isInvalidDecl()) 7877 return; 7878 7879 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7880 return; 7881 7882 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7883 FindHiddenVirtualMethods(MD, OverloadedMethods); 7884 if (!OverloadedMethods.empty()) { 7885 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7886 << MD << (OverloadedMethods.size() > 1); 7887 7888 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7889 } 7890 } 7891 7892 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7893 auto PrintDiagAndRemoveAttr = [&]() { 7894 // No diagnostics if this is a template instantiation. 7895 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7896 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7897 diag::ext_cannot_use_trivial_abi) << &RD; 7898 RD.dropAttr<TrivialABIAttr>(); 7899 }; 7900 7901 // Ill-formed if the struct has virtual functions. 7902 if (RD.isPolymorphic()) { 7903 PrintDiagAndRemoveAttr(); 7904 return; 7905 } 7906 7907 for (const auto &B : RD.bases()) { 7908 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7909 // virtual base. 7910 if ((!B.getType()->isDependentType() && 7911 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7912 B.isVirtual()) { 7913 PrintDiagAndRemoveAttr(); 7914 return; 7915 } 7916 } 7917 7918 for (const auto *FD : RD.fields()) { 7919 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7920 // non-trivial for the purpose of calls. 7921 QualType FT = FD->getType(); 7922 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7923 PrintDiagAndRemoveAttr(); 7924 return; 7925 } 7926 7927 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7928 if (!RT->isDependentType() && 7929 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7930 PrintDiagAndRemoveAttr(); 7931 return; 7932 } 7933 } 7934 } 7935 7936 void Sema::ActOnFinishCXXMemberSpecification( 7937 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 7938 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 7939 if (!TagDecl) 7940 return; 7941 7942 AdjustDeclIfTemplate(TagDecl); 7943 7944 for (const ParsedAttr &AL : AttrList) { 7945 if (AL.getKind() != ParsedAttr::AT_Visibility) 7946 continue; 7947 AL.setInvalid(); 7948 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) 7949 << AL.getName(); 7950 } 7951 7952 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7953 // strict aliasing violation! 7954 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7955 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7956 7957 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 7958 } 7959 7960 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7961 /// special functions, such as the default constructor, copy 7962 /// constructor, or destructor, to the given C++ class (C++ 7963 /// [special]p1). This routine can only be executed just before the 7964 /// definition of the class is complete. 7965 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7966 if (ClassDecl->needsImplicitDefaultConstructor()) { 7967 ++getASTContext().NumImplicitDefaultConstructors; 7968 7969 if (ClassDecl->hasInheritedConstructor()) 7970 DeclareImplicitDefaultConstructor(ClassDecl); 7971 } 7972 7973 if (ClassDecl->needsImplicitCopyConstructor()) { 7974 ++getASTContext().NumImplicitCopyConstructors; 7975 7976 // If the properties or semantics of the copy constructor couldn't be 7977 // determined while the class was being declared, force a declaration 7978 // of it now. 7979 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7980 ClassDecl->hasInheritedConstructor()) 7981 DeclareImplicitCopyConstructor(ClassDecl); 7982 // For the MS ABI we need to know whether the copy ctor is deleted. A 7983 // prerequisite for deleting the implicit copy ctor is that the class has a 7984 // move ctor or move assignment that is either user-declared or whose 7985 // semantics are inherited from a subobject. FIXME: We should provide a more 7986 // direct way for CodeGen to ask whether the constructor was deleted. 7987 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7988 (ClassDecl->hasUserDeclaredMoveConstructor() || 7989 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7990 ClassDecl->hasUserDeclaredMoveAssignment() || 7991 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7992 DeclareImplicitCopyConstructor(ClassDecl); 7993 } 7994 7995 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7996 ++getASTContext().NumImplicitMoveConstructors; 7997 7998 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7999 ClassDecl->hasInheritedConstructor()) 8000 DeclareImplicitMoveConstructor(ClassDecl); 8001 } 8002 8003 if (ClassDecl->needsImplicitCopyAssignment()) { 8004 ++getASTContext().NumImplicitCopyAssignmentOperators; 8005 8006 // If we have a dynamic class, then the copy assignment operator may be 8007 // virtual, so we have to declare it immediately. This ensures that, e.g., 8008 // it shows up in the right place in the vtable and that we diagnose 8009 // problems with the implicit exception specification. 8010 if (ClassDecl->isDynamicClass() || 8011 ClassDecl->needsOverloadResolutionForCopyAssignment() || 8012 ClassDecl->hasInheritedAssignment()) 8013 DeclareImplicitCopyAssignment(ClassDecl); 8014 } 8015 8016 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 8017 ++getASTContext().NumImplicitMoveAssignmentOperators; 8018 8019 // Likewise for the move assignment operator. 8020 if (ClassDecl->isDynamicClass() || 8021 ClassDecl->needsOverloadResolutionForMoveAssignment() || 8022 ClassDecl->hasInheritedAssignment()) 8023 DeclareImplicitMoveAssignment(ClassDecl); 8024 } 8025 8026 if (ClassDecl->needsImplicitDestructor()) { 8027 ++getASTContext().NumImplicitDestructors; 8028 8029 // If we have a dynamic class, then the destructor may be virtual, so we 8030 // have to declare the destructor immediately. This ensures that, e.g., it 8031 // shows up in the right place in the vtable and that we diagnose problems 8032 // with the implicit exception specification. 8033 if (ClassDecl->isDynamicClass() || 8034 ClassDecl->needsOverloadResolutionForDestructor()) 8035 DeclareImplicitDestructor(ClassDecl); 8036 } 8037 } 8038 8039 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 8040 if (!D) 8041 return 0; 8042 8043 // The order of template parameters is not important here. All names 8044 // get added to the same scope. 8045 SmallVector<TemplateParameterList *, 4> ParameterLists; 8046 8047 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8048 D = TD->getTemplatedDecl(); 8049 8050 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 8051 ParameterLists.push_back(PSD->getTemplateParameters()); 8052 8053 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 8054 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 8055 ParameterLists.push_back(DD->getTemplateParameterList(i)); 8056 8057 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8058 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 8059 ParameterLists.push_back(FTD->getTemplateParameters()); 8060 } 8061 } 8062 8063 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 8064 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 8065 ParameterLists.push_back(TD->getTemplateParameterList(i)); 8066 8067 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 8068 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 8069 ParameterLists.push_back(CTD->getTemplateParameters()); 8070 } 8071 } 8072 8073 unsigned Count = 0; 8074 for (TemplateParameterList *Params : ParameterLists) { 8075 if (Params->size() > 0) 8076 // Ignore explicit specializations; they don't contribute to the template 8077 // depth. 8078 ++Count; 8079 for (NamedDecl *Param : *Params) { 8080 if (Param->getDeclName()) { 8081 S->AddDecl(Param); 8082 IdResolver.AddDecl(Param); 8083 } 8084 } 8085 } 8086 8087 return Count; 8088 } 8089 8090 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8091 if (!RecordD) return; 8092 AdjustDeclIfTemplate(RecordD); 8093 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 8094 PushDeclContext(S, Record); 8095 } 8096 8097 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8098 if (!RecordD) return; 8099 PopDeclContext(); 8100 } 8101 8102 /// This is used to implement the constant expression evaluation part of the 8103 /// attribute enable_if extension. There is nothing in standard C++ which would 8104 /// require reentering parameters. 8105 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 8106 if (!Param) 8107 return; 8108 8109 S->AddDecl(Param); 8110 if (Param->getDeclName()) 8111 IdResolver.AddDecl(Param); 8112 } 8113 8114 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 8115 /// parsing a top-level (non-nested) C++ class, and we are now 8116 /// parsing those parts of the given Method declaration that could 8117 /// not be parsed earlier (C++ [class.mem]p2), such as default 8118 /// arguments. This action should enter the scope of the given 8119 /// Method declaration as if we had just parsed the qualified method 8120 /// name. However, it should not bring the parameters into scope; 8121 /// that will be performed by ActOnDelayedCXXMethodParameter. 8122 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8123 } 8124 8125 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 8126 /// C++ method declaration. We're (re-)introducing the given 8127 /// function parameter into scope for use in parsing later parts of 8128 /// the method declaration. For example, we could see an 8129 /// ActOnParamDefaultArgument event for this parameter. 8130 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 8131 if (!ParamD) 8132 return; 8133 8134 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8135 8136 // If this parameter has an unparsed default argument, clear it out 8137 // to make way for the parsed default argument. 8138 if (Param->hasUnparsedDefaultArg()) 8139 Param->setDefaultArg(nullptr); 8140 8141 S->AddDecl(Param); 8142 if (Param->getDeclName()) 8143 IdResolver.AddDecl(Param); 8144 } 8145 8146 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8147 /// processing the delayed method declaration for Method. The method 8148 /// declaration is now considered finished. There may be a separate 8149 /// ActOnStartOfFunctionDef action later (not necessarily 8150 /// immediately!) for this method, if it was also defined inside the 8151 /// class body. 8152 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8153 if (!MethodD) 8154 return; 8155 8156 AdjustDeclIfTemplate(MethodD); 8157 8158 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8159 8160 // Now that we have our default arguments, check the constructor 8161 // again. It could produce additional diagnostics or affect whether 8162 // the class has implicitly-declared destructors, among other 8163 // things. 8164 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8165 CheckConstructor(Constructor); 8166 8167 // Check the default arguments, which we may have added. 8168 if (!Method->isInvalidDecl()) 8169 CheckCXXDefaultArguments(Method); 8170 } 8171 8172 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8173 /// the well-formedness of the constructor declarator @p D with type @p 8174 /// R. If there are any errors in the declarator, this routine will 8175 /// emit diagnostics and set the invalid bit to true. In any case, the type 8176 /// will be updated to reflect a well-formed type for the constructor and 8177 /// returned. 8178 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8179 StorageClass &SC) { 8180 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8181 8182 // C++ [class.ctor]p3: 8183 // A constructor shall not be virtual (10.3) or static (9.4). A 8184 // constructor can be invoked for a const, volatile or const 8185 // volatile object. A constructor shall not be declared const, 8186 // volatile, or const volatile (9.3.2). 8187 if (isVirtual) { 8188 if (!D.isInvalidType()) 8189 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8190 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8191 << SourceRange(D.getIdentifierLoc()); 8192 D.setInvalidType(); 8193 } 8194 if (SC == SC_Static) { 8195 if (!D.isInvalidType()) 8196 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8197 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8198 << SourceRange(D.getIdentifierLoc()); 8199 D.setInvalidType(); 8200 SC = SC_None; 8201 } 8202 8203 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8204 diagnoseIgnoredQualifiers( 8205 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8206 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8207 D.getDeclSpec().getRestrictSpecLoc(), 8208 D.getDeclSpec().getAtomicSpecLoc()); 8209 D.setInvalidType(); 8210 } 8211 8212 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8213 if (FTI.hasMethodTypeQualifiers()) { 8214 FTI.MethodQualifiers->forEachQualifier( 8215 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { 8216 Diag(SL, diag::err_invalid_qualified_constructor) 8217 << QualName << SourceRange(SL); 8218 }); 8219 D.setInvalidType(); 8220 } 8221 8222 // C++0x [class.ctor]p4: 8223 // A constructor shall not be declared with a ref-qualifier. 8224 if (FTI.hasRefQualifier()) { 8225 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8226 << FTI.RefQualifierIsLValueRef 8227 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8228 D.setInvalidType(); 8229 } 8230 8231 // Rebuild the function type "R" without any type qualifiers (in 8232 // case any of the errors above fired) and with "void" as the 8233 // return type, since constructors don't have return types. 8234 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8235 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8236 return R; 8237 8238 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8239 EPI.TypeQuals = Qualifiers(); 8240 EPI.RefQualifier = RQ_None; 8241 8242 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8243 } 8244 8245 /// CheckConstructor - Checks a fully-formed constructor for 8246 /// well-formedness, issuing any diagnostics required. Returns true if 8247 /// the constructor declarator is invalid. 8248 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8249 CXXRecordDecl *ClassDecl 8250 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8251 if (!ClassDecl) 8252 return Constructor->setInvalidDecl(); 8253 8254 // C++ [class.copy]p3: 8255 // A declaration of a constructor for a class X is ill-formed if 8256 // its first parameter is of type (optionally cv-qualified) X and 8257 // either there are no other parameters or else all other 8258 // parameters have default arguments. 8259 if (!Constructor->isInvalidDecl() && 8260 ((Constructor->getNumParams() == 1) || 8261 (Constructor->getNumParams() > 1 && 8262 Constructor->getParamDecl(1)->hasDefaultArg())) && 8263 Constructor->getTemplateSpecializationKind() 8264 != TSK_ImplicitInstantiation) { 8265 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8266 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8267 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8268 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8269 const char *ConstRef 8270 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8271 : " const &"; 8272 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8273 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8274 8275 // FIXME: Rather that making the constructor invalid, we should endeavor 8276 // to fix the type. 8277 Constructor->setInvalidDecl(); 8278 } 8279 } 8280 } 8281 8282 /// CheckDestructor - Checks a fully-formed destructor definition for 8283 /// well-formedness, issuing any diagnostics required. Returns true 8284 /// on error. 8285 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8286 CXXRecordDecl *RD = Destructor->getParent(); 8287 8288 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8289 SourceLocation Loc; 8290 8291 if (!Destructor->isImplicit()) 8292 Loc = Destructor->getLocation(); 8293 else 8294 Loc = RD->getLocation(); 8295 8296 // If we have a virtual destructor, look up the deallocation function 8297 if (FunctionDecl *OperatorDelete = 8298 FindDeallocationFunctionForDestructor(Loc, RD)) { 8299 Expr *ThisArg = nullptr; 8300 8301 // If the notional 'delete this' expression requires a non-trivial 8302 // conversion from 'this' to the type of a destroying operator delete's 8303 // first parameter, perform that conversion now. 8304 if (OperatorDelete->isDestroyingOperatorDelete()) { 8305 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8306 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8307 // C++ [class.dtor]p13: 8308 // ... as if for the expression 'delete this' appearing in a 8309 // non-virtual destructor of the destructor's class. 8310 ContextRAII SwitchContext(*this, Destructor); 8311 ExprResult This = 8312 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8313 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8314 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8315 if (This.isInvalid()) { 8316 // FIXME: Register this as a context note so that it comes out 8317 // in the right order. 8318 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8319 return true; 8320 } 8321 ThisArg = This.get(); 8322 } 8323 } 8324 8325 DiagnoseUseOfDecl(OperatorDelete, Loc); 8326 MarkFunctionReferenced(Loc, OperatorDelete); 8327 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8328 } 8329 } 8330 8331 return false; 8332 } 8333 8334 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8335 /// the well-formednes of the destructor declarator @p D with type @p 8336 /// R. If there are any errors in the declarator, this routine will 8337 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8338 /// will be updated to reflect a well-formed type for the destructor and 8339 /// returned. 8340 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8341 StorageClass& SC) { 8342 // C++ [class.dtor]p1: 8343 // [...] A typedef-name that names a class is a class-name 8344 // (7.1.3); however, a typedef-name that names a class shall not 8345 // be used as the identifier in the declarator for a destructor 8346 // declaration. 8347 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8348 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8349 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8350 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8351 else if (const TemplateSpecializationType *TST = 8352 DeclaratorType->getAs<TemplateSpecializationType>()) 8353 if (TST->isTypeAlias()) 8354 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8355 << DeclaratorType << 1; 8356 8357 // C++ [class.dtor]p2: 8358 // A destructor is used to destroy objects of its class type. A 8359 // destructor takes no parameters, and no return type can be 8360 // specified for it (not even void). The address of a destructor 8361 // shall not be taken. A destructor shall not be static. A 8362 // destructor can be invoked for a const, volatile or const 8363 // volatile object. A destructor shall not be declared const, 8364 // volatile or const volatile (9.3.2). 8365 if (SC == SC_Static) { 8366 if (!D.isInvalidType()) 8367 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8368 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8369 << SourceRange(D.getIdentifierLoc()) 8370 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8371 8372 SC = SC_None; 8373 } 8374 if (!D.isInvalidType()) { 8375 // Destructors don't have return types, but the parser will 8376 // happily parse something like: 8377 // 8378 // class X { 8379 // float ~X(); 8380 // }; 8381 // 8382 // The return type will be eliminated later. 8383 if (D.getDeclSpec().hasTypeSpecifier()) 8384 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8385 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8386 << SourceRange(D.getIdentifierLoc()); 8387 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8388 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8389 SourceLocation(), 8390 D.getDeclSpec().getConstSpecLoc(), 8391 D.getDeclSpec().getVolatileSpecLoc(), 8392 D.getDeclSpec().getRestrictSpecLoc(), 8393 D.getDeclSpec().getAtomicSpecLoc()); 8394 D.setInvalidType(); 8395 } 8396 } 8397 8398 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8399 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 8400 FTI.MethodQualifiers->forEachQualifier( 8401 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { 8402 Diag(SL, diag::err_invalid_qualified_destructor) 8403 << QualName << SourceRange(SL); 8404 }); 8405 D.setInvalidType(); 8406 } 8407 8408 // C++0x [class.dtor]p2: 8409 // A destructor shall not be declared with a ref-qualifier. 8410 if (FTI.hasRefQualifier()) { 8411 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8412 << FTI.RefQualifierIsLValueRef 8413 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8414 D.setInvalidType(); 8415 } 8416 8417 // Make sure we don't have any parameters. 8418 if (FTIHasNonVoidParameters(FTI)) { 8419 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8420 8421 // Delete the parameters. 8422 FTI.freeParams(); 8423 D.setInvalidType(); 8424 } 8425 8426 // Make sure the destructor isn't variadic. 8427 if (FTI.isVariadic) { 8428 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8429 D.setInvalidType(); 8430 } 8431 8432 // Rebuild the function type "R" without any type qualifiers or 8433 // parameters (in case any of the errors above fired) and with 8434 // "void" as the return type, since destructors don't have return 8435 // types. 8436 if (!D.isInvalidType()) 8437 return R; 8438 8439 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8440 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8441 EPI.Variadic = false; 8442 EPI.TypeQuals = Qualifiers(); 8443 EPI.RefQualifier = RQ_None; 8444 return Context.getFunctionType(Context.VoidTy, None, EPI); 8445 } 8446 8447 static void extendLeft(SourceRange &R, SourceRange Before) { 8448 if (Before.isInvalid()) 8449 return; 8450 R.setBegin(Before.getBegin()); 8451 if (R.getEnd().isInvalid()) 8452 R.setEnd(Before.getEnd()); 8453 } 8454 8455 static void extendRight(SourceRange &R, SourceRange After) { 8456 if (After.isInvalid()) 8457 return; 8458 if (R.getBegin().isInvalid()) 8459 R.setBegin(After.getBegin()); 8460 R.setEnd(After.getEnd()); 8461 } 8462 8463 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8464 /// well-formednes of the conversion function declarator @p D with 8465 /// type @p R. If there are any errors in the declarator, this routine 8466 /// will emit diagnostics and return true. Otherwise, it will return 8467 /// false. Either way, the type @p R will be updated to reflect a 8468 /// well-formed type for the conversion operator. 8469 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8470 StorageClass& SC) { 8471 // C++ [class.conv.fct]p1: 8472 // Neither parameter types nor return type can be specified. The 8473 // type of a conversion function (8.3.5) is "function taking no 8474 // parameter returning conversion-type-id." 8475 if (SC == SC_Static) { 8476 if (!D.isInvalidType()) 8477 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8478 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8479 << D.getName().getSourceRange(); 8480 D.setInvalidType(); 8481 SC = SC_None; 8482 } 8483 8484 TypeSourceInfo *ConvTSI = nullptr; 8485 QualType ConvType = 8486 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8487 8488 const DeclSpec &DS = D.getDeclSpec(); 8489 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8490 // Conversion functions don't have return types, but the parser will 8491 // happily parse something like: 8492 // 8493 // class X { 8494 // float operator bool(); 8495 // }; 8496 // 8497 // The return type will be changed later anyway. 8498 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8499 << SourceRange(DS.getTypeSpecTypeLoc()) 8500 << SourceRange(D.getIdentifierLoc()); 8501 D.setInvalidType(); 8502 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8503 // It's also plausible that the user writes type qualifiers in the wrong 8504 // place, such as: 8505 // struct S { const operator int(); }; 8506 // FIXME: we could provide a fixit to move the qualifiers onto the 8507 // conversion type. 8508 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8509 << SourceRange(D.getIdentifierLoc()) << 0; 8510 D.setInvalidType(); 8511 } 8512 8513 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8514 8515 // Make sure we don't have any parameters. 8516 if (Proto->getNumParams() > 0) { 8517 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8518 8519 // Delete the parameters. 8520 D.getFunctionTypeInfo().freeParams(); 8521 D.setInvalidType(); 8522 } else if (Proto->isVariadic()) { 8523 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8524 D.setInvalidType(); 8525 } 8526 8527 // Diagnose "&operator bool()" and other such nonsense. This 8528 // is actually a gcc extension which we don't support. 8529 if (Proto->getReturnType() != ConvType) { 8530 bool NeedsTypedef = false; 8531 SourceRange Before, After; 8532 8533 // Walk the chunks and extract information on them for our diagnostic. 8534 bool PastFunctionChunk = false; 8535 for (auto &Chunk : D.type_objects()) { 8536 switch (Chunk.Kind) { 8537 case DeclaratorChunk::Function: 8538 if (!PastFunctionChunk) { 8539 if (Chunk.Fun.HasTrailingReturnType) { 8540 TypeSourceInfo *TRT = nullptr; 8541 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8542 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8543 } 8544 PastFunctionChunk = true; 8545 break; 8546 } 8547 LLVM_FALLTHROUGH; 8548 case DeclaratorChunk::Array: 8549 NeedsTypedef = true; 8550 extendRight(After, Chunk.getSourceRange()); 8551 break; 8552 8553 case DeclaratorChunk::Pointer: 8554 case DeclaratorChunk::BlockPointer: 8555 case DeclaratorChunk::Reference: 8556 case DeclaratorChunk::MemberPointer: 8557 case DeclaratorChunk::Pipe: 8558 extendLeft(Before, Chunk.getSourceRange()); 8559 break; 8560 8561 case DeclaratorChunk::Paren: 8562 extendLeft(Before, Chunk.Loc); 8563 extendRight(After, Chunk.EndLoc); 8564 break; 8565 } 8566 } 8567 8568 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8569 After.isValid() ? After.getBegin() : 8570 D.getIdentifierLoc(); 8571 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8572 DB << Before << After; 8573 8574 if (!NeedsTypedef) { 8575 DB << /*don't need a typedef*/0; 8576 8577 // If we can provide a correct fix-it hint, do so. 8578 if (After.isInvalid() && ConvTSI) { 8579 SourceLocation InsertLoc = 8580 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 8581 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8582 << FixItHint::CreateInsertionFromRange( 8583 InsertLoc, CharSourceRange::getTokenRange(Before)) 8584 << FixItHint::CreateRemoval(Before); 8585 } 8586 } else if (!Proto->getReturnType()->isDependentType()) { 8587 DB << /*typedef*/1 << Proto->getReturnType(); 8588 } else if (getLangOpts().CPlusPlus11) { 8589 DB << /*alias template*/2 << Proto->getReturnType(); 8590 } else { 8591 DB << /*might not be fixable*/3; 8592 } 8593 8594 // Recover by incorporating the other type chunks into the result type. 8595 // Note, this does *not* change the name of the function. This is compatible 8596 // with the GCC extension: 8597 // struct S { &operator int(); } s; 8598 // int &r = s.operator int(); // ok in GCC 8599 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8600 ConvType = Proto->getReturnType(); 8601 } 8602 8603 // C++ [class.conv.fct]p4: 8604 // The conversion-type-id shall not represent a function type nor 8605 // an array type. 8606 if (ConvType->isArrayType()) { 8607 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8608 ConvType = Context.getPointerType(ConvType); 8609 D.setInvalidType(); 8610 } else if (ConvType->isFunctionType()) { 8611 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8612 ConvType = Context.getPointerType(ConvType); 8613 D.setInvalidType(); 8614 } 8615 8616 // Rebuild the function type "R" without any parameters (in case any 8617 // of the errors above fired) and with the conversion type as the 8618 // return type. 8619 if (D.isInvalidType()) 8620 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8621 8622 // C++0x explicit conversion operators. 8623 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) 8624 Diag(DS.getExplicitSpecLoc(), 8625 getLangOpts().CPlusPlus11 8626 ? diag::warn_cxx98_compat_explicit_conversion_functions 8627 : diag::ext_explicit_conversion_functions) 8628 << SourceRange(DS.getExplicitSpecRange()); 8629 } 8630 8631 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8632 /// the declaration of the given C++ conversion function. This routine 8633 /// is responsible for recording the conversion function in the C++ 8634 /// class, if possible. 8635 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8636 assert(Conversion && "Expected to receive a conversion function declaration"); 8637 8638 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8639 8640 // Make sure we aren't redeclaring the conversion function. 8641 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8642 8643 // C++ [class.conv.fct]p1: 8644 // [...] A conversion function is never used to convert a 8645 // (possibly cv-qualified) object to the (possibly cv-qualified) 8646 // same object type (or a reference to it), to a (possibly 8647 // cv-qualified) base class of that type (or a reference to it), 8648 // or to (possibly cv-qualified) void. 8649 // FIXME: Suppress this warning if the conversion function ends up being a 8650 // virtual function that overrides a virtual function in a base class. 8651 QualType ClassType 8652 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8653 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8654 ConvType = ConvTypeRef->getPointeeType(); 8655 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8656 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8657 /* Suppress diagnostics for instantiations. */; 8658 else if (ConvType->isRecordType()) { 8659 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8660 if (ConvType == ClassType) 8661 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8662 << ClassType; 8663 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8664 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8665 << ClassType << ConvType; 8666 } else if (ConvType->isVoidType()) { 8667 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8668 << ClassType << ConvType; 8669 } 8670 8671 if (FunctionTemplateDecl *ConversionTemplate 8672 = Conversion->getDescribedFunctionTemplate()) 8673 return ConversionTemplate; 8674 8675 return Conversion; 8676 } 8677 8678 namespace { 8679 /// Utility class to accumulate and print a diagnostic listing the invalid 8680 /// specifier(s) on a declaration. 8681 struct BadSpecifierDiagnoser { 8682 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8683 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8684 ~BadSpecifierDiagnoser() { 8685 Diagnostic << Specifiers; 8686 } 8687 8688 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8689 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8690 } 8691 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8692 return check(SpecLoc, 8693 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8694 } 8695 void check(SourceLocation SpecLoc, const char *Spec) { 8696 if (SpecLoc.isInvalid()) return; 8697 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8698 if (!Specifiers.empty()) Specifiers += " "; 8699 Specifiers += Spec; 8700 } 8701 8702 Sema &S; 8703 Sema::SemaDiagnosticBuilder Diagnostic; 8704 std::string Specifiers; 8705 }; 8706 } 8707 8708 /// Check the validity of a declarator that we parsed for a deduction-guide. 8709 /// These aren't actually declarators in the grammar, so we need to check that 8710 /// the user didn't specify any pieces that are not part of the deduction-guide 8711 /// grammar. 8712 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8713 StorageClass &SC) { 8714 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8715 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8716 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8717 8718 // C++ [temp.deduct.guide]p3: 8719 // A deduction-gide shall be declared in the same scope as the 8720 // corresponding class template. 8721 if (!CurContext->getRedeclContext()->Equals( 8722 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8723 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8724 << GuidedTemplateDecl; 8725 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8726 } 8727 8728 auto &DS = D.getMutableDeclSpec(); 8729 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8730 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8731 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8732 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8733 BadSpecifierDiagnoser Diagnoser( 8734 *this, D.getIdentifierLoc(), 8735 diag::err_deduction_guide_invalid_specifier); 8736 8737 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8738 DS.ClearStorageClassSpecs(); 8739 SC = SC_None; 8740 8741 // 'explicit' is permitted. 8742 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8743 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8744 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8745 DS.ClearConstexprSpec(); 8746 8747 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8748 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8749 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8750 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8751 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8752 DS.ClearTypeQualifiers(); 8753 8754 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8755 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8756 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8757 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8758 DS.ClearTypeSpecType(); 8759 } 8760 8761 if (D.isInvalidType()) 8762 return; 8763 8764 // Check the declarator is simple enough. 8765 bool FoundFunction = false; 8766 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8767 if (Chunk.Kind == DeclaratorChunk::Paren) 8768 continue; 8769 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8770 Diag(D.getDeclSpec().getBeginLoc(), 8771 diag::err_deduction_guide_with_complex_decl) 8772 << D.getSourceRange(); 8773 break; 8774 } 8775 if (!Chunk.Fun.hasTrailingReturnType()) { 8776 Diag(D.getName().getBeginLoc(), 8777 diag::err_deduction_guide_no_trailing_return_type); 8778 break; 8779 } 8780 8781 // Check that the return type is written as a specialization of 8782 // the template specified as the deduction-guide's name. 8783 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8784 TypeSourceInfo *TSI = nullptr; 8785 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8786 assert(TSI && "deduction guide has valid type but invalid return type?"); 8787 bool AcceptableReturnType = false; 8788 bool MightInstantiateToSpecialization = false; 8789 if (auto RetTST = 8790 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8791 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8792 bool TemplateMatches = 8793 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8794 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8795 AcceptableReturnType = true; 8796 else { 8797 // This could still instantiate to the right type, unless we know it 8798 // names the wrong class template. 8799 auto *TD = SpecifiedName.getAsTemplateDecl(); 8800 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8801 !TemplateMatches); 8802 } 8803 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8804 MightInstantiateToSpecialization = true; 8805 } 8806 8807 if (!AcceptableReturnType) { 8808 Diag(TSI->getTypeLoc().getBeginLoc(), 8809 diag::err_deduction_guide_bad_trailing_return_type) 8810 << GuidedTemplate << TSI->getType() 8811 << MightInstantiateToSpecialization 8812 << TSI->getTypeLoc().getSourceRange(); 8813 } 8814 8815 // Keep going to check that we don't have any inner declarator pieces (we 8816 // could still have a function returning a pointer to a function). 8817 FoundFunction = true; 8818 } 8819 8820 if (D.isFunctionDefinition()) 8821 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8822 } 8823 8824 //===----------------------------------------------------------------------===// 8825 // Namespace Handling 8826 //===----------------------------------------------------------------------===// 8827 8828 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8829 /// reopened. 8830 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8831 SourceLocation Loc, 8832 IdentifierInfo *II, bool *IsInline, 8833 NamespaceDecl *PrevNS) { 8834 assert(*IsInline != PrevNS->isInline()); 8835 8836 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8837 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8838 // inline namespaces, with the intention of bringing names into namespace std. 8839 // 8840 // We support this just well enough to get that case working; this is not 8841 // sufficient to support reopening namespaces as inline in general. 8842 if (*IsInline && II && II->getName().startswith("__atomic") && 8843 S.getSourceManager().isInSystemHeader(Loc)) { 8844 // Mark all prior declarations of the namespace as inline. 8845 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8846 NS = NS->getPreviousDecl()) 8847 NS->setInline(*IsInline); 8848 // Patch up the lookup table for the containing namespace. This isn't really 8849 // correct, but it's good enough for this particular case. 8850 for (auto *I : PrevNS->decls()) 8851 if (auto *ND = dyn_cast<NamedDecl>(I)) 8852 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8853 return; 8854 } 8855 8856 if (PrevNS->isInline()) 8857 // The user probably just forgot the 'inline', so suggest that it 8858 // be added back. 8859 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8860 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8861 else 8862 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8863 8864 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8865 *IsInline = PrevNS->isInline(); 8866 } 8867 8868 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8869 /// definition. 8870 Decl *Sema::ActOnStartNamespaceDef( 8871 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 8872 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 8873 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 8874 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8875 // For anonymous namespace, take the location of the left brace. 8876 SourceLocation Loc = II ? IdentLoc : LBrace; 8877 bool IsInline = InlineLoc.isValid(); 8878 bool IsInvalid = false; 8879 bool IsStd = false; 8880 bool AddToKnown = false; 8881 Scope *DeclRegionScope = NamespcScope->getParent(); 8882 8883 NamespaceDecl *PrevNS = nullptr; 8884 if (II) { 8885 // C++ [namespace.def]p2: 8886 // The identifier in an original-namespace-definition shall not 8887 // have been previously defined in the declarative region in 8888 // which the original-namespace-definition appears. The 8889 // identifier in an original-namespace-definition is the name of 8890 // the namespace. Subsequently in that declarative region, it is 8891 // treated as an original-namespace-name. 8892 // 8893 // Since namespace names are unique in their scope, and we don't 8894 // look through using directives, just look for any ordinary names 8895 // as if by qualified name lookup. 8896 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8897 ForExternalRedeclaration); 8898 LookupQualifiedName(R, CurContext->getRedeclContext()); 8899 NamedDecl *PrevDecl = 8900 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8901 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8902 8903 if (PrevNS) { 8904 // This is an extended namespace definition. 8905 if (IsInline != PrevNS->isInline()) 8906 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8907 &IsInline, PrevNS); 8908 } else if (PrevDecl) { 8909 // This is an invalid name redefinition. 8910 Diag(Loc, diag::err_redefinition_different_kind) 8911 << II; 8912 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8913 IsInvalid = true; 8914 // Continue on to push Namespc as current DeclContext and return it. 8915 } else if (II->isStr("std") && 8916 CurContext->getRedeclContext()->isTranslationUnit()) { 8917 // This is the first "real" definition of the namespace "std", so update 8918 // our cache of the "std" namespace to point at this definition. 8919 PrevNS = getStdNamespace(); 8920 IsStd = true; 8921 AddToKnown = !IsInline; 8922 } else { 8923 // We've seen this namespace for the first time. 8924 AddToKnown = !IsInline; 8925 } 8926 } else { 8927 // Anonymous namespaces. 8928 8929 // Determine whether the parent already has an anonymous namespace. 8930 DeclContext *Parent = CurContext->getRedeclContext(); 8931 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8932 PrevNS = TU->getAnonymousNamespace(); 8933 } else { 8934 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8935 PrevNS = ND->getAnonymousNamespace(); 8936 } 8937 8938 if (PrevNS && IsInline != PrevNS->isInline()) 8939 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8940 &IsInline, PrevNS); 8941 } 8942 8943 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8944 StartLoc, Loc, II, PrevNS); 8945 if (IsInvalid) 8946 Namespc->setInvalidDecl(); 8947 8948 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8949 AddPragmaAttributes(DeclRegionScope, Namespc); 8950 8951 // FIXME: Should we be merging attributes? 8952 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8953 PushNamespaceVisibilityAttr(Attr, Loc); 8954 8955 if (IsStd) 8956 StdNamespace = Namespc; 8957 if (AddToKnown) 8958 KnownNamespaces[Namespc] = false; 8959 8960 if (II) { 8961 PushOnScopeChains(Namespc, DeclRegionScope); 8962 } else { 8963 // Link the anonymous namespace into its parent. 8964 DeclContext *Parent = CurContext->getRedeclContext(); 8965 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8966 TU->setAnonymousNamespace(Namespc); 8967 } else { 8968 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8969 } 8970 8971 CurContext->addDecl(Namespc); 8972 8973 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8974 // behaves as if it were replaced by 8975 // namespace unique { /* empty body */ } 8976 // using namespace unique; 8977 // namespace unique { namespace-body } 8978 // where all occurrences of 'unique' in a translation unit are 8979 // replaced by the same identifier and this identifier differs 8980 // from all other identifiers in the entire program. 8981 8982 // We just create the namespace with an empty name and then add an 8983 // implicit using declaration, just like the standard suggests. 8984 // 8985 // CodeGen enforces the "universally unique" aspect by giving all 8986 // declarations semantically contained within an anonymous 8987 // namespace internal linkage. 8988 8989 if (!PrevNS) { 8990 UD = UsingDirectiveDecl::Create(Context, Parent, 8991 /* 'using' */ LBrace, 8992 /* 'namespace' */ SourceLocation(), 8993 /* qualifier */ NestedNameSpecifierLoc(), 8994 /* identifier */ SourceLocation(), 8995 Namespc, 8996 /* Ancestor */ Parent); 8997 UD->setImplicit(); 8998 Parent->addDecl(UD); 8999 } 9000 } 9001 9002 ActOnDocumentableDecl(Namespc); 9003 9004 // Although we could have an invalid decl (i.e. the namespace name is a 9005 // redefinition), push it as current DeclContext and try to continue parsing. 9006 // FIXME: We should be able to push Namespc here, so that the each DeclContext 9007 // for the namespace has the declarations that showed up in that particular 9008 // namespace definition. 9009 PushDeclContext(NamespcScope, Namespc); 9010 return Namespc; 9011 } 9012 9013 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 9014 /// is a namespace alias, returns the namespace it points to. 9015 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 9016 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 9017 return AD->getNamespace(); 9018 return dyn_cast_or_null<NamespaceDecl>(D); 9019 } 9020 9021 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 9022 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 9023 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 9024 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 9025 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 9026 Namespc->setRBraceLoc(RBrace); 9027 PopDeclContext(); 9028 if (Namespc->hasAttr<VisibilityAttr>()) 9029 PopPragmaVisibility(true, RBrace); 9030 // If this namespace contains an export-declaration, export it now. 9031 if (DeferredExportedNamespaces.erase(Namespc)) 9032 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 9033 } 9034 9035 CXXRecordDecl *Sema::getStdBadAlloc() const { 9036 return cast_or_null<CXXRecordDecl>( 9037 StdBadAlloc.get(Context.getExternalSource())); 9038 } 9039 9040 EnumDecl *Sema::getStdAlignValT() const { 9041 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 9042 } 9043 9044 NamespaceDecl *Sema::getStdNamespace() const { 9045 return cast_or_null<NamespaceDecl>( 9046 StdNamespace.get(Context.getExternalSource())); 9047 } 9048 9049 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 9050 if (!StdExperimentalNamespaceCache) { 9051 if (auto Std = getStdNamespace()) { 9052 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 9053 SourceLocation(), LookupNamespaceName); 9054 if (!LookupQualifiedName(Result, Std) || 9055 !(StdExperimentalNamespaceCache = 9056 Result.getAsSingle<NamespaceDecl>())) 9057 Result.suppressDiagnostics(); 9058 } 9059 } 9060 return StdExperimentalNamespaceCache; 9061 } 9062 9063 namespace { 9064 9065 enum UnsupportedSTLSelect { 9066 USS_InvalidMember, 9067 USS_MissingMember, 9068 USS_NonTrivial, 9069 USS_Other 9070 }; 9071 9072 struct InvalidSTLDiagnoser { 9073 Sema &S; 9074 SourceLocation Loc; 9075 QualType TyForDiags; 9076 9077 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 9078 const VarDecl *VD = nullptr) { 9079 { 9080 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 9081 << TyForDiags << ((int)Sel); 9082 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 9083 assert(!Name.empty()); 9084 D << Name; 9085 } 9086 } 9087 if (Sel == USS_InvalidMember) { 9088 S.Diag(VD->getLocation(), diag::note_var_declared_here) 9089 << VD << VD->getSourceRange(); 9090 } 9091 return QualType(); 9092 } 9093 }; 9094 } // namespace 9095 9096 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 9097 SourceLocation Loc) { 9098 assert(getLangOpts().CPlusPlus && 9099 "Looking for comparison category type outside of C++."); 9100 9101 // Check if we've already successfully checked the comparison category type 9102 // before. If so, skip checking it again. 9103 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 9104 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 9105 return Info->getType(); 9106 9107 // If lookup failed 9108 if (!Info) { 9109 std::string NameForDiags = "std::"; 9110 NameForDiags += ComparisonCategories::getCategoryString(Kind); 9111 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 9112 << NameForDiags; 9113 return QualType(); 9114 } 9115 9116 assert(Info->Kind == Kind); 9117 assert(Info->Record); 9118 9119 // Update the Record decl in case we encountered a forward declaration on our 9120 // first pass. FIXME: This is a bit of a hack. 9121 if (Info->Record->hasDefinition()) 9122 Info->Record = Info->Record->getDefinition(); 9123 9124 // Use an elaborated type for diagnostics which has a name containing the 9125 // prepended 'std' namespace but not any inline namespace names. 9126 QualType TyForDiags = [&]() { 9127 auto *NNS = 9128 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9129 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9130 }(); 9131 9132 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9133 return QualType(); 9134 9135 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9136 9137 if (!Info->Record->isTriviallyCopyable()) 9138 return UnsupportedSTLError(USS_NonTrivial); 9139 9140 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9141 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9142 // Tolerate empty base classes. 9143 if (Base->isEmpty()) 9144 continue; 9145 // Reject STL implementations which have at least one non-empty base. 9146 return UnsupportedSTLError(); 9147 } 9148 9149 // Check that the STL has implemented the types using a single integer field. 9150 // This expectation allows better codegen for builtin operators. We require: 9151 // (1) The class has exactly one field. 9152 // (2) The field is an integral or enumeration type. 9153 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9154 if (std::distance(FIt, FEnd) != 1 || 9155 !FIt->getType()->isIntegralOrEnumerationType()) { 9156 return UnsupportedSTLError(); 9157 } 9158 9159 // Build each of the require values and store them in Info. 9160 for (ComparisonCategoryResult CCR : 9161 ComparisonCategories::getPossibleResultsForType(Kind)) { 9162 StringRef MemName = ComparisonCategories::getResultString(CCR); 9163 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9164 9165 if (!ValInfo) 9166 return UnsupportedSTLError(USS_MissingMember, MemName); 9167 9168 VarDecl *VD = ValInfo->VD; 9169 assert(VD && "should not be null!"); 9170 9171 // Attempt to diagnose reasons why the STL definition of this type 9172 // might be foobar, including it failing to be a constant expression. 9173 // TODO Handle more ways the lookup or result can be invalid. 9174 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9175 !VD->checkInitIsICE()) 9176 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9177 9178 // Attempt to evaluate the var decl as a constant expression and extract 9179 // the value of its first field as a ICE. If this fails, the STL 9180 // implementation is not supported. 9181 if (!ValInfo->hasValidIntValue()) 9182 return UnsupportedSTLError(); 9183 9184 MarkVariableReferenced(Loc, VD); 9185 } 9186 9187 // We've successfully built the required types and expressions. Update 9188 // the cache and return the newly cached value. 9189 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9190 return Info->getType(); 9191 } 9192 9193 /// Retrieve the special "std" namespace, which may require us to 9194 /// implicitly define the namespace. 9195 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9196 if (!StdNamespace) { 9197 // The "std" namespace has not yet been defined, so build one implicitly. 9198 StdNamespace = NamespaceDecl::Create(Context, 9199 Context.getTranslationUnitDecl(), 9200 /*Inline=*/false, 9201 SourceLocation(), SourceLocation(), 9202 &PP.getIdentifierTable().get("std"), 9203 /*PrevDecl=*/nullptr); 9204 getStdNamespace()->setImplicit(true); 9205 } 9206 9207 return getStdNamespace(); 9208 } 9209 9210 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9211 assert(getLangOpts().CPlusPlus && 9212 "Looking for std::initializer_list outside of C++."); 9213 9214 // We're looking for implicit instantiations of 9215 // template <typename E> class std::initializer_list. 9216 9217 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9218 return false; 9219 9220 ClassTemplateDecl *Template = nullptr; 9221 const TemplateArgument *Arguments = nullptr; 9222 9223 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9224 9225 ClassTemplateSpecializationDecl *Specialization = 9226 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9227 if (!Specialization) 9228 return false; 9229 9230 Template = Specialization->getSpecializedTemplate(); 9231 Arguments = Specialization->getTemplateArgs().data(); 9232 } else if (const TemplateSpecializationType *TST = 9233 Ty->getAs<TemplateSpecializationType>()) { 9234 Template = dyn_cast_or_null<ClassTemplateDecl>( 9235 TST->getTemplateName().getAsTemplateDecl()); 9236 Arguments = TST->getArgs(); 9237 } 9238 if (!Template) 9239 return false; 9240 9241 if (!StdInitializerList) { 9242 // Haven't recognized std::initializer_list yet, maybe this is it. 9243 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9244 if (TemplateClass->getIdentifier() != 9245 &PP.getIdentifierTable().get("initializer_list") || 9246 !getStdNamespace()->InEnclosingNamespaceSetOf( 9247 TemplateClass->getDeclContext())) 9248 return false; 9249 // This is a template called std::initializer_list, but is it the right 9250 // template? 9251 TemplateParameterList *Params = Template->getTemplateParameters(); 9252 if (Params->getMinRequiredArguments() != 1) 9253 return false; 9254 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9255 return false; 9256 9257 // It's the right template. 9258 StdInitializerList = Template; 9259 } 9260 9261 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9262 return false; 9263 9264 // This is an instance of std::initializer_list. Find the argument type. 9265 if (Element) 9266 *Element = Arguments[0].getAsType(); 9267 return true; 9268 } 9269 9270 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9271 NamespaceDecl *Std = S.getStdNamespace(); 9272 if (!Std) { 9273 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9274 return nullptr; 9275 } 9276 9277 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9278 Loc, Sema::LookupOrdinaryName); 9279 if (!S.LookupQualifiedName(Result, Std)) { 9280 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9281 return nullptr; 9282 } 9283 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9284 if (!Template) { 9285 Result.suppressDiagnostics(); 9286 // We found something weird. Complain about the first thing we found. 9287 NamedDecl *Found = *Result.begin(); 9288 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9289 return nullptr; 9290 } 9291 9292 // We found some template called std::initializer_list. Now verify that it's 9293 // correct. 9294 TemplateParameterList *Params = Template->getTemplateParameters(); 9295 if (Params->getMinRequiredArguments() != 1 || 9296 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9297 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9298 return nullptr; 9299 } 9300 9301 return Template; 9302 } 9303 9304 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9305 if (!StdInitializerList) { 9306 StdInitializerList = LookupStdInitializerList(*this, Loc); 9307 if (!StdInitializerList) 9308 return QualType(); 9309 } 9310 9311 TemplateArgumentListInfo Args(Loc, Loc); 9312 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9313 Context.getTrivialTypeSourceInfo(Element, 9314 Loc))); 9315 return Context.getCanonicalType( 9316 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9317 } 9318 9319 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9320 // C++ [dcl.init.list]p2: 9321 // A constructor is an initializer-list constructor if its first parameter 9322 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9323 // std::initializer_list<E> for some type E, and either there are no other 9324 // parameters or else all other parameters have default arguments. 9325 if (Ctor->getNumParams() < 1 || 9326 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9327 return false; 9328 9329 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9330 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9331 ArgType = RT->getPointeeType().getUnqualifiedType(); 9332 9333 return isStdInitializerList(ArgType, nullptr); 9334 } 9335 9336 /// Determine whether a using statement is in a context where it will be 9337 /// apply in all contexts. 9338 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9339 switch (CurContext->getDeclKind()) { 9340 case Decl::TranslationUnit: 9341 return true; 9342 case Decl::LinkageSpec: 9343 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9344 default: 9345 return false; 9346 } 9347 } 9348 9349 namespace { 9350 9351 // Callback to only accept typo corrections that are namespaces. 9352 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 9353 public: 9354 bool ValidateCandidate(const TypoCorrection &candidate) override { 9355 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9356 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9357 return false; 9358 } 9359 9360 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9361 return llvm::make_unique<NamespaceValidatorCCC>(*this); 9362 } 9363 }; 9364 9365 } 9366 9367 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9368 CXXScopeSpec &SS, 9369 SourceLocation IdentLoc, 9370 IdentifierInfo *Ident) { 9371 R.clear(); 9372 NamespaceValidatorCCC CCC{}; 9373 if (TypoCorrection Corrected = 9374 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 9375 Sema::CTK_ErrorRecovery)) { 9376 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9377 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9378 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9379 Ident->getName().equals(CorrectedStr); 9380 S.diagnoseTypo(Corrected, 9381 S.PDiag(diag::err_using_directive_member_suggest) 9382 << Ident << DC << DroppedSpecifier << SS.getRange(), 9383 S.PDiag(diag::note_namespace_defined_here)); 9384 } else { 9385 S.diagnoseTypo(Corrected, 9386 S.PDiag(diag::err_using_directive_suggest) << Ident, 9387 S.PDiag(diag::note_namespace_defined_here)); 9388 } 9389 R.addDecl(Corrected.getFoundDecl()); 9390 return true; 9391 } 9392 return false; 9393 } 9394 9395 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9396 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9397 SourceLocation IdentLoc, 9398 IdentifierInfo *NamespcName, 9399 const ParsedAttributesView &AttrList) { 9400 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9401 assert(NamespcName && "Invalid NamespcName."); 9402 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9403 9404 // This can only happen along a recovery path. 9405 while (S->isTemplateParamScope()) 9406 S = S->getParent(); 9407 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9408 9409 UsingDirectiveDecl *UDir = nullptr; 9410 NestedNameSpecifier *Qualifier = nullptr; 9411 if (SS.isSet()) 9412 Qualifier = SS.getScopeRep(); 9413 9414 // Lookup namespace name. 9415 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9416 LookupParsedName(R, S, &SS); 9417 if (R.isAmbiguous()) 9418 return nullptr; 9419 9420 if (R.empty()) { 9421 R.clear(); 9422 // Allow "using namespace std;" or "using namespace ::std;" even if 9423 // "std" hasn't been defined yet, for GCC compatibility. 9424 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9425 NamespcName->isStr("std")) { 9426 Diag(IdentLoc, diag::ext_using_undefined_std); 9427 R.addDecl(getOrCreateStdNamespace()); 9428 R.resolveKind(); 9429 } 9430 // Otherwise, attempt typo correction. 9431 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9432 } 9433 9434 if (!R.empty()) { 9435 NamedDecl *Named = R.getRepresentativeDecl(); 9436 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9437 assert(NS && "expected namespace decl"); 9438 9439 // The use of a nested name specifier may trigger deprecation warnings. 9440 DiagnoseUseOfDecl(Named, IdentLoc); 9441 9442 // C++ [namespace.udir]p1: 9443 // A using-directive specifies that the names in the nominated 9444 // namespace can be used in the scope in which the 9445 // using-directive appears after the using-directive. During 9446 // unqualified name lookup (3.4.1), the names appear as if they 9447 // were declared in the nearest enclosing namespace which 9448 // contains both the using-directive and the nominated 9449 // namespace. [Note: in this context, "contains" means "contains 9450 // directly or indirectly". ] 9451 9452 // Find enclosing context containing both using-directive and 9453 // nominated namespace. 9454 DeclContext *CommonAncestor = NS; 9455 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9456 CommonAncestor = CommonAncestor->getParent(); 9457 9458 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9459 SS.getWithLocInContext(Context), 9460 IdentLoc, Named, CommonAncestor); 9461 9462 if (IsUsingDirectiveInToplevelContext(CurContext) && 9463 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9464 Diag(IdentLoc, diag::warn_using_directive_in_header); 9465 } 9466 9467 PushUsingDirective(S, UDir); 9468 } else { 9469 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9470 } 9471 9472 if (UDir) 9473 ProcessDeclAttributeList(S, UDir, AttrList); 9474 9475 return UDir; 9476 } 9477 9478 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9479 // If the scope has an associated entity and the using directive is at 9480 // namespace or translation unit scope, add the UsingDirectiveDecl into 9481 // its lookup structure so qualified name lookup can find it. 9482 DeclContext *Ctx = S->getEntity(); 9483 if (Ctx && !Ctx->isFunctionOrMethod()) 9484 Ctx->addDecl(UDir); 9485 else 9486 // Otherwise, it is at block scope. The using-directives will affect lookup 9487 // only to the end of the scope. 9488 S->PushUsingDirective(UDir); 9489 } 9490 9491 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9492 SourceLocation UsingLoc, 9493 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9494 UnqualifiedId &Name, 9495 SourceLocation EllipsisLoc, 9496 const ParsedAttributesView &AttrList) { 9497 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9498 9499 if (SS.isEmpty()) { 9500 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 9501 return nullptr; 9502 } 9503 9504 switch (Name.getKind()) { 9505 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9506 case UnqualifiedIdKind::IK_Identifier: 9507 case UnqualifiedIdKind::IK_OperatorFunctionId: 9508 case UnqualifiedIdKind::IK_LiteralOperatorId: 9509 case UnqualifiedIdKind::IK_ConversionFunctionId: 9510 break; 9511 9512 case UnqualifiedIdKind::IK_ConstructorName: 9513 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9514 // C++11 inheriting constructors. 9515 Diag(Name.getBeginLoc(), 9516 getLangOpts().CPlusPlus11 9517 ? diag::warn_cxx98_compat_using_decl_constructor 9518 : diag::err_using_decl_constructor) 9519 << SS.getRange(); 9520 9521 if (getLangOpts().CPlusPlus11) break; 9522 9523 return nullptr; 9524 9525 case UnqualifiedIdKind::IK_DestructorName: 9526 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 9527 return nullptr; 9528 9529 case UnqualifiedIdKind::IK_TemplateId: 9530 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 9531 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9532 return nullptr; 9533 9534 case UnqualifiedIdKind::IK_DeductionGuideName: 9535 llvm_unreachable("cannot parse qualified deduction guide name"); 9536 } 9537 9538 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9539 DeclarationName TargetName = TargetNameInfo.getName(); 9540 if (!TargetName) 9541 return nullptr; 9542 9543 // Warn about access declarations. 9544 if (UsingLoc.isInvalid()) { 9545 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 9546 ? diag::err_access_decl 9547 : diag::warn_access_decl_deprecated) 9548 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9549 } 9550 9551 if (EllipsisLoc.isInvalid()) { 9552 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9553 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9554 return nullptr; 9555 } else { 9556 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9557 !TargetNameInfo.containsUnexpandedParameterPack()) { 9558 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9559 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9560 EllipsisLoc = SourceLocation(); 9561 } 9562 } 9563 9564 NamedDecl *UD = 9565 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9566 SS, TargetNameInfo, EllipsisLoc, AttrList, 9567 /*IsInstantiation*/false); 9568 if (UD) 9569 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9570 9571 return UD; 9572 } 9573 9574 /// Determine whether a using declaration considers the given 9575 /// declarations as "equivalent", e.g., if they are redeclarations of 9576 /// the same entity or are both typedefs of the same type. 9577 static bool 9578 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9579 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9580 return true; 9581 9582 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9583 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9584 return Context.hasSameType(TD1->getUnderlyingType(), 9585 TD2->getUnderlyingType()); 9586 9587 return false; 9588 } 9589 9590 9591 /// Determines whether to create a using shadow decl for a particular 9592 /// decl, given the set of decls existing prior to this using lookup. 9593 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9594 const LookupResult &Previous, 9595 UsingShadowDecl *&PrevShadow) { 9596 // Diagnose finding a decl which is not from a base class of the 9597 // current class. We do this now because there are cases where this 9598 // function will silently decide not to build a shadow decl, which 9599 // will pre-empt further diagnostics. 9600 // 9601 // We don't need to do this in C++11 because we do the check once on 9602 // the qualifier. 9603 // 9604 // FIXME: diagnose the following if we care enough: 9605 // struct A { int foo; }; 9606 // struct B : A { using A::foo; }; 9607 // template <class T> struct C : A {}; 9608 // template <class T> struct D : C<T> { using B::foo; } // <--- 9609 // This is invalid (during instantiation) in C++03 because B::foo 9610 // resolves to the using decl in B, which is not a base class of D<T>. 9611 // We can't diagnose it immediately because C<T> is an unknown 9612 // specialization. The UsingShadowDecl in D<T> then points directly 9613 // to A::foo, which will look well-formed when we instantiate. 9614 // The right solution is to not collapse the shadow-decl chain. 9615 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9616 DeclContext *OrigDC = Orig->getDeclContext(); 9617 9618 // Handle enums and anonymous structs. 9619 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9620 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9621 while (OrigRec->isAnonymousStructOrUnion()) 9622 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9623 9624 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9625 if (OrigDC == CurContext) { 9626 Diag(Using->getLocation(), 9627 diag::err_using_decl_nested_name_specifier_is_current_class) 9628 << Using->getQualifierLoc().getSourceRange(); 9629 Diag(Orig->getLocation(), diag::note_using_decl_target); 9630 Using->setInvalidDecl(); 9631 return true; 9632 } 9633 9634 Diag(Using->getQualifierLoc().getBeginLoc(), 9635 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9636 << Using->getQualifier() 9637 << cast<CXXRecordDecl>(CurContext) 9638 << Using->getQualifierLoc().getSourceRange(); 9639 Diag(Orig->getLocation(), diag::note_using_decl_target); 9640 Using->setInvalidDecl(); 9641 return true; 9642 } 9643 } 9644 9645 if (Previous.empty()) return false; 9646 9647 NamedDecl *Target = Orig; 9648 if (isa<UsingShadowDecl>(Target)) 9649 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9650 9651 // If the target happens to be one of the previous declarations, we 9652 // don't have a conflict. 9653 // 9654 // FIXME: but we might be increasing its access, in which case we 9655 // should redeclare it. 9656 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9657 bool FoundEquivalentDecl = false; 9658 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9659 I != E; ++I) { 9660 NamedDecl *D = (*I)->getUnderlyingDecl(); 9661 // We can have UsingDecls in our Previous results because we use the same 9662 // LookupResult for checking whether the UsingDecl itself is a valid 9663 // redeclaration. 9664 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9665 continue; 9666 9667 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9668 // C++ [class.mem]p19: 9669 // If T is the name of a class, then [every named member other than 9670 // a non-static data member] shall have a name different from T 9671 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9672 !isa<IndirectFieldDecl>(Target) && 9673 !isa<UnresolvedUsingValueDecl>(Target) && 9674 DiagnoseClassNameShadow( 9675 CurContext, 9676 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9677 return true; 9678 } 9679 9680 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9681 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9682 PrevShadow = Shadow; 9683 FoundEquivalentDecl = true; 9684 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9685 // We don't conflict with an existing using shadow decl of an equivalent 9686 // declaration, but we're not a redeclaration of it. 9687 FoundEquivalentDecl = true; 9688 } 9689 9690 if (isVisible(D)) 9691 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9692 } 9693 9694 if (FoundEquivalentDecl) 9695 return false; 9696 9697 if (FunctionDecl *FD = Target->getAsFunction()) { 9698 NamedDecl *OldDecl = nullptr; 9699 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9700 /*IsForUsingDecl*/ true)) { 9701 case Ovl_Overload: 9702 return false; 9703 9704 case Ovl_NonFunction: 9705 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9706 break; 9707 9708 // We found a decl with the exact signature. 9709 case Ovl_Match: 9710 // If we're in a record, we want to hide the target, so we 9711 // return true (without a diagnostic) to tell the caller not to 9712 // build a shadow decl. 9713 if (CurContext->isRecord()) 9714 return true; 9715 9716 // If we're not in a record, this is an error. 9717 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9718 break; 9719 } 9720 9721 Diag(Target->getLocation(), diag::note_using_decl_target); 9722 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9723 Using->setInvalidDecl(); 9724 return true; 9725 } 9726 9727 // Target is not a function. 9728 9729 if (isa<TagDecl>(Target)) { 9730 // No conflict between a tag and a non-tag. 9731 if (!Tag) return false; 9732 9733 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9734 Diag(Target->getLocation(), diag::note_using_decl_target); 9735 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9736 Using->setInvalidDecl(); 9737 return true; 9738 } 9739 9740 // No conflict between a tag and a non-tag. 9741 if (!NonTag) return false; 9742 9743 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9744 Diag(Target->getLocation(), diag::note_using_decl_target); 9745 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9746 Using->setInvalidDecl(); 9747 return true; 9748 } 9749 9750 /// Determine whether a direct base class is a virtual base class. 9751 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9752 if (!Derived->getNumVBases()) 9753 return false; 9754 for (auto &B : Derived->bases()) 9755 if (B.getType()->getAsCXXRecordDecl() == Base) 9756 return B.isVirtual(); 9757 llvm_unreachable("not a direct base class"); 9758 } 9759 9760 /// Builds a shadow declaration corresponding to a 'using' declaration. 9761 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9762 UsingDecl *UD, 9763 NamedDecl *Orig, 9764 UsingShadowDecl *PrevDecl) { 9765 // If we resolved to another shadow declaration, just coalesce them. 9766 NamedDecl *Target = Orig; 9767 if (isa<UsingShadowDecl>(Target)) { 9768 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9769 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9770 } 9771 9772 NamedDecl *NonTemplateTarget = Target; 9773 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9774 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9775 9776 UsingShadowDecl *Shadow; 9777 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9778 bool IsVirtualBase = 9779 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9780 UD->getQualifier()->getAsRecordDecl()); 9781 Shadow = ConstructorUsingShadowDecl::Create( 9782 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9783 } else { 9784 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9785 Target); 9786 } 9787 UD->addShadowDecl(Shadow); 9788 9789 Shadow->setAccess(UD->getAccess()); 9790 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9791 Shadow->setInvalidDecl(); 9792 9793 Shadow->setPreviousDecl(PrevDecl); 9794 9795 if (S) 9796 PushOnScopeChains(Shadow, S); 9797 else 9798 CurContext->addDecl(Shadow); 9799 9800 9801 return Shadow; 9802 } 9803 9804 /// Hides a using shadow declaration. This is required by the current 9805 /// using-decl implementation when a resolvable using declaration in a 9806 /// class is followed by a declaration which would hide or override 9807 /// one or more of the using decl's targets; for example: 9808 /// 9809 /// struct Base { void foo(int); }; 9810 /// struct Derived : Base { 9811 /// using Base::foo; 9812 /// void foo(int); 9813 /// }; 9814 /// 9815 /// The governing language is C++03 [namespace.udecl]p12: 9816 /// 9817 /// When a using-declaration brings names from a base class into a 9818 /// derived class scope, member functions in the derived class 9819 /// override and/or hide member functions with the same name and 9820 /// parameter types in a base class (rather than conflicting). 9821 /// 9822 /// There are two ways to implement this: 9823 /// (1) optimistically create shadow decls when they're not hidden 9824 /// by existing declarations, or 9825 /// (2) don't create any shadow decls (or at least don't make them 9826 /// visible) until we've fully parsed/instantiated the class. 9827 /// The problem with (1) is that we might have to retroactively remove 9828 /// a shadow decl, which requires several O(n) operations because the 9829 /// decl structures are (very reasonably) not designed for removal. 9830 /// (2) avoids this but is very fiddly and phase-dependent. 9831 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9832 if (Shadow->getDeclName().getNameKind() == 9833 DeclarationName::CXXConversionFunctionName) 9834 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9835 9836 // Remove it from the DeclContext... 9837 Shadow->getDeclContext()->removeDecl(Shadow); 9838 9839 // ...and the scope, if applicable... 9840 if (S) { 9841 S->RemoveDecl(Shadow); 9842 IdResolver.RemoveDecl(Shadow); 9843 } 9844 9845 // ...and the using decl. 9846 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9847 9848 // TODO: complain somehow if Shadow was used. It shouldn't 9849 // be possible for this to happen, because...? 9850 } 9851 9852 /// Find the base specifier for a base class with the given type. 9853 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9854 QualType DesiredBase, 9855 bool &AnyDependentBases) { 9856 // Check whether the named type is a direct base class. 9857 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9858 for (auto &Base : Derived->bases()) { 9859 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9860 if (CanonicalDesiredBase == BaseType) 9861 return &Base; 9862 if (BaseType->isDependentType()) 9863 AnyDependentBases = true; 9864 } 9865 return nullptr; 9866 } 9867 9868 namespace { 9869 class UsingValidatorCCC final : public CorrectionCandidateCallback { 9870 public: 9871 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9872 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9873 : HasTypenameKeyword(HasTypenameKeyword), 9874 IsInstantiation(IsInstantiation), OldNNS(NNS), 9875 RequireMemberOf(RequireMemberOf) {} 9876 9877 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9878 NamedDecl *ND = Candidate.getCorrectionDecl(); 9879 9880 // Keywords are not valid here. 9881 if (!ND || isa<NamespaceDecl>(ND)) 9882 return false; 9883 9884 // Completely unqualified names are invalid for a 'using' declaration. 9885 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9886 return false; 9887 9888 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9889 // reject. 9890 9891 if (RequireMemberOf) { 9892 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9893 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9894 // No-one ever wants a using-declaration to name an injected-class-name 9895 // of a base class, unless they're declaring an inheriting constructor. 9896 ASTContext &Ctx = ND->getASTContext(); 9897 if (!Ctx.getLangOpts().CPlusPlus11) 9898 return false; 9899 QualType FoundType = Ctx.getRecordType(FoundRecord); 9900 9901 // Check that the injected-class-name is named as a member of its own 9902 // type; we don't want to suggest 'using Derived::Base;', since that 9903 // means something else. 9904 NestedNameSpecifier *Specifier = 9905 Candidate.WillReplaceSpecifier() 9906 ? Candidate.getCorrectionSpecifier() 9907 : OldNNS; 9908 if (!Specifier->getAsType() || 9909 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9910 return false; 9911 9912 // Check that this inheriting constructor declaration actually names a 9913 // direct base class of the current class. 9914 bool AnyDependentBases = false; 9915 if (!findDirectBaseWithType(RequireMemberOf, 9916 Ctx.getRecordType(FoundRecord), 9917 AnyDependentBases) && 9918 !AnyDependentBases) 9919 return false; 9920 } else { 9921 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9922 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9923 return false; 9924 9925 // FIXME: Check that the base class member is accessible? 9926 } 9927 } else { 9928 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9929 if (FoundRecord && FoundRecord->isInjectedClassName()) 9930 return false; 9931 } 9932 9933 if (isa<TypeDecl>(ND)) 9934 return HasTypenameKeyword || !IsInstantiation; 9935 9936 return !HasTypenameKeyword; 9937 } 9938 9939 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9940 return llvm::make_unique<UsingValidatorCCC>(*this); 9941 } 9942 9943 private: 9944 bool HasTypenameKeyword; 9945 bool IsInstantiation; 9946 NestedNameSpecifier *OldNNS; 9947 CXXRecordDecl *RequireMemberOf; 9948 }; 9949 } // end anonymous namespace 9950 9951 /// Builds a using declaration. 9952 /// 9953 /// \param IsInstantiation - Whether this call arises from an 9954 /// instantiation of an unresolved using declaration. We treat 9955 /// the lookup differently for these declarations. 9956 NamedDecl *Sema::BuildUsingDeclaration( 9957 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 9958 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 9959 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 9960 const ParsedAttributesView &AttrList, bool IsInstantiation) { 9961 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9962 SourceLocation IdentLoc = NameInfo.getLoc(); 9963 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9964 9965 // FIXME: We ignore attributes for now. 9966 9967 // For an inheriting constructor declaration, the name of the using 9968 // declaration is the name of a constructor in this class, not in the 9969 // base class. 9970 DeclarationNameInfo UsingName = NameInfo; 9971 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9972 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9973 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9974 Context.getCanonicalType(Context.getRecordType(RD)))); 9975 9976 // Do the redeclaration lookup in the current scope. 9977 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9978 ForVisibleRedeclaration); 9979 Previous.setHideTags(false); 9980 if (S) { 9981 LookupName(Previous, S); 9982 9983 // It is really dumb that we have to do this. 9984 LookupResult::Filter F = Previous.makeFilter(); 9985 while (F.hasNext()) { 9986 NamedDecl *D = F.next(); 9987 if (!isDeclInScope(D, CurContext, S)) 9988 F.erase(); 9989 // If we found a local extern declaration that's not ordinarily visible, 9990 // and this declaration is being added to a non-block scope, ignore it. 9991 // We're only checking for scope conflicts here, not also for violations 9992 // of the linkage rules. 9993 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9994 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9995 F.erase(); 9996 } 9997 F.done(); 9998 } else { 9999 assert(IsInstantiation && "no scope in non-instantiation"); 10000 if (CurContext->isRecord()) 10001 LookupQualifiedName(Previous, CurContext); 10002 else { 10003 // No redeclaration check is needed here; in non-member contexts we 10004 // diagnosed all possible conflicts with other using-declarations when 10005 // building the template: 10006 // 10007 // For a dependent non-type using declaration, the only valid case is 10008 // if we instantiate to a single enumerator. We check for conflicts 10009 // between shadow declarations we introduce, and we check in the template 10010 // definition for conflicts between a non-type using declaration and any 10011 // other declaration, which together covers all cases. 10012 // 10013 // A dependent typename using declaration will never successfully 10014 // instantiate, since it will always name a class member, so we reject 10015 // that in the template definition. 10016 } 10017 } 10018 10019 // Check for invalid redeclarations. 10020 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 10021 SS, IdentLoc, Previous)) 10022 return nullptr; 10023 10024 // Check for bad qualifiers. 10025 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 10026 IdentLoc)) 10027 return nullptr; 10028 10029 DeclContext *LookupContext = computeDeclContext(SS); 10030 NamedDecl *D; 10031 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10032 if (!LookupContext || EllipsisLoc.isValid()) { 10033 if (HasTypenameKeyword) { 10034 // FIXME: not all declaration name kinds are legal here 10035 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 10036 UsingLoc, TypenameLoc, 10037 QualifierLoc, 10038 IdentLoc, NameInfo.getName(), 10039 EllipsisLoc); 10040 } else { 10041 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 10042 QualifierLoc, NameInfo, EllipsisLoc); 10043 } 10044 D->setAccess(AS); 10045 CurContext->addDecl(D); 10046 return D; 10047 } 10048 10049 auto Build = [&](bool Invalid) { 10050 UsingDecl *UD = 10051 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 10052 UsingName, HasTypenameKeyword); 10053 UD->setAccess(AS); 10054 CurContext->addDecl(UD); 10055 UD->setInvalidDecl(Invalid); 10056 return UD; 10057 }; 10058 auto BuildInvalid = [&]{ return Build(true); }; 10059 auto BuildValid = [&]{ return Build(false); }; 10060 10061 if (RequireCompleteDeclContext(SS, LookupContext)) 10062 return BuildInvalid(); 10063 10064 // Look up the target name. 10065 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10066 10067 // Unlike most lookups, we don't always want to hide tag 10068 // declarations: tag names are visible through the using declaration 10069 // even if hidden by ordinary names, *except* in a dependent context 10070 // where it's important for the sanity of two-phase lookup. 10071 if (!IsInstantiation) 10072 R.setHideTags(false); 10073 10074 // For the purposes of this lookup, we have a base object type 10075 // equal to that of the current context. 10076 if (CurContext->isRecord()) { 10077 R.setBaseObjectType( 10078 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 10079 } 10080 10081 LookupQualifiedName(R, LookupContext); 10082 10083 // Try to correct typos if possible. If constructor name lookup finds no 10084 // results, that means the named class has no explicit constructors, and we 10085 // suppressed declaring implicit ones (probably because it's dependent or 10086 // invalid). 10087 if (R.empty() && 10088 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 10089 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 10090 // it will believe that glibc provides a ::gets in cases where it does not, 10091 // and will try to pull it into namespace std with a using-declaration. 10092 // Just ignore the using-declaration in that case. 10093 auto *II = NameInfo.getName().getAsIdentifierInfo(); 10094 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 10095 CurContext->isStdNamespace() && 10096 isa<TranslationUnitDecl>(LookupContext) && 10097 getSourceManager().isInSystemHeader(UsingLoc)) 10098 return nullptr; 10099 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 10100 dyn_cast<CXXRecordDecl>(CurContext)); 10101 if (TypoCorrection Corrected = 10102 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 10103 CTK_ErrorRecovery)) { 10104 // We reject candidates where DroppedSpecifier == true, hence the 10105 // literal '0' below. 10106 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 10107 << NameInfo.getName() << LookupContext << 0 10108 << SS.getRange()); 10109 10110 // If we picked a correction with no attached Decl we can't do anything 10111 // useful with it, bail out. 10112 NamedDecl *ND = Corrected.getCorrectionDecl(); 10113 if (!ND) 10114 return BuildInvalid(); 10115 10116 // If we corrected to an inheriting constructor, handle it as one. 10117 auto *RD = dyn_cast<CXXRecordDecl>(ND); 10118 if (RD && RD->isInjectedClassName()) { 10119 // The parent of the injected class name is the class itself. 10120 RD = cast<CXXRecordDecl>(RD->getParent()); 10121 10122 // Fix up the information we'll use to build the using declaration. 10123 if (Corrected.WillReplaceSpecifier()) { 10124 NestedNameSpecifierLocBuilder Builder; 10125 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 10126 QualifierLoc.getSourceRange()); 10127 QualifierLoc = Builder.getWithLocInContext(Context); 10128 } 10129 10130 // In this case, the name we introduce is the name of a derived class 10131 // constructor. 10132 auto *CurClass = cast<CXXRecordDecl>(CurContext); 10133 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10134 Context.getCanonicalType(Context.getRecordType(CurClass)))); 10135 UsingName.setNamedTypeInfo(nullptr); 10136 for (auto *Ctor : LookupConstructors(RD)) 10137 R.addDecl(Ctor); 10138 R.resolveKind(); 10139 } else { 10140 // FIXME: Pick up all the declarations if we found an overloaded 10141 // function. 10142 UsingName.setName(ND->getDeclName()); 10143 R.addDecl(ND); 10144 } 10145 } else { 10146 Diag(IdentLoc, diag::err_no_member) 10147 << NameInfo.getName() << LookupContext << SS.getRange(); 10148 return BuildInvalid(); 10149 } 10150 } 10151 10152 if (R.isAmbiguous()) 10153 return BuildInvalid(); 10154 10155 if (HasTypenameKeyword) { 10156 // If we asked for a typename and got a non-type decl, error out. 10157 if (!R.getAsSingle<TypeDecl>()) { 10158 Diag(IdentLoc, diag::err_using_typename_non_type); 10159 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10160 Diag((*I)->getUnderlyingDecl()->getLocation(), 10161 diag::note_using_decl_target); 10162 return BuildInvalid(); 10163 } 10164 } else { 10165 // If we asked for a non-typename and we got a type, error out, 10166 // but only if this is an instantiation of an unresolved using 10167 // decl. Otherwise just silently find the type name. 10168 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10169 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10170 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10171 return BuildInvalid(); 10172 } 10173 } 10174 10175 // C++14 [namespace.udecl]p6: 10176 // A using-declaration shall not name a namespace. 10177 if (R.getAsSingle<NamespaceDecl>()) { 10178 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10179 << SS.getRange(); 10180 return BuildInvalid(); 10181 } 10182 10183 // C++14 [namespace.udecl]p7: 10184 // A using-declaration shall not name a scoped enumerator. 10185 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10186 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10187 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10188 << SS.getRange(); 10189 return BuildInvalid(); 10190 } 10191 } 10192 10193 UsingDecl *UD = BuildValid(); 10194 10195 // Some additional rules apply to inheriting constructors. 10196 if (UsingName.getName().getNameKind() == 10197 DeclarationName::CXXConstructorName) { 10198 // Suppress access diagnostics; the access check is instead performed at the 10199 // point of use for an inheriting constructor. 10200 R.suppressDiagnostics(); 10201 if (CheckInheritingConstructorUsingDecl(UD)) 10202 return UD; 10203 } 10204 10205 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10206 UsingShadowDecl *PrevDecl = nullptr; 10207 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10208 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10209 } 10210 10211 return UD; 10212 } 10213 10214 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10215 ArrayRef<NamedDecl *> Expansions) { 10216 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10217 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10218 isa<UsingPackDecl>(InstantiatedFrom)); 10219 10220 auto *UPD = 10221 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10222 UPD->setAccess(InstantiatedFrom->getAccess()); 10223 CurContext->addDecl(UPD); 10224 return UPD; 10225 } 10226 10227 /// Additional checks for a using declaration referring to a constructor name. 10228 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10229 assert(!UD->hasTypename() && "expecting a constructor name"); 10230 10231 const Type *SourceType = UD->getQualifier()->getAsType(); 10232 assert(SourceType && 10233 "Using decl naming constructor doesn't have type in scope spec."); 10234 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10235 10236 // Check whether the named type is a direct base class. 10237 bool AnyDependentBases = false; 10238 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10239 AnyDependentBases); 10240 if (!Base && !AnyDependentBases) { 10241 Diag(UD->getUsingLoc(), 10242 diag::err_using_decl_constructor_not_in_direct_base) 10243 << UD->getNameInfo().getSourceRange() 10244 << QualType(SourceType, 0) << TargetClass; 10245 UD->setInvalidDecl(); 10246 return true; 10247 } 10248 10249 if (Base) 10250 Base->setInheritConstructors(); 10251 10252 return false; 10253 } 10254 10255 /// Checks that the given using declaration is not an invalid 10256 /// redeclaration. Note that this is checking only for the using decl 10257 /// itself, not for any ill-formedness among the UsingShadowDecls. 10258 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10259 bool HasTypenameKeyword, 10260 const CXXScopeSpec &SS, 10261 SourceLocation NameLoc, 10262 const LookupResult &Prev) { 10263 NestedNameSpecifier *Qual = SS.getScopeRep(); 10264 10265 // C++03 [namespace.udecl]p8: 10266 // C++0x [namespace.udecl]p10: 10267 // A using-declaration is a declaration and can therefore be used 10268 // repeatedly where (and only where) multiple declarations are 10269 // allowed. 10270 // 10271 // That's in non-member contexts. 10272 if (!CurContext->getRedeclContext()->isRecord()) { 10273 // A dependent qualifier outside a class can only ever resolve to an 10274 // enumeration type. Therefore it conflicts with any other non-type 10275 // declaration in the same scope. 10276 // FIXME: How should we check for dependent type-type conflicts at block 10277 // scope? 10278 if (Qual->isDependent() && !HasTypenameKeyword) { 10279 for (auto *D : Prev) { 10280 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10281 bool OldCouldBeEnumerator = 10282 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10283 Diag(NameLoc, 10284 OldCouldBeEnumerator ? diag::err_redefinition 10285 : diag::err_redefinition_different_kind) 10286 << Prev.getLookupName(); 10287 Diag(D->getLocation(), diag::note_previous_definition); 10288 return true; 10289 } 10290 } 10291 } 10292 return false; 10293 } 10294 10295 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10296 NamedDecl *D = *I; 10297 10298 bool DTypename; 10299 NestedNameSpecifier *DQual; 10300 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10301 DTypename = UD->hasTypename(); 10302 DQual = UD->getQualifier(); 10303 } else if (UnresolvedUsingValueDecl *UD 10304 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10305 DTypename = false; 10306 DQual = UD->getQualifier(); 10307 } else if (UnresolvedUsingTypenameDecl *UD 10308 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10309 DTypename = true; 10310 DQual = UD->getQualifier(); 10311 } else continue; 10312 10313 // using decls differ if one says 'typename' and the other doesn't. 10314 // FIXME: non-dependent using decls? 10315 if (HasTypenameKeyword != DTypename) continue; 10316 10317 // using decls differ if they name different scopes (but note that 10318 // template instantiation can cause this check to trigger when it 10319 // didn't before instantiation). 10320 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10321 Context.getCanonicalNestedNameSpecifier(DQual)) 10322 continue; 10323 10324 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10325 Diag(D->getLocation(), diag::note_using_decl) << 1; 10326 return true; 10327 } 10328 10329 return false; 10330 } 10331 10332 10333 /// Checks that the given nested-name qualifier used in a using decl 10334 /// in the current context is appropriately related to the current 10335 /// scope. If an error is found, diagnoses it and returns true. 10336 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10337 bool HasTypename, 10338 const CXXScopeSpec &SS, 10339 const DeclarationNameInfo &NameInfo, 10340 SourceLocation NameLoc) { 10341 DeclContext *NamedContext = computeDeclContext(SS); 10342 10343 if (!CurContext->isRecord()) { 10344 // C++03 [namespace.udecl]p3: 10345 // C++0x [namespace.udecl]p8: 10346 // A using-declaration for a class member shall be a member-declaration. 10347 10348 // If we weren't able to compute a valid scope, it might validly be a 10349 // dependent class scope or a dependent enumeration unscoped scope. If 10350 // we have a 'typename' keyword, the scope must resolve to a class type. 10351 if ((HasTypename && !NamedContext) || 10352 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10353 auto *RD = NamedContext 10354 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10355 : nullptr; 10356 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10357 RD = nullptr; 10358 10359 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10360 << SS.getRange(); 10361 10362 // If we have a complete, non-dependent source type, try to suggest a 10363 // way to get the same effect. 10364 if (!RD) 10365 return true; 10366 10367 // Find what this using-declaration was referring to. 10368 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10369 R.setHideTags(false); 10370 R.suppressDiagnostics(); 10371 LookupQualifiedName(R, RD); 10372 10373 if (R.getAsSingle<TypeDecl>()) { 10374 if (getLangOpts().CPlusPlus11) { 10375 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10376 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10377 << 0 // alias declaration 10378 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10379 NameInfo.getName().getAsString() + 10380 " = "); 10381 } else { 10382 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10383 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 10384 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10385 << 1 // typedef declaration 10386 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10387 << FixItHint::CreateInsertion( 10388 InsertLoc, " " + NameInfo.getName().getAsString()); 10389 } 10390 } else if (R.getAsSingle<VarDecl>()) { 10391 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10392 // repeating the type of the static data member here. 10393 FixItHint FixIt; 10394 if (getLangOpts().CPlusPlus11) { 10395 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10396 FixIt = FixItHint::CreateReplacement( 10397 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10398 } 10399 10400 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10401 << 2 // reference declaration 10402 << FixIt; 10403 } else if (R.getAsSingle<EnumConstantDecl>()) { 10404 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10405 // repeating the type of the enumeration here, and we can't do so if 10406 // the type is anonymous. 10407 FixItHint FixIt; 10408 if (getLangOpts().CPlusPlus11) { 10409 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10410 FixIt = FixItHint::CreateReplacement( 10411 UsingLoc, 10412 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10413 } 10414 10415 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10416 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10417 << FixIt; 10418 } 10419 return true; 10420 } 10421 10422 // Otherwise, this might be valid. 10423 return false; 10424 } 10425 10426 // The current scope is a record. 10427 10428 // If the named context is dependent, we can't decide much. 10429 if (!NamedContext) { 10430 // FIXME: in C++0x, we can diagnose if we can prove that the 10431 // nested-name-specifier does not refer to a base class, which is 10432 // still possible in some cases. 10433 10434 // Otherwise we have to conservatively report that things might be 10435 // okay. 10436 return false; 10437 } 10438 10439 if (!NamedContext->isRecord()) { 10440 // Ideally this would point at the last name in the specifier, 10441 // but we don't have that level of source info. 10442 Diag(SS.getRange().getBegin(), 10443 diag::err_using_decl_nested_name_specifier_is_not_class) 10444 << SS.getScopeRep() << SS.getRange(); 10445 return true; 10446 } 10447 10448 if (!NamedContext->isDependentContext() && 10449 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10450 return true; 10451 10452 if (getLangOpts().CPlusPlus11) { 10453 // C++11 [namespace.udecl]p3: 10454 // In a using-declaration used as a member-declaration, the 10455 // nested-name-specifier shall name a base class of the class 10456 // being defined. 10457 10458 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10459 cast<CXXRecordDecl>(NamedContext))) { 10460 if (CurContext == NamedContext) { 10461 Diag(NameLoc, 10462 diag::err_using_decl_nested_name_specifier_is_current_class) 10463 << SS.getRange(); 10464 return true; 10465 } 10466 10467 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10468 Diag(SS.getRange().getBegin(), 10469 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10470 << SS.getScopeRep() 10471 << cast<CXXRecordDecl>(CurContext) 10472 << SS.getRange(); 10473 } 10474 return true; 10475 } 10476 10477 return false; 10478 } 10479 10480 // C++03 [namespace.udecl]p4: 10481 // A using-declaration used as a member-declaration shall refer 10482 // to a member of a base class of the class being defined [etc.]. 10483 10484 // Salient point: SS doesn't have to name a base class as long as 10485 // lookup only finds members from base classes. Therefore we can 10486 // diagnose here only if we can prove that that can't happen, 10487 // i.e. if the class hierarchies provably don't intersect. 10488 10489 // TODO: it would be nice if "definitely valid" results were cached 10490 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10491 // need to be repeated. 10492 10493 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10494 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10495 Bases.insert(Base); 10496 return true; 10497 }; 10498 10499 // Collect all bases. Return false if we find a dependent base. 10500 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10501 return false; 10502 10503 // Returns true if the base is dependent or is one of the accumulated base 10504 // classes. 10505 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10506 return !Bases.count(Base); 10507 }; 10508 10509 // Return false if the class has a dependent base or if it or one 10510 // of its bases is present in the base set of the current context. 10511 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10512 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10513 return false; 10514 10515 Diag(SS.getRange().getBegin(), 10516 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10517 << SS.getScopeRep() 10518 << cast<CXXRecordDecl>(CurContext) 10519 << SS.getRange(); 10520 10521 return true; 10522 } 10523 10524 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10525 MultiTemplateParamsArg TemplateParamLists, 10526 SourceLocation UsingLoc, UnqualifiedId &Name, 10527 const ParsedAttributesView &AttrList, 10528 TypeResult Type, Decl *DeclFromDeclSpec) { 10529 // Skip up to the relevant declaration scope. 10530 while (S->isTemplateParamScope()) 10531 S = S->getParent(); 10532 assert((S->getFlags() & Scope::DeclScope) && 10533 "got alias-declaration outside of declaration scope"); 10534 10535 if (Type.isInvalid()) 10536 return nullptr; 10537 10538 bool Invalid = false; 10539 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10540 TypeSourceInfo *TInfo = nullptr; 10541 GetTypeFromParser(Type.get(), &TInfo); 10542 10543 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10544 return nullptr; 10545 10546 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10547 UPPC_DeclarationType)) { 10548 Invalid = true; 10549 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10550 TInfo->getTypeLoc().getBeginLoc()); 10551 } 10552 10553 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10554 TemplateParamLists.size() 10555 ? forRedeclarationInCurContext() 10556 : ForVisibleRedeclaration); 10557 LookupName(Previous, S); 10558 10559 // Warn about shadowing the name of a template parameter. 10560 if (Previous.isSingleResult() && 10561 Previous.getFoundDecl()->isTemplateParameter()) { 10562 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10563 Previous.clear(); 10564 } 10565 10566 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10567 "name in alias declaration must be an identifier"); 10568 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10569 Name.StartLocation, 10570 Name.Identifier, TInfo); 10571 10572 NewTD->setAccess(AS); 10573 10574 if (Invalid) 10575 NewTD->setInvalidDecl(); 10576 10577 ProcessDeclAttributeList(S, NewTD, AttrList); 10578 AddPragmaAttributes(S, NewTD); 10579 10580 CheckTypedefForVariablyModifiedType(S, NewTD); 10581 Invalid |= NewTD->isInvalidDecl(); 10582 10583 bool Redeclaration = false; 10584 10585 NamedDecl *NewND; 10586 if (TemplateParamLists.size()) { 10587 TypeAliasTemplateDecl *OldDecl = nullptr; 10588 TemplateParameterList *OldTemplateParams = nullptr; 10589 10590 if (TemplateParamLists.size() != 1) { 10591 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10592 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10593 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10594 } 10595 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10596 10597 // Check that we can declare a template here. 10598 if (CheckTemplateDeclScope(S, TemplateParams)) 10599 return nullptr; 10600 10601 // Only consider previous declarations in the same scope. 10602 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10603 /*ExplicitInstantiationOrSpecialization*/false); 10604 if (!Previous.empty()) { 10605 Redeclaration = true; 10606 10607 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10608 if (!OldDecl && !Invalid) { 10609 Diag(UsingLoc, diag::err_redefinition_different_kind) 10610 << Name.Identifier; 10611 10612 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10613 if (OldD->getLocation().isValid()) 10614 Diag(OldD->getLocation(), diag::note_previous_definition); 10615 10616 Invalid = true; 10617 } 10618 10619 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10620 if (TemplateParameterListsAreEqual(TemplateParams, 10621 OldDecl->getTemplateParameters(), 10622 /*Complain=*/true, 10623 TPL_TemplateMatch)) 10624 OldTemplateParams = 10625 OldDecl->getMostRecentDecl()->getTemplateParameters(); 10626 else 10627 Invalid = true; 10628 10629 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10630 if (!Invalid && 10631 !Context.hasSameType(OldTD->getUnderlyingType(), 10632 NewTD->getUnderlyingType())) { 10633 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10634 // but we can't reasonably accept it. 10635 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10636 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10637 if (OldTD->getLocation().isValid()) 10638 Diag(OldTD->getLocation(), diag::note_previous_definition); 10639 Invalid = true; 10640 } 10641 } 10642 } 10643 10644 // Merge any previous default template arguments into our parameters, 10645 // and check the parameter list. 10646 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10647 TPC_TypeAliasTemplate)) 10648 return nullptr; 10649 10650 TypeAliasTemplateDecl *NewDecl = 10651 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10652 Name.Identifier, TemplateParams, 10653 NewTD); 10654 NewTD->setDescribedAliasTemplate(NewDecl); 10655 10656 NewDecl->setAccess(AS); 10657 10658 if (Invalid) 10659 NewDecl->setInvalidDecl(); 10660 else if (OldDecl) { 10661 NewDecl->setPreviousDecl(OldDecl); 10662 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10663 } 10664 10665 NewND = NewDecl; 10666 } else { 10667 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10668 setTagNameForLinkagePurposes(TD, NewTD); 10669 handleTagNumbering(TD, S); 10670 } 10671 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10672 NewND = NewTD; 10673 } 10674 10675 PushOnScopeChains(NewND, S); 10676 ActOnDocumentableDecl(NewND); 10677 return NewND; 10678 } 10679 10680 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10681 SourceLocation AliasLoc, 10682 IdentifierInfo *Alias, CXXScopeSpec &SS, 10683 SourceLocation IdentLoc, 10684 IdentifierInfo *Ident) { 10685 10686 // Lookup the namespace name. 10687 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10688 LookupParsedName(R, S, &SS); 10689 10690 if (R.isAmbiguous()) 10691 return nullptr; 10692 10693 if (R.empty()) { 10694 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10695 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10696 return nullptr; 10697 } 10698 } 10699 assert(!R.isAmbiguous() && !R.empty()); 10700 NamedDecl *ND = R.getRepresentativeDecl(); 10701 10702 // Check if we have a previous declaration with the same name. 10703 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10704 ForVisibleRedeclaration); 10705 LookupName(PrevR, S); 10706 10707 // Check we're not shadowing a template parameter. 10708 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10709 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10710 PrevR.clear(); 10711 } 10712 10713 // Filter out any other lookup result from an enclosing scope. 10714 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10715 /*AllowInlineNamespace*/false); 10716 10717 // Find the previous declaration and check that we can redeclare it. 10718 NamespaceAliasDecl *Prev = nullptr; 10719 if (PrevR.isSingleResult()) { 10720 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10721 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10722 // We already have an alias with the same name that points to the same 10723 // namespace; check that it matches. 10724 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10725 Prev = AD; 10726 } else if (isVisible(PrevDecl)) { 10727 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10728 << Alias; 10729 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10730 << AD->getNamespace(); 10731 return nullptr; 10732 } 10733 } else if (isVisible(PrevDecl)) { 10734 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10735 ? diag::err_redefinition 10736 : diag::err_redefinition_different_kind; 10737 Diag(AliasLoc, DiagID) << Alias; 10738 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10739 return nullptr; 10740 } 10741 } 10742 10743 // The use of a nested name specifier may trigger deprecation warnings. 10744 DiagnoseUseOfDecl(ND, IdentLoc); 10745 10746 NamespaceAliasDecl *AliasDecl = 10747 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10748 Alias, SS.getWithLocInContext(Context), 10749 IdentLoc, ND); 10750 if (Prev) 10751 AliasDecl->setPreviousDecl(Prev); 10752 10753 PushOnScopeChains(AliasDecl, S); 10754 return AliasDecl; 10755 } 10756 10757 namespace { 10758 struct SpecialMemberExceptionSpecInfo 10759 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10760 SourceLocation Loc; 10761 Sema::ImplicitExceptionSpecification ExceptSpec; 10762 10763 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10764 Sema::CXXSpecialMember CSM, 10765 Sema::InheritedConstructorInfo *ICI, 10766 SourceLocation Loc) 10767 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10768 10769 bool visitBase(CXXBaseSpecifier *Base); 10770 bool visitField(FieldDecl *FD); 10771 10772 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10773 unsigned Quals); 10774 10775 void visitSubobjectCall(Subobject Subobj, 10776 Sema::SpecialMemberOverloadResult SMOR); 10777 }; 10778 } 10779 10780 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10781 auto *RT = Base->getType()->getAs<RecordType>(); 10782 if (!RT) 10783 return false; 10784 10785 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10786 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10787 if (auto *BaseCtor = SMOR.getMethod()) { 10788 visitSubobjectCall(Base, BaseCtor); 10789 return false; 10790 } 10791 10792 visitClassSubobject(BaseClass, Base, 0); 10793 return false; 10794 } 10795 10796 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10797 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10798 Expr *E = FD->getInClassInitializer(); 10799 if (!E) 10800 // FIXME: It's a little wasteful to build and throw away a 10801 // CXXDefaultInitExpr here. 10802 // FIXME: We should have a single context note pointing at Loc, and 10803 // this location should be MD->getLocation() instead, since that's 10804 // the location where we actually use the default init expression. 10805 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10806 if (E) 10807 ExceptSpec.CalledExpr(E); 10808 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10809 ->getAs<RecordType>()) { 10810 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10811 FD->getType().getCVRQualifiers()); 10812 } 10813 return false; 10814 } 10815 10816 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10817 Subobject Subobj, 10818 unsigned Quals) { 10819 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10820 bool IsMutable = Field && Field->isMutable(); 10821 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10822 } 10823 10824 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10825 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10826 // Note, if lookup fails, it doesn't matter what exception specification we 10827 // choose because the special member will be deleted. 10828 if (CXXMethodDecl *MD = SMOR.getMethod()) 10829 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10830 } 10831 10832 namespace { 10833 /// RAII object to register a special member as being currently declared. 10834 struct ComputingExceptionSpec { 10835 Sema &S; 10836 10837 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 10838 : S(S) { 10839 Sema::CodeSynthesisContext Ctx; 10840 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 10841 Ctx.PointOfInstantiation = Loc; 10842 Ctx.Entity = MD; 10843 S.pushCodeSynthesisContext(Ctx); 10844 } 10845 ~ComputingExceptionSpec() { 10846 S.popCodeSynthesisContext(); 10847 } 10848 }; 10849 } 10850 10851 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 10852 llvm::APSInt Result; 10853 ExprResult Converted = CheckConvertedConstantExpression( 10854 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 10855 ExplicitSpec.setExpr(Converted.get()); 10856 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 10857 ExplicitSpec.setKind(Result.getBoolValue() 10858 ? ExplicitSpecKind::ResolvedTrue 10859 : ExplicitSpecKind::ResolvedFalse); 10860 return true; 10861 } 10862 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 10863 return false; 10864 } 10865 10866 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 10867 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 10868 if (!ExplicitExpr->isTypeDependent()) 10869 tryResolveExplicitSpecifier(ES); 10870 return ES; 10871 } 10872 10873 static Sema::ImplicitExceptionSpecification 10874 ComputeDefaultedSpecialMemberExceptionSpec( 10875 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10876 Sema::InheritedConstructorInfo *ICI) { 10877 ComputingExceptionSpec CES(S, MD, Loc); 10878 10879 CXXRecordDecl *ClassDecl = MD->getParent(); 10880 10881 // C++ [except.spec]p14: 10882 // An implicitly declared special member function (Clause 12) shall have an 10883 // exception-specification. [...] 10884 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 10885 if (ClassDecl->isInvalidDecl()) 10886 return Info.ExceptSpec; 10887 10888 // FIXME: If this diagnostic fires, we're probably missing a check for 10889 // attempting to resolve an exception specification before it's known 10890 // at a higher level. 10891 if (S.RequireCompleteType(MD->getLocation(), 10892 S.Context.getRecordType(ClassDecl), 10893 diag::err_exception_spec_incomplete_type)) 10894 return Info.ExceptSpec; 10895 10896 // C++1z [except.spec]p7: 10897 // [Look for exceptions thrown by] a constructor selected [...] to 10898 // initialize a potentially constructed subobject, 10899 // C++1z [except.spec]p8: 10900 // The exception specification for an implicitly-declared destructor, or a 10901 // destructor without a noexcept-specifier, is potentially-throwing if and 10902 // only if any of the destructors for any of its potentially constructed 10903 // subojects is potentially throwing. 10904 // FIXME: We respect the first rule but ignore the "potentially constructed" 10905 // in the second rule to resolve a core issue (no number yet) that would have 10906 // us reject: 10907 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10908 // struct B : A {}; 10909 // struct C : B { void f(); }; 10910 // ... due to giving B::~B() a non-throwing exception specification. 10911 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10912 : Info.VisitAllBases); 10913 10914 return Info.ExceptSpec; 10915 } 10916 10917 namespace { 10918 /// RAII object to register a special member as being currently declared. 10919 struct DeclaringSpecialMember { 10920 Sema &S; 10921 Sema::SpecialMemberDecl D; 10922 Sema::ContextRAII SavedContext; 10923 bool WasAlreadyBeingDeclared; 10924 10925 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10926 : S(S), D(RD, CSM), SavedContext(S, RD) { 10927 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10928 if (WasAlreadyBeingDeclared) 10929 // This almost never happens, but if it does, ensure that our cache 10930 // doesn't contain a stale result. 10931 S.SpecialMemberCache.clear(); 10932 else { 10933 // Register a note to be produced if we encounter an error while 10934 // declaring the special member. 10935 Sema::CodeSynthesisContext Ctx; 10936 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10937 // FIXME: We don't have a location to use here. Using the class's 10938 // location maintains the fiction that we declare all special members 10939 // with the class, but (1) it's not clear that lying about that helps our 10940 // users understand what's going on, and (2) there may be outer contexts 10941 // on the stack (some of which are relevant) and printing them exposes 10942 // our lies. 10943 Ctx.PointOfInstantiation = RD->getLocation(); 10944 Ctx.Entity = RD; 10945 Ctx.SpecialMember = CSM; 10946 S.pushCodeSynthesisContext(Ctx); 10947 } 10948 } 10949 ~DeclaringSpecialMember() { 10950 if (!WasAlreadyBeingDeclared) { 10951 S.SpecialMembersBeingDeclared.erase(D); 10952 S.popCodeSynthesisContext(); 10953 } 10954 } 10955 10956 /// Are we already trying to declare this special member? 10957 bool isAlreadyBeingDeclared() const { 10958 return WasAlreadyBeingDeclared; 10959 } 10960 }; 10961 } 10962 10963 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10964 // Look up any existing declarations, but don't trigger declaration of all 10965 // implicit special members with this name. 10966 DeclarationName Name = FD->getDeclName(); 10967 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10968 ForExternalRedeclaration); 10969 for (auto *D : FD->getParent()->lookup(Name)) 10970 if (auto *Acceptable = R.getAcceptableDecl(D)) 10971 R.addDecl(Acceptable); 10972 R.resolveKind(); 10973 R.suppressDiagnostics(); 10974 10975 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10976 } 10977 10978 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 10979 QualType ResultTy, 10980 ArrayRef<QualType> Args) { 10981 // Build an exception specification pointing back at this constructor. 10982 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 10983 10984 if (getLangOpts().OpenCLCPlusPlus) { 10985 // OpenCL: Implicitly defaulted special member are of the generic address 10986 // space. 10987 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic); 10988 } 10989 10990 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 10991 SpecialMem->setType(QT); 10992 } 10993 10994 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10995 CXXRecordDecl *ClassDecl) { 10996 // C++ [class.ctor]p5: 10997 // A default constructor for a class X is a constructor of class X 10998 // that can be called without an argument. If there is no 10999 // user-declared constructor for class X, a default constructor is 11000 // implicitly declared. An implicitly-declared default constructor 11001 // is an inline public member of its class. 11002 assert(ClassDecl->needsImplicitDefaultConstructor() && 11003 "Should not build implicit default constructor!"); 11004 11005 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 11006 if (DSM.isAlreadyBeingDeclared()) 11007 return nullptr; 11008 11009 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11010 CXXDefaultConstructor, 11011 false); 11012 11013 // Create the actual constructor declaration. 11014 CanQualType ClassType 11015 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11016 SourceLocation ClassLoc = ClassDecl->getLocation(); 11017 DeclarationName Name 11018 = Context.DeclarationNames.getCXXConstructorName(ClassType); 11019 DeclarationNameInfo NameInfo(Name, ClassLoc); 11020 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 11021 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 11022 /*TInfo=*/nullptr, ExplicitSpecifier(), 11023 /*isInline=*/true, /*isImplicitlyDeclared=*/true, Constexpr); 11024 DefaultCon->setAccess(AS_public); 11025 DefaultCon->setDefaulted(); 11026 11027 if (getLangOpts().CUDA) { 11028 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 11029 DefaultCon, 11030 /* ConstRHS */ false, 11031 /* Diagnose */ false); 11032 } 11033 11034 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 11035 11036 // We don't need to use SpecialMemberIsTrivial here; triviality for default 11037 // constructors is easy to compute. 11038 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 11039 11040 // Note that we have declared this constructor. 11041 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 11042 11043 Scope *S = getScopeForContext(ClassDecl); 11044 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 11045 11046 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 11047 SetDeclDeleted(DefaultCon, ClassLoc); 11048 11049 if (S) 11050 PushOnScopeChains(DefaultCon, S, false); 11051 ClassDecl->addDecl(DefaultCon); 11052 11053 return DefaultCon; 11054 } 11055 11056 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 11057 CXXConstructorDecl *Constructor) { 11058 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 11059 !Constructor->doesThisDeclarationHaveABody() && 11060 !Constructor->isDeleted()) && 11061 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 11062 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11063 return; 11064 11065 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11066 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 11067 11068 SynthesizedFunctionScope Scope(*this, Constructor); 11069 11070 // The exception specification is needed because we are defining the 11071 // function. 11072 ResolveExceptionSpec(CurrentLocation, 11073 Constructor->getType()->castAs<FunctionProtoType>()); 11074 MarkVTableUsed(CurrentLocation, ClassDecl); 11075 11076 // Add a context note for diagnostics produced after this point. 11077 Scope.addContextNote(CurrentLocation); 11078 11079 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 11080 Constructor->setInvalidDecl(); 11081 return; 11082 } 11083 11084 SourceLocation Loc = Constructor->getEndLoc().isValid() 11085 ? Constructor->getEndLoc() 11086 : Constructor->getLocation(); 11087 Constructor->setBody(new (Context) CompoundStmt(Loc)); 11088 Constructor->markUsed(Context); 11089 11090 if (ASTMutationListener *L = getASTMutationListener()) { 11091 L->CompletedImplicitDefinition(Constructor); 11092 } 11093 11094 DiagnoseUninitializedFields(*this, Constructor); 11095 } 11096 11097 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 11098 // Perform any delayed checks on exception specifications. 11099 CheckDelayedMemberExceptionSpecs(); 11100 } 11101 11102 /// Find or create the fake constructor we synthesize to model constructing an 11103 /// object of a derived class via a constructor of a base class. 11104 CXXConstructorDecl * 11105 Sema::findInheritingConstructor(SourceLocation Loc, 11106 CXXConstructorDecl *BaseCtor, 11107 ConstructorUsingShadowDecl *Shadow) { 11108 CXXRecordDecl *Derived = Shadow->getParent(); 11109 SourceLocation UsingLoc = Shadow->getLocation(); 11110 11111 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 11112 // For now we use the name of the base class constructor as a member of the 11113 // derived class to indicate a (fake) inherited constructor name. 11114 DeclarationName Name = BaseCtor->getDeclName(); 11115 11116 // Check to see if we already have a fake constructor for this inherited 11117 // constructor call. 11118 for (NamedDecl *Ctor : Derived->lookup(Name)) 11119 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 11120 ->getInheritedConstructor() 11121 .getConstructor(), 11122 BaseCtor)) 11123 return cast<CXXConstructorDecl>(Ctor); 11124 11125 DeclarationNameInfo NameInfo(Name, UsingLoc); 11126 TypeSourceInfo *TInfo = 11127 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 11128 FunctionProtoTypeLoc ProtoLoc = 11129 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 11130 11131 // Check the inherited constructor is valid and find the list of base classes 11132 // from which it was inherited. 11133 InheritedConstructorInfo ICI(*this, Loc, Shadow); 11134 11135 bool Constexpr = 11136 BaseCtor->isConstexpr() && 11137 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 11138 false, BaseCtor, &ICI); 11139 11140 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 11141 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 11142 BaseCtor->getExplicitSpecifier(), /*Inline=*/true, 11143 /*ImplicitlyDeclared=*/true, Constexpr, 11144 InheritedConstructor(Shadow, BaseCtor)); 11145 if (Shadow->isInvalidDecl()) 11146 DerivedCtor->setInvalidDecl(); 11147 11148 // Build an unevaluated exception specification for this fake constructor. 11149 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 11150 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11151 EPI.ExceptionSpec.Type = EST_Unevaluated; 11152 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 11153 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 11154 FPT->getParamTypes(), EPI)); 11155 11156 // Build the parameter declarations. 11157 SmallVector<ParmVarDecl *, 16> ParamDecls; 11158 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 11159 TypeSourceInfo *TInfo = 11160 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 11161 ParmVarDecl *PD = ParmVarDecl::Create( 11162 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 11163 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 11164 PD->setScopeInfo(0, I); 11165 PD->setImplicit(); 11166 // Ensure attributes are propagated onto parameters (this matters for 11167 // format, pass_object_size, ...). 11168 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 11169 ParamDecls.push_back(PD); 11170 ProtoLoc.setParam(I, PD); 11171 } 11172 11173 // Set up the new constructor. 11174 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 11175 DerivedCtor->setAccess(BaseCtor->getAccess()); 11176 DerivedCtor->setParams(ParamDecls); 11177 Derived->addDecl(DerivedCtor); 11178 11179 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 11180 SetDeclDeleted(DerivedCtor, UsingLoc); 11181 11182 return DerivedCtor; 11183 } 11184 11185 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 11186 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 11187 Ctor->getInheritedConstructor().getShadowDecl()); 11188 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 11189 /*Diagnose*/true); 11190 } 11191 11192 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 11193 CXXConstructorDecl *Constructor) { 11194 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11195 assert(Constructor->getInheritedConstructor() && 11196 !Constructor->doesThisDeclarationHaveABody() && 11197 !Constructor->isDeleted()); 11198 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11199 return; 11200 11201 // Initializations are performed "as if by a defaulted default constructor", 11202 // so enter the appropriate scope. 11203 SynthesizedFunctionScope Scope(*this, Constructor); 11204 11205 // The exception specification is needed because we are defining the 11206 // function. 11207 ResolveExceptionSpec(CurrentLocation, 11208 Constructor->getType()->castAs<FunctionProtoType>()); 11209 MarkVTableUsed(CurrentLocation, ClassDecl); 11210 11211 // Add a context note for diagnostics produced after this point. 11212 Scope.addContextNote(CurrentLocation); 11213 11214 ConstructorUsingShadowDecl *Shadow = 11215 Constructor->getInheritedConstructor().getShadowDecl(); 11216 CXXConstructorDecl *InheritedCtor = 11217 Constructor->getInheritedConstructor().getConstructor(); 11218 11219 // [class.inhctor.init]p1: 11220 // initialization proceeds as if a defaulted default constructor is used to 11221 // initialize the D object and each base class subobject from which the 11222 // constructor was inherited 11223 11224 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11225 CXXRecordDecl *RD = Shadow->getParent(); 11226 SourceLocation InitLoc = Shadow->getLocation(); 11227 11228 // Build explicit initializers for all base classes from which the 11229 // constructor was inherited. 11230 SmallVector<CXXCtorInitializer*, 8> Inits; 11231 for (bool VBase : {false, true}) { 11232 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11233 if (B.isVirtual() != VBase) 11234 continue; 11235 11236 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11237 if (!BaseRD) 11238 continue; 11239 11240 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11241 if (!BaseCtor.first) 11242 continue; 11243 11244 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11245 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11246 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11247 11248 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11249 Inits.push_back(new (Context) CXXCtorInitializer( 11250 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11251 SourceLocation())); 11252 } 11253 } 11254 11255 // We now proceed as if for a defaulted default constructor, with the relevant 11256 // initializers replaced. 11257 11258 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11259 Constructor->setInvalidDecl(); 11260 return; 11261 } 11262 11263 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11264 Constructor->markUsed(Context); 11265 11266 if (ASTMutationListener *L = getASTMutationListener()) { 11267 L->CompletedImplicitDefinition(Constructor); 11268 } 11269 11270 DiagnoseUninitializedFields(*this, Constructor); 11271 } 11272 11273 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11274 // C++ [class.dtor]p2: 11275 // If a class has no user-declared destructor, a destructor is 11276 // declared implicitly. An implicitly-declared destructor is an 11277 // inline public member of its class. 11278 assert(ClassDecl->needsImplicitDestructor()); 11279 11280 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11281 if (DSM.isAlreadyBeingDeclared()) 11282 return nullptr; 11283 11284 // Create the actual destructor declaration. 11285 CanQualType ClassType 11286 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11287 SourceLocation ClassLoc = ClassDecl->getLocation(); 11288 DeclarationName Name 11289 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11290 DeclarationNameInfo NameInfo(Name, ClassLoc); 11291 CXXDestructorDecl *Destructor 11292 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11293 QualType(), nullptr, /*isInline=*/true, 11294 /*isImplicitlyDeclared=*/true); 11295 Destructor->setAccess(AS_public); 11296 Destructor->setDefaulted(); 11297 11298 if (getLangOpts().CUDA) { 11299 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11300 Destructor, 11301 /* ConstRHS */ false, 11302 /* Diagnose */ false); 11303 } 11304 11305 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 11306 11307 // We don't need to use SpecialMemberIsTrivial here; triviality for 11308 // destructors is easy to compute. 11309 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11310 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11311 ClassDecl->hasTrivialDestructorForCall()); 11312 11313 // Note that we have declared this destructor. 11314 ++getASTContext().NumImplicitDestructorsDeclared; 11315 11316 Scope *S = getScopeForContext(ClassDecl); 11317 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11318 11319 // We can't check whether an implicit destructor is deleted before we complete 11320 // the definition of the class, because its validity depends on the alignment 11321 // of the class. We'll check this from ActOnFields once the class is complete. 11322 if (ClassDecl->isCompleteDefinition() && 11323 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11324 SetDeclDeleted(Destructor, ClassLoc); 11325 11326 // Introduce this destructor into its scope. 11327 if (S) 11328 PushOnScopeChains(Destructor, S, false); 11329 ClassDecl->addDecl(Destructor); 11330 11331 return Destructor; 11332 } 11333 11334 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11335 CXXDestructorDecl *Destructor) { 11336 assert((Destructor->isDefaulted() && 11337 !Destructor->doesThisDeclarationHaveABody() && 11338 !Destructor->isDeleted()) && 11339 "DefineImplicitDestructor - call it for implicit default dtor"); 11340 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11341 return; 11342 11343 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11344 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11345 11346 SynthesizedFunctionScope Scope(*this, Destructor); 11347 11348 // The exception specification is needed because we are defining the 11349 // function. 11350 ResolveExceptionSpec(CurrentLocation, 11351 Destructor->getType()->castAs<FunctionProtoType>()); 11352 MarkVTableUsed(CurrentLocation, ClassDecl); 11353 11354 // Add a context note for diagnostics produced after this point. 11355 Scope.addContextNote(CurrentLocation); 11356 11357 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11358 Destructor->getParent()); 11359 11360 if (CheckDestructor(Destructor)) { 11361 Destructor->setInvalidDecl(); 11362 return; 11363 } 11364 11365 SourceLocation Loc = Destructor->getEndLoc().isValid() 11366 ? Destructor->getEndLoc() 11367 : Destructor->getLocation(); 11368 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11369 Destructor->markUsed(Context); 11370 11371 if (ASTMutationListener *L = getASTMutationListener()) { 11372 L->CompletedImplicitDefinition(Destructor); 11373 } 11374 } 11375 11376 /// Perform any semantic analysis which needs to be delayed until all 11377 /// pending class member declarations have been parsed. 11378 void Sema::ActOnFinishCXXMemberDecls() { 11379 // If the context is an invalid C++ class, just suppress these checks. 11380 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11381 if (Record->isInvalidDecl()) { 11382 DelayedOverridingExceptionSpecChecks.clear(); 11383 DelayedEquivalentExceptionSpecChecks.clear(); 11384 return; 11385 } 11386 checkForMultipleExportedDefaultConstructors(*this, Record); 11387 } 11388 } 11389 11390 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11391 referenceDLLExportedClassMethods(); 11392 } 11393 11394 void Sema::referenceDLLExportedClassMethods() { 11395 if (!DelayedDllExportClasses.empty()) { 11396 // Calling ReferenceDllExportedMembers might cause the current function to 11397 // be called again, so use a local copy of DelayedDllExportClasses. 11398 SmallVector<CXXRecordDecl *, 4> WorkList; 11399 std::swap(DelayedDllExportClasses, WorkList); 11400 for (CXXRecordDecl *Class : WorkList) 11401 ReferenceDllExportedMembers(*this, Class); 11402 } 11403 } 11404 11405 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 11406 assert(getLangOpts().CPlusPlus11 && 11407 "adjusting dtor exception specs was introduced in c++11"); 11408 11409 if (Destructor->isDependentContext()) 11410 return; 11411 11412 // C++11 [class.dtor]p3: 11413 // A declaration of a destructor that does not have an exception- 11414 // specification is implicitly considered to have the same exception- 11415 // specification as an implicit declaration. 11416 const FunctionProtoType *DtorType = Destructor->getType()-> 11417 getAs<FunctionProtoType>(); 11418 if (DtorType->hasExceptionSpec()) 11419 return; 11420 11421 // Replace the destructor's type, building off the existing one. Fortunately, 11422 // the only thing of interest in the destructor type is its extended info. 11423 // The return and arguments are fixed. 11424 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11425 EPI.ExceptionSpec.Type = EST_Unevaluated; 11426 EPI.ExceptionSpec.SourceDecl = Destructor; 11427 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11428 11429 // FIXME: If the destructor has a body that could throw, and the newly created 11430 // spec doesn't allow exceptions, we should emit a warning, because this 11431 // change in behavior can break conforming C++03 programs at runtime. 11432 // However, we don't have a body or an exception specification yet, so it 11433 // needs to be done somewhere else. 11434 } 11435 11436 namespace { 11437 /// An abstract base class for all helper classes used in building the 11438 // copy/move operators. These classes serve as factory functions and help us 11439 // avoid using the same Expr* in the AST twice. 11440 class ExprBuilder { 11441 ExprBuilder(const ExprBuilder&) = delete; 11442 ExprBuilder &operator=(const ExprBuilder&) = delete; 11443 11444 protected: 11445 static Expr *assertNotNull(Expr *E) { 11446 assert(E && "Expression construction must not fail."); 11447 return E; 11448 } 11449 11450 public: 11451 ExprBuilder() {} 11452 virtual ~ExprBuilder() {} 11453 11454 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11455 }; 11456 11457 class RefBuilder: public ExprBuilder { 11458 VarDecl *Var; 11459 QualType VarType; 11460 11461 public: 11462 Expr *build(Sema &S, SourceLocation Loc) const override { 11463 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 11464 } 11465 11466 RefBuilder(VarDecl *Var, QualType VarType) 11467 : Var(Var), VarType(VarType) {} 11468 }; 11469 11470 class ThisBuilder: public ExprBuilder { 11471 public: 11472 Expr *build(Sema &S, SourceLocation Loc) const override { 11473 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11474 } 11475 }; 11476 11477 class CastBuilder: public ExprBuilder { 11478 const ExprBuilder &Builder; 11479 QualType Type; 11480 ExprValueKind Kind; 11481 const CXXCastPath &Path; 11482 11483 public: 11484 Expr *build(Sema &S, SourceLocation Loc) const override { 11485 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11486 CK_UncheckedDerivedToBase, Kind, 11487 &Path).get()); 11488 } 11489 11490 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11491 const CXXCastPath &Path) 11492 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11493 }; 11494 11495 class DerefBuilder: public ExprBuilder { 11496 const ExprBuilder &Builder; 11497 11498 public: 11499 Expr *build(Sema &S, SourceLocation Loc) const override { 11500 return assertNotNull( 11501 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11502 } 11503 11504 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11505 }; 11506 11507 class MemberBuilder: public ExprBuilder { 11508 const ExprBuilder &Builder; 11509 QualType Type; 11510 CXXScopeSpec SS; 11511 bool IsArrow; 11512 LookupResult &MemberLookup; 11513 11514 public: 11515 Expr *build(Sema &S, SourceLocation Loc) const override { 11516 return assertNotNull(S.BuildMemberReferenceExpr( 11517 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11518 nullptr, MemberLookup, nullptr, nullptr).get()); 11519 } 11520 11521 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11522 LookupResult &MemberLookup) 11523 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11524 MemberLookup(MemberLookup) {} 11525 }; 11526 11527 class MoveCastBuilder: public ExprBuilder { 11528 const ExprBuilder &Builder; 11529 11530 public: 11531 Expr *build(Sema &S, SourceLocation Loc) const override { 11532 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11533 } 11534 11535 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11536 }; 11537 11538 class LvalueConvBuilder: public ExprBuilder { 11539 const ExprBuilder &Builder; 11540 11541 public: 11542 Expr *build(Sema &S, SourceLocation Loc) const override { 11543 return assertNotNull( 11544 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11545 } 11546 11547 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11548 }; 11549 11550 class SubscriptBuilder: public ExprBuilder { 11551 const ExprBuilder &Base; 11552 const ExprBuilder &Index; 11553 11554 public: 11555 Expr *build(Sema &S, SourceLocation Loc) const override { 11556 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11557 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11558 } 11559 11560 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11561 : Base(Base), Index(Index) {} 11562 }; 11563 11564 } // end anonymous namespace 11565 11566 /// When generating a defaulted copy or move assignment operator, if a field 11567 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11568 /// do so. This optimization only applies for arrays of scalars, and for arrays 11569 /// of class type where the selected copy/move-assignment operator is trivial. 11570 static StmtResult 11571 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11572 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11573 // Compute the size of the memory buffer to be copied. 11574 QualType SizeType = S.Context.getSizeType(); 11575 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11576 S.Context.getTypeSizeInChars(T).getQuantity()); 11577 11578 // Take the address of the field references for "from" and "to". We 11579 // directly construct UnaryOperators here because semantic analysis 11580 // does not permit us to take the address of an xvalue. 11581 Expr *From = FromB.build(S, Loc); 11582 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11583 S.Context.getPointerType(From->getType()), 11584 VK_RValue, OK_Ordinary, Loc, false); 11585 Expr *To = ToB.build(S, Loc); 11586 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11587 S.Context.getPointerType(To->getType()), 11588 VK_RValue, OK_Ordinary, Loc, false); 11589 11590 const Type *E = T->getBaseElementTypeUnsafe(); 11591 bool NeedsCollectableMemCpy = 11592 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11593 11594 // Create a reference to the __builtin_objc_memmove_collectable function 11595 StringRef MemCpyName = NeedsCollectableMemCpy ? 11596 "__builtin_objc_memmove_collectable" : 11597 "__builtin_memcpy"; 11598 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11599 Sema::LookupOrdinaryName); 11600 S.LookupName(R, S.TUScope, true); 11601 11602 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11603 if (!MemCpy) 11604 // Something went horribly wrong earlier, and we will have complained 11605 // about it. 11606 return StmtError(); 11607 11608 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11609 VK_RValue, Loc, nullptr); 11610 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11611 11612 Expr *CallArgs[] = { 11613 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11614 }; 11615 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11616 Loc, CallArgs, Loc); 11617 11618 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11619 return Call.getAs<Stmt>(); 11620 } 11621 11622 /// Builds a statement that copies/moves the given entity from \p From to 11623 /// \c To. 11624 /// 11625 /// This routine is used to copy/move the members of a class with an 11626 /// implicitly-declared copy/move assignment operator. When the entities being 11627 /// copied are arrays, this routine builds for loops to copy them. 11628 /// 11629 /// \param S The Sema object used for type-checking. 11630 /// 11631 /// \param Loc The location where the implicit copy/move is being generated. 11632 /// 11633 /// \param T The type of the expressions being copied/moved. Both expressions 11634 /// must have this type. 11635 /// 11636 /// \param To The expression we are copying/moving to. 11637 /// 11638 /// \param From The expression we are copying/moving from. 11639 /// 11640 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11641 /// Otherwise, it's a non-static member subobject. 11642 /// 11643 /// \param Copying Whether we're copying or moving. 11644 /// 11645 /// \param Depth Internal parameter recording the depth of the recursion. 11646 /// 11647 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11648 /// if a memcpy should be used instead. 11649 static StmtResult 11650 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11651 const ExprBuilder &To, const ExprBuilder &From, 11652 bool CopyingBaseSubobject, bool Copying, 11653 unsigned Depth = 0) { 11654 // C++11 [class.copy]p28: 11655 // Each subobject is assigned in the manner appropriate to its type: 11656 // 11657 // - if the subobject is of class type, as if by a call to operator= with 11658 // the subobject as the object expression and the corresponding 11659 // subobject of x as a single function argument (as if by explicit 11660 // qualification; that is, ignoring any possible virtual overriding 11661 // functions in more derived classes); 11662 // 11663 // C++03 [class.copy]p13: 11664 // - if the subobject is of class type, the copy assignment operator for 11665 // the class is used (as if by explicit qualification; that is, 11666 // ignoring any possible virtual overriding functions in more derived 11667 // classes); 11668 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11669 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11670 11671 // Look for operator=. 11672 DeclarationName Name 11673 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11674 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11675 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11676 11677 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11678 // operator. 11679 if (!S.getLangOpts().CPlusPlus11) { 11680 LookupResult::Filter F = OpLookup.makeFilter(); 11681 while (F.hasNext()) { 11682 NamedDecl *D = F.next(); 11683 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11684 if (Method->isCopyAssignmentOperator() || 11685 (!Copying && Method->isMoveAssignmentOperator())) 11686 continue; 11687 11688 F.erase(); 11689 } 11690 F.done(); 11691 } 11692 11693 // Suppress the protected check (C++ [class.protected]) for each of the 11694 // assignment operators we found. This strange dance is required when 11695 // we're assigning via a base classes's copy-assignment operator. To 11696 // ensure that we're getting the right base class subobject (without 11697 // ambiguities), we need to cast "this" to that subobject type; to 11698 // ensure that we don't go through the virtual call mechanism, we need 11699 // to qualify the operator= name with the base class (see below). However, 11700 // this means that if the base class has a protected copy assignment 11701 // operator, the protected member access check will fail. So, we 11702 // rewrite "protected" access to "public" access in this case, since we 11703 // know by construction that we're calling from a derived class. 11704 if (CopyingBaseSubobject) { 11705 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11706 L != LEnd; ++L) { 11707 if (L.getAccess() == AS_protected) 11708 L.setAccess(AS_public); 11709 } 11710 } 11711 11712 // Create the nested-name-specifier that will be used to qualify the 11713 // reference to operator=; this is required to suppress the virtual 11714 // call mechanism. 11715 CXXScopeSpec SS; 11716 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11717 SS.MakeTrivial(S.Context, 11718 NestedNameSpecifier::Create(S.Context, nullptr, false, 11719 CanonicalT), 11720 Loc); 11721 11722 // Create the reference to operator=. 11723 ExprResult OpEqualRef 11724 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11725 SS, /*TemplateKWLoc=*/SourceLocation(), 11726 /*FirstQualifierInScope=*/nullptr, 11727 OpLookup, 11728 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11729 /*SuppressQualifierCheck=*/true); 11730 if (OpEqualRef.isInvalid()) 11731 return StmtError(); 11732 11733 // Build the call to the assignment operator. 11734 11735 Expr *FromInst = From.build(S, Loc); 11736 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11737 OpEqualRef.getAs<Expr>(), 11738 Loc, FromInst, Loc); 11739 if (Call.isInvalid()) 11740 return StmtError(); 11741 11742 // If we built a call to a trivial 'operator=' while copying an array, 11743 // bail out. We'll replace the whole shebang with a memcpy. 11744 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11745 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11746 return StmtResult((Stmt*)nullptr); 11747 11748 // Convert to an expression-statement, and clean up any produced 11749 // temporaries. 11750 return S.ActOnExprStmt(Call); 11751 } 11752 11753 // - if the subobject is of scalar type, the built-in assignment 11754 // operator is used. 11755 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11756 if (!ArrayTy) { 11757 ExprResult Assignment = S.CreateBuiltinBinOp( 11758 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11759 if (Assignment.isInvalid()) 11760 return StmtError(); 11761 return S.ActOnExprStmt(Assignment); 11762 } 11763 11764 // - if the subobject is an array, each element is assigned, in the 11765 // manner appropriate to the element type; 11766 11767 // Construct a loop over the array bounds, e.g., 11768 // 11769 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11770 // 11771 // that will copy each of the array elements. 11772 QualType SizeType = S.Context.getSizeType(); 11773 11774 // Create the iteration variable. 11775 IdentifierInfo *IterationVarName = nullptr; 11776 { 11777 SmallString<8> Str; 11778 llvm::raw_svector_ostream OS(Str); 11779 OS << "__i" << Depth; 11780 IterationVarName = &S.Context.Idents.get(OS.str()); 11781 } 11782 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11783 IterationVarName, SizeType, 11784 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11785 SC_None); 11786 11787 // Initialize the iteration variable to zero. 11788 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11789 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11790 11791 // Creates a reference to the iteration variable. 11792 RefBuilder IterationVarRef(IterationVar, SizeType); 11793 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11794 11795 // Create the DeclStmt that holds the iteration variable. 11796 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11797 11798 // Subscript the "from" and "to" expressions with the iteration variable. 11799 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11800 MoveCastBuilder FromIndexMove(FromIndexCopy); 11801 const ExprBuilder *FromIndex; 11802 if (Copying) 11803 FromIndex = &FromIndexCopy; 11804 else 11805 FromIndex = &FromIndexMove; 11806 11807 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11808 11809 // Build the copy/move for an individual element of the array. 11810 StmtResult Copy = 11811 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11812 ToIndex, *FromIndex, CopyingBaseSubobject, 11813 Copying, Depth + 1); 11814 // Bail out if copying fails or if we determined that we should use memcpy. 11815 if (Copy.isInvalid() || !Copy.get()) 11816 return Copy; 11817 11818 // Create the comparison against the array bound. 11819 llvm::APInt Upper 11820 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11821 Expr *Comparison 11822 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11823 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11824 BO_NE, S.Context.BoolTy, 11825 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11826 11827 // Create the pre-increment of the iteration variable. We can determine 11828 // whether the increment will overflow based on the value of the array 11829 // bound. 11830 Expr *Increment = new (S.Context) 11831 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11832 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11833 11834 // Construct the loop that copies all elements of this array. 11835 return S.ActOnForStmt( 11836 Loc, Loc, InitStmt, 11837 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11838 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11839 } 11840 11841 static StmtResult 11842 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11843 const ExprBuilder &To, const ExprBuilder &From, 11844 bool CopyingBaseSubobject, bool Copying) { 11845 // Maybe we should use a memcpy? 11846 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11847 T.isTriviallyCopyableType(S.Context)) 11848 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11849 11850 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11851 CopyingBaseSubobject, 11852 Copying, 0)); 11853 11854 // If we ended up picking a trivial assignment operator for an array of a 11855 // non-trivially-copyable class type, just emit a memcpy. 11856 if (!Result.isInvalid() && !Result.get()) 11857 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11858 11859 return Result; 11860 } 11861 11862 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11863 // Note: The following rules are largely analoguous to the copy 11864 // constructor rules. Note that virtual bases are not taken into account 11865 // for determining the argument type of the operator. Note also that 11866 // operators taking an object instead of a reference are allowed. 11867 assert(ClassDecl->needsImplicitCopyAssignment()); 11868 11869 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11870 if (DSM.isAlreadyBeingDeclared()) 11871 return nullptr; 11872 11873 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11874 if (Context.getLangOpts().OpenCLCPlusPlus) 11875 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 11876 QualType RetType = Context.getLValueReferenceType(ArgType); 11877 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11878 if (Const) 11879 ArgType = ArgType.withConst(); 11880 11881 ArgType = Context.getLValueReferenceType(ArgType); 11882 11883 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11884 CXXCopyAssignment, 11885 Const); 11886 11887 // An implicitly-declared copy assignment operator is an inline public 11888 // member of its class. 11889 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11890 SourceLocation ClassLoc = ClassDecl->getLocation(); 11891 DeclarationNameInfo NameInfo(Name, ClassLoc); 11892 CXXMethodDecl *CopyAssignment = 11893 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11894 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11895 /*isInline=*/true, Constexpr, SourceLocation()); 11896 CopyAssignment->setAccess(AS_public); 11897 CopyAssignment->setDefaulted(); 11898 CopyAssignment->setImplicit(); 11899 11900 if (getLangOpts().CUDA) { 11901 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11902 CopyAssignment, 11903 /* ConstRHS */ Const, 11904 /* Diagnose */ false); 11905 } 11906 11907 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 11908 11909 // Add the parameter to the operator. 11910 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11911 ClassLoc, ClassLoc, 11912 /*Id=*/nullptr, ArgType, 11913 /*TInfo=*/nullptr, SC_None, 11914 nullptr); 11915 CopyAssignment->setParams(FromParam); 11916 11917 CopyAssignment->setTrivial( 11918 ClassDecl->needsOverloadResolutionForCopyAssignment() 11919 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11920 : ClassDecl->hasTrivialCopyAssignment()); 11921 11922 // Note that we have added this copy-assignment operator. 11923 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 11924 11925 Scope *S = getScopeForContext(ClassDecl); 11926 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11927 11928 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11929 SetDeclDeleted(CopyAssignment, ClassLoc); 11930 11931 if (S) 11932 PushOnScopeChains(CopyAssignment, S, false); 11933 ClassDecl->addDecl(CopyAssignment); 11934 11935 return CopyAssignment; 11936 } 11937 11938 /// Diagnose an implicit copy operation for a class which is odr-used, but 11939 /// which is deprecated because the class has a user-declared copy constructor, 11940 /// copy assignment operator, or destructor. 11941 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11942 assert(CopyOp->isImplicit()); 11943 11944 CXXRecordDecl *RD = CopyOp->getParent(); 11945 CXXMethodDecl *UserDeclaredOperation = nullptr; 11946 11947 // In Microsoft mode, assignment operations don't affect constructors and 11948 // vice versa. 11949 if (RD->hasUserDeclaredDestructor()) { 11950 UserDeclaredOperation = RD->getDestructor(); 11951 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11952 RD->hasUserDeclaredCopyConstructor() && 11953 !S.getLangOpts().MSVCCompat) { 11954 // Find any user-declared copy constructor. 11955 for (auto *I : RD->ctors()) { 11956 if (I->isCopyConstructor()) { 11957 UserDeclaredOperation = I; 11958 break; 11959 } 11960 } 11961 assert(UserDeclaredOperation); 11962 } else if (isa<CXXConstructorDecl>(CopyOp) && 11963 RD->hasUserDeclaredCopyAssignment() && 11964 !S.getLangOpts().MSVCCompat) { 11965 // Find any user-declared move assignment operator. 11966 for (auto *I : RD->methods()) { 11967 if (I->isCopyAssignmentOperator()) { 11968 UserDeclaredOperation = I; 11969 break; 11970 } 11971 } 11972 assert(UserDeclaredOperation); 11973 } 11974 11975 if (UserDeclaredOperation) { 11976 S.Diag(UserDeclaredOperation->getLocation(), 11977 diag::warn_deprecated_copy_operation) 11978 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11979 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11980 } 11981 } 11982 11983 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11984 CXXMethodDecl *CopyAssignOperator) { 11985 assert((CopyAssignOperator->isDefaulted() && 11986 CopyAssignOperator->isOverloadedOperator() && 11987 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11988 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11989 !CopyAssignOperator->isDeleted()) && 11990 "DefineImplicitCopyAssignment called for wrong function"); 11991 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11992 return; 11993 11994 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11995 if (ClassDecl->isInvalidDecl()) { 11996 CopyAssignOperator->setInvalidDecl(); 11997 return; 11998 } 11999 12000 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 12001 12002 // The exception specification is needed because we are defining the 12003 // function. 12004 ResolveExceptionSpec(CurrentLocation, 12005 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 12006 12007 // Add a context note for diagnostics produced after this point. 12008 Scope.addContextNote(CurrentLocation); 12009 12010 // C++11 [class.copy]p18: 12011 // The [definition of an implicitly declared copy assignment operator] is 12012 // deprecated if the class has a user-declared copy constructor or a 12013 // user-declared destructor. 12014 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 12015 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 12016 12017 // C++0x [class.copy]p30: 12018 // The implicitly-defined or explicitly-defaulted copy assignment operator 12019 // for a non-union class X performs memberwise copy assignment of its 12020 // subobjects. The direct base classes of X are assigned first, in the 12021 // order of their declaration in the base-specifier-list, and then the 12022 // immediate non-static data members of X are assigned, in the order in 12023 // which they were declared in the class definition. 12024 12025 // The statements that form the synthesized function body. 12026 SmallVector<Stmt*, 8> Statements; 12027 12028 // The parameter for the "other" object, which we are copying from. 12029 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 12030 Qualifiers OtherQuals = Other->getType().getQualifiers(); 12031 QualType OtherRefType = Other->getType(); 12032 if (const LValueReferenceType *OtherRef 12033 = OtherRefType->getAs<LValueReferenceType>()) { 12034 OtherRefType = OtherRef->getPointeeType(); 12035 OtherQuals = OtherRefType.getQualifiers(); 12036 } 12037 12038 // Our location for everything implicitly-generated. 12039 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 12040 ? CopyAssignOperator->getEndLoc() 12041 : CopyAssignOperator->getLocation(); 12042 12043 // Builds a DeclRefExpr for the "other" object. 12044 RefBuilder OtherRef(Other, OtherRefType); 12045 12046 // Builds the "this" pointer. 12047 ThisBuilder This; 12048 12049 // Assign base classes. 12050 bool Invalid = false; 12051 for (auto &Base : ClassDecl->bases()) { 12052 // Form the assignment: 12053 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 12054 QualType BaseType = Base.getType().getUnqualifiedType(); 12055 if (!BaseType->isRecordType()) { 12056 Invalid = true; 12057 continue; 12058 } 12059 12060 CXXCastPath BasePath; 12061 BasePath.push_back(&Base); 12062 12063 // Construct the "from" expression, which is an implicit cast to the 12064 // appropriately-qualified base type. 12065 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 12066 VK_LValue, BasePath); 12067 12068 // Dereference "this". 12069 DerefBuilder DerefThis(This); 12070 CastBuilder To(DerefThis, 12071 Context.getQualifiedType( 12072 BaseType, CopyAssignOperator->getMethodQualifiers()), 12073 VK_LValue, BasePath); 12074 12075 // Build the copy. 12076 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 12077 To, From, 12078 /*CopyingBaseSubobject=*/true, 12079 /*Copying=*/true); 12080 if (Copy.isInvalid()) { 12081 CopyAssignOperator->setInvalidDecl(); 12082 return; 12083 } 12084 12085 // Success! Record the copy. 12086 Statements.push_back(Copy.getAs<Expr>()); 12087 } 12088 12089 // Assign non-static members. 12090 for (auto *Field : ClassDecl->fields()) { 12091 // FIXME: We should form some kind of AST representation for the implied 12092 // memcpy in a union copy operation. 12093 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12094 continue; 12095 12096 if (Field->isInvalidDecl()) { 12097 Invalid = true; 12098 continue; 12099 } 12100 12101 // Check for members of reference type; we can't copy those. 12102 if (Field->getType()->isReferenceType()) { 12103 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12104 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12105 Diag(Field->getLocation(), diag::note_declared_at); 12106 Invalid = true; 12107 continue; 12108 } 12109 12110 // Check for members of const-qualified, non-class type. 12111 QualType BaseType = Context.getBaseElementType(Field->getType()); 12112 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12113 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12114 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12115 Diag(Field->getLocation(), diag::note_declared_at); 12116 Invalid = true; 12117 continue; 12118 } 12119 12120 // Suppress assigning zero-width bitfields. 12121 if (Field->isZeroLengthBitField(Context)) 12122 continue; 12123 12124 QualType FieldType = Field->getType().getNonReferenceType(); 12125 if (FieldType->isIncompleteArrayType()) { 12126 assert(ClassDecl->hasFlexibleArrayMember() && 12127 "Incomplete array type is not valid"); 12128 continue; 12129 } 12130 12131 // Build references to the field in the object we're copying from and to. 12132 CXXScopeSpec SS; // Intentionally empty 12133 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12134 LookupMemberName); 12135 MemberLookup.addDecl(Field); 12136 MemberLookup.resolveKind(); 12137 12138 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 12139 12140 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 12141 12142 // Build the copy of this field. 12143 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 12144 To, From, 12145 /*CopyingBaseSubobject=*/false, 12146 /*Copying=*/true); 12147 if (Copy.isInvalid()) { 12148 CopyAssignOperator->setInvalidDecl(); 12149 return; 12150 } 12151 12152 // Success! Record the copy. 12153 Statements.push_back(Copy.getAs<Stmt>()); 12154 } 12155 12156 if (!Invalid) { 12157 // Add a "return *this;" 12158 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12159 12160 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12161 if (Return.isInvalid()) 12162 Invalid = true; 12163 else 12164 Statements.push_back(Return.getAs<Stmt>()); 12165 } 12166 12167 if (Invalid) { 12168 CopyAssignOperator->setInvalidDecl(); 12169 return; 12170 } 12171 12172 StmtResult Body; 12173 { 12174 CompoundScopeRAII CompoundScope(*this); 12175 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12176 /*isStmtExpr=*/false); 12177 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12178 } 12179 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 12180 CopyAssignOperator->markUsed(Context); 12181 12182 if (ASTMutationListener *L = getASTMutationListener()) { 12183 L->CompletedImplicitDefinition(CopyAssignOperator); 12184 } 12185 } 12186 12187 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 12188 assert(ClassDecl->needsImplicitMoveAssignment()); 12189 12190 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 12191 if (DSM.isAlreadyBeingDeclared()) 12192 return nullptr; 12193 12194 // Note: The following rules are largely analoguous to the move 12195 // constructor rules. 12196 12197 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12198 if (Context.getLangOpts().OpenCLCPlusPlus) 12199 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12200 QualType RetType = Context.getLValueReferenceType(ArgType); 12201 ArgType = Context.getRValueReferenceType(ArgType); 12202 12203 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12204 CXXMoveAssignment, 12205 false); 12206 12207 // An implicitly-declared move assignment operator is an inline public 12208 // member of its class. 12209 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12210 SourceLocation ClassLoc = ClassDecl->getLocation(); 12211 DeclarationNameInfo NameInfo(Name, ClassLoc); 12212 CXXMethodDecl *MoveAssignment = 12213 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12214 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12215 /*isInline=*/true, Constexpr, SourceLocation()); 12216 MoveAssignment->setAccess(AS_public); 12217 MoveAssignment->setDefaulted(); 12218 MoveAssignment->setImplicit(); 12219 12220 if (getLangOpts().CUDA) { 12221 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12222 MoveAssignment, 12223 /* ConstRHS */ false, 12224 /* Diagnose */ false); 12225 } 12226 12227 // Build an exception specification pointing back at this member. 12228 FunctionProtoType::ExtProtoInfo EPI = 12229 getImplicitMethodEPI(*this, MoveAssignment); 12230 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12231 12232 // Add the parameter to the operator. 12233 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12234 ClassLoc, ClassLoc, 12235 /*Id=*/nullptr, ArgType, 12236 /*TInfo=*/nullptr, SC_None, 12237 nullptr); 12238 MoveAssignment->setParams(FromParam); 12239 12240 MoveAssignment->setTrivial( 12241 ClassDecl->needsOverloadResolutionForMoveAssignment() 12242 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12243 : ClassDecl->hasTrivialMoveAssignment()); 12244 12245 // Note that we have added this copy-assignment operator. 12246 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 12247 12248 Scope *S = getScopeForContext(ClassDecl); 12249 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12250 12251 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12252 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12253 SetDeclDeleted(MoveAssignment, ClassLoc); 12254 } 12255 12256 if (S) 12257 PushOnScopeChains(MoveAssignment, S, false); 12258 ClassDecl->addDecl(MoveAssignment); 12259 12260 return MoveAssignment; 12261 } 12262 12263 /// Check if we're implicitly defining a move assignment operator for a class 12264 /// with virtual bases. Such a move assignment might move-assign the virtual 12265 /// base multiple times. 12266 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12267 SourceLocation CurrentLocation) { 12268 assert(!Class->isDependentContext() && "should not define dependent move"); 12269 12270 // Only a virtual base could get implicitly move-assigned multiple times. 12271 // Only a non-trivial move assignment can observe this. We only want to 12272 // diagnose if we implicitly define an assignment operator that assigns 12273 // two base classes, both of which move-assign the same virtual base. 12274 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12275 Class->getNumBases() < 2) 12276 return; 12277 12278 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12279 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12280 VBaseMap VBases; 12281 12282 for (auto &BI : Class->bases()) { 12283 Worklist.push_back(&BI); 12284 while (!Worklist.empty()) { 12285 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12286 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12287 12288 // If the base has no non-trivial move assignment operators, 12289 // we don't care about moves from it. 12290 if (!Base->hasNonTrivialMoveAssignment()) 12291 continue; 12292 12293 // If there's nothing virtual here, skip it. 12294 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12295 continue; 12296 12297 // If we're not actually going to call a move assignment for this base, 12298 // or the selected move assignment is trivial, skip it. 12299 Sema::SpecialMemberOverloadResult SMOR = 12300 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12301 /*ConstArg*/false, /*VolatileArg*/false, 12302 /*RValueThis*/true, /*ConstThis*/false, 12303 /*VolatileThis*/false); 12304 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12305 !SMOR.getMethod()->isMoveAssignmentOperator()) 12306 continue; 12307 12308 if (BaseSpec->isVirtual()) { 12309 // We're going to move-assign this virtual base, and its move 12310 // assignment operator is not trivial. If this can happen for 12311 // multiple distinct direct bases of Class, diagnose it. (If it 12312 // only happens in one base, we'll diagnose it when synthesizing 12313 // that base class's move assignment operator.) 12314 CXXBaseSpecifier *&Existing = 12315 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12316 .first->second; 12317 if (Existing && Existing != &BI) { 12318 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12319 << Class << Base; 12320 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 12321 << (Base->getCanonicalDecl() == 12322 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12323 << Base << Existing->getType() << Existing->getSourceRange(); 12324 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 12325 << (Base->getCanonicalDecl() == 12326 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12327 << Base << BI.getType() << BaseSpec->getSourceRange(); 12328 12329 // Only diagnose each vbase once. 12330 Existing = nullptr; 12331 } 12332 } else { 12333 // Only walk over bases that have defaulted move assignment operators. 12334 // We assume that any user-provided move assignment operator handles 12335 // the multiple-moves-of-vbase case itself somehow. 12336 if (!SMOR.getMethod()->isDefaulted()) 12337 continue; 12338 12339 // We're going to move the base classes of Base. Add them to the list. 12340 for (auto &BI : Base->bases()) 12341 Worklist.push_back(&BI); 12342 } 12343 } 12344 } 12345 } 12346 12347 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12348 CXXMethodDecl *MoveAssignOperator) { 12349 assert((MoveAssignOperator->isDefaulted() && 12350 MoveAssignOperator->isOverloadedOperator() && 12351 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12352 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12353 !MoveAssignOperator->isDeleted()) && 12354 "DefineImplicitMoveAssignment called for wrong function"); 12355 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12356 return; 12357 12358 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12359 if (ClassDecl->isInvalidDecl()) { 12360 MoveAssignOperator->setInvalidDecl(); 12361 return; 12362 } 12363 12364 // C++0x [class.copy]p28: 12365 // The implicitly-defined or move assignment operator for a non-union class 12366 // X performs memberwise move assignment of its subobjects. The direct base 12367 // classes of X are assigned first, in the order of their declaration in the 12368 // base-specifier-list, and then the immediate non-static data members of X 12369 // are assigned, in the order in which they were declared in the class 12370 // definition. 12371 12372 // Issue a warning if our implicit move assignment operator will move 12373 // from a virtual base more than once. 12374 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12375 12376 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12377 12378 // The exception specification is needed because we are defining the 12379 // function. 12380 ResolveExceptionSpec(CurrentLocation, 12381 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12382 12383 // Add a context note for diagnostics produced after this point. 12384 Scope.addContextNote(CurrentLocation); 12385 12386 // The statements that form the synthesized function body. 12387 SmallVector<Stmt*, 8> Statements; 12388 12389 // The parameter for the "other" object, which we are move from. 12390 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12391 QualType OtherRefType = Other->getType()-> 12392 getAs<RValueReferenceType>()->getPointeeType(); 12393 12394 // Our location for everything implicitly-generated. 12395 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 12396 ? MoveAssignOperator->getEndLoc() 12397 : MoveAssignOperator->getLocation(); 12398 12399 // Builds a reference to the "other" object. 12400 RefBuilder OtherRef(Other, OtherRefType); 12401 // Cast to rvalue. 12402 MoveCastBuilder MoveOther(OtherRef); 12403 12404 // Builds the "this" pointer. 12405 ThisBuilder This; 12406 12407 // Assign base classes. 12408 bool Invalid = false; 12409 for (auto &Base : ClassDecl->bases()) { 12410 // C++11 [class.copy]p28: 12411 // It is unspecified whether subobjects representing virtual base classes 12412 // are assigned more than once by the implicitly-defined copy assignment 12413 // operator. 12414 // FIXME: Do not assign to a vbase that will be assigned by some other base 12415 // class. For a move-assignment, this can result in the vbase being moved 12416 // multiple times. 12417 12418 // Form the assignment: 12419 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12420 QualType BaseType = Base.getType().getUnqualifiedType(); 12421 if (!BaseType->isRecordType()) { 12422 Invalid = true; 12423 continue; 12424 } 12425 12426 CXXCastPath BasePath; 12427 BasePath.push_back(&Base); 12428 12429 // Construct the "from" expression, which is an implicit cast to the 12430 // appropriately-qualified base type. 12431 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12432 12433 // Dereference "this". 12434 DerefBuilder DerefThis(This); 12435 12436 // Implicitly cast "this" to the appropriately-qualified base type. 12437 CastBuilder To(DerefThis, 12438 Context.getQualifiedType( 12439 BaseType, MoveAssignOperator->getMethodQualifiers()), 12440 VK_LValue, BasePath); 12441 12442 // Build the move. 12443 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12444 To, From, 12445 /*CopyingBaseSubobject=*/true, 12446 /*Copying=*/false); 12447 if (Move.isInvalid()) { 12448 MoveAssignOperator->setInvalidDecl(); 12449 return; 12450 } 12451 12452 // Success! Record the move. 12453 Statements.push_back(Move.getAs<Expr>()); 12454 } 12455 12456 // Assign non-static members. 12457 for (auto *Field : ClassDecl->fields()) { 12458 // FIXME: We should form some kind of AST representation for the implied 12459 // memcpy in a union copy operation. 12460 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12461 continue; 12462 12463 if (Field->isInvalidDecl()) { 12464 Invalid = true; 12465 continue; 12466 } 12467 12468 // Check for members of reference type; we can't move those. 12469 if (Field->getType()->isReferenceType()) { 12470 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12471 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12472 Diag(Field->getLocation(), diag::note_declared_at); 12473 Invalid = true; 12474 continue; 12475 } 12476 12477 // Check for members of const-qualified, non-class type. 12478 QualType BaseType = Context.getBaseElementType(Field->getType()); 12479 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12480 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12481 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12482 Diag(Field->getLocation(), diag::note_declared_at); 12483 Invalid = true; 12484 continue; 12485 } 12486 12487 // Suppress assigning zero-width bitfields. 12488 if (Field->isZeroLengthBitField(Context)) 12489 continue; 12490 12491 QualType FieldType = Field->getType().getNonReferenceType(); 12492 if (FieldType->isIncompleteArrayType()) { 12493 assert(ClassDecl->hasFlexibleArrayMember() && 12494 "Incomplete array type is not valid"); 12495 continue; 12496 } 12497 12498 // Build references to the field in the object we're copying from and to. 12499 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12500 LookupMemberName); 12501 MemberLookup.addDecl(Field); 12502 MemberLookup.resolveKind(); 12503 MemberBuilder From(MoveOther, OtherRefType, 12504 /*IsArrow=*/false, MemberLookup); 12505 MemberBuilder To(This, getCurrentThisType(), 12506 /*IsArrow=*/true, MemberLookup); 12507 12508 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12509 "Member reference with rvalue base must be rvalue except for reference " 12510 "members, which aren't allowed for move assignment."); 12511 12512 // Build the move of this field. 12513 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12514 To, From, 12515 /*CopyingBaseSubobject=*/false, 12516 /*Copying=*/false); 12517 if (Move.isInvalid()) { 12518 MoveAssignOperator->setInvalidDecl(); 12519 return; 12520 } 12521 12522 // Success! Record the copy. 12523 Statements.push_back(Move.getAs<Stmt>()); 12524 } 12525 12526 if (!Invalid) { 12527 // Add a "return *this;" 12528 ExprResult ThisObj = 12529 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12530 12531 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12532 if (Return.isInvalid()) 12533 Invalid = true; 12534 else 12535 Statements.push_back(Return.getAs<Stmt>()); 12536 } 12537 12538 if (Invalid) { 12539 MoveAssignOperator->setInvalidDecl(); 12540 return; 12541 } 12542 12543 StmtResult Body; 12544 { 12545 CompoundScopeRAII CompoundScope(*this); 12546 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12547 /*isStmtExpr=*/false); 12548 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12549 } 12550 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12551 MoveAssignOperator->markUsed(Context); 12552 12553 if (ASTMutationListener *L = getASTMutationListener()) { 12554 L->CompletedImplicitDefinition(MoveAssignOperator); 12555 } 12556 } 12557 12558 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12559 CXXRecordDecl *ClassDecl) { 12560 // C++ [class.copy]p4: 12561 // If the class definition does not explicitly declare a copy 12562 // constructor, one is declared implicitly. 12563 assert(ClassDecl->needsImplicitCopyConstructor()); 12564 12565 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12566 if (DSM.isAlreadyBeingDeclared()) 12567 return nullptr; 12568 12569 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12570 QualType ArgType = ClassType; 12571 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12572 if (Const) 12573 ArgType = ArgType.withConst(); 12574 12575 if (Context.getLangOpts().OpenCLCPlusPlus) 12576 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12577 12578 ArgType = Context.getLValueReferenceType(ArgType); 12579 12580 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12581 CXXCopyConstructor, 12582 Const); 12583 12584 DeclarationName Name 12585 = Context.DeclarationNames.getCXXConstructorName( 12586 Context.getCanonicalType(ClassType)); 12587 SourceLocation ClassLoc = ClassDecl->getLocation(); 12588 DeclarationNameInfo NameInfo(Name, ClassLoc); 12589 12590 // An implicitly-declared copy constructor is an inline public 12591 // member of its class. 12592 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12593 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12594 ExplicitSpecifier(), 12595 /*isInline=*/true, 12596 /*isImplicitlyDeclared=*/true, Constexpr); 12597 CopyConstructor->setAccess(AS_public); 12598 CopyConstructor->setDefaulted(); 12599 12600 if (getLangOpts().CUDA) { 12601 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12602 CopyConstructor, 12603 /* ConstRHS */ Const, 12604 /* Diagnose */ false); 12605 } 12606 12607 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 12608 12609 // Add the parameter to the constructor. 12610 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12611 ClassLoc, ClassLoc, 12612 /*IdentifierInfo=*/nullptr, 12613 ArgType, /*TInfo=*/nullptr, 12614 SC_None, nullptr); 12615 CopyConstructor->setParams(FromParam); 12616 12617 CopyConstructor->setTrivial( 12618 ClassDecl->needsOverloadResolutionForCopyConstructor() 12619 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12620 : ClassDecl->hasTrivialCopyConstructor()); 12621 12622 CopyConstructor->setTrivialForCall( 12623 ClassDecl->hasAttr<TrivialABIAttr>() || 12624 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12625 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12626 TAH_ConsiderTrivialABI) 12627 : ClassDecl->hasTrivialCopyConstructorForCall())); 12628 12629 // Note that we have declared this constructor. 12630 ++getASTContext().NumImplicitCopyConstructorsDeclared; 12631 12632 Scope *S = getScopeForContext(ClassDecl); 12633 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12634 12635 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12636 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12637 SetDeclDeleted(CopyConstructor, ClassLoc); 12638 } 12639 12640 if (S) 12641 PushOnScopeChains(CopyConstructor, S, false); 12642 ClassDecl->addDecl(CopyConstructor); 12643 12644 return CopyConstructor; 12645 } 12646 12647 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12648 CXXConstructorDecl *CopyConstructor) { 12649 assert((CopyConstructor->isDefaulted() && 12650 CopyConstructor->isCopyConstructor() && 12651 !CopyConstructor->doesThisDeclarationHaveABody() && 12652 !CopyConstructor->isDeleted()) && 12653 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12654 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12655 return; 12656 12657 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12658 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12659 12660 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12661 12662 // The exception specification is needed because we are defining the 12663 // function. 12664 ResolveExceptionSpec(CurrentLocation, 12665 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12666 MarkVTableUsed(CurrentLocation, ClassDecl); 12667 12668 // Add a context note for diagnostics produced after this point. 12669 Scope.addContextNote(CurrentLocation); 12670 12671 // C++11 [class.copy]p7: 12672 // The [definition of an implicitly declared copy constructor] is 12673 // deprecated if the class has a user-declared copy assignment operator 12674 // or a user-declared destructor. 12675 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12676 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12677 12678 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12679 CopyConstructor->setInvalidDecl(); 12680 } else { 12681 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 12682 ? CopyConstructor->getEndLoc() 12683 : CopyConstructor->getLocation(); 12684 Sema::CompoundScopeRAII CompoundScope(*this); 12685 CopyConstructor->setBody( 12686 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12687 CopyConstructor->markUsed(Context); 12688 } 12689 12690 if (ASTMutationListener *L = getASTMutationListener()) { 12691 L->CompletedImplicitDefinition(CopyConstructor); 12692 } 12693 } 12694 12695 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12696 CXXRecordDecl *ClassDecl) { 12697 assert(ClassDecl->needsImplicitMoveConstructor()); 12698 12699 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12700 if (DSM.isAlreadyBeingDeclared()) 12701 return nullptr; 12702 12703 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12704 12705 QualType ArgType = ClassType; 12706 if (Context.getLangOpts().OpenCLCPlusPlus) 12707 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic); 12708 ArgType = Context.getRValueReferenceType(ArgType); 12709 12710 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12711 CXXMoveConstructor, 12712 false); 12713 12714 DeclarationName Name 12715 = Context.DeclarationNames.getCXXConstructorName( 12716 Context.getCanonicalType(ClassType)); 12717 SourceLocation ClassLoc = ClassDecl->getLocation(); 12718 DeclarationNameInfo NameInfo(Name, ClassLoc); 12719 12720 // C++11 [class.copy]p11: 12721 // An implicitly-declared copy/move constructor is an inline public 12722 // member of its class. 12723 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12724 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12725 ExplicitSpecifier(), 12726 /*isInline=*/true, 12727 /*isImplicitlyDeclared=*/true, Constexpr); 12728 MoveConstructor->setAccess(AS_public); 12729 MoveConstructor->setDefaulted(); 12730 12731 if (getLangOpts().CUDA) { 12732 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12733 MoveConstructor, 12734 /* ConstRHS */ false, 12735 /* Diagnose */ false); 12736 } 12737 12738 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 12739 12740 // Add the parameter to the constructor. 12741 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12742 ClassLoc, ClassLoc, 12743 /*IdentifierInfo=*/nullptr, 12744 ArgType, /*TInfo=*/nullptr, 12745 SC_None, nullptr); 12746 MoveConstructor->setParams(FromParam); 12747 12748 MoveConstructor->setTrivial( 12749 ClassDecl->needsOverloadResolutionForMoveConstructor() 12750 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12751 : ClassDecl->hasTrivialMoveConstructor()); 12752 12753 MoveConstructor->setTrivialForCall( 12754 ClassDecl->hasAttr<TrivialABIAttr>() || 12755 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12756 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12757 TAH_ConsiderTrivialABI) 12758 : ClassDecl->hasTrivialMoveConstructorForCall())); 12759 12760 // Note that we have declared this constructor. 12761 ++getASTContext().NumImplicitMoveConstructorsDeclared; 12762 12763 Scope *S = getScopeForContext(ClassDecl); 12764 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12765 12766 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12767 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12768 SetDeclDeleted(MoveConstructor, ClassLoc); 12769 } 12770 12771 if (S) 12772 PushOnScopeChains(MoveConstructor, S, false); 12773 ClassDecl->addDecl(MoveConstructor); 12774 12775 return MoveConstructor; 12776 } 12777 12778 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12779 CXXConstructorDecl *MoveConstructor) { 12780 assert((MoveConstructor->isDefaulted() && 12781 MoveConstructor->isMoveConstructor() && 12782 !MoveConstructor->doesThisDeclarationHaveABody() && 12783 !MoveConstructor->isDeleted()) && 12784 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12785 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12786 return; 12787 12788 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12789 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12790 12791 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12792 12793 // The exception specification is needed because we are defining the 12794 // function. 12795 ResolveExceptionSpec(CurrentLocation, 12796 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12797 MarkVTableUsed(CurrentLocation, ClassDecl); 12798 12799 // Add a context note for diagnostics produced after this point. 12800 Scope.addContextNote(CurrentLocation); 12801 12802 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12803 MoveConstructor->setInvalidDecl(); 12804 } else { 12805 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 12806 ? MoveConstructor->getEndLoc() 12807 : MoveConstructor->getLocation(); 12808 Sema::CompoundScopeRAII CompoundScope(*this); 12809 MoveConstructor->setBody(ActOnCompoundStmt( 12810 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12811 MoveConstructor->markUsed(Context); 12812 } 12813 12814 if (ASTMutationListener *L = getASTMutationListener()) { 12815 L->CompletedImplicitDefinition(MoveConstructor); 12816 } 12817 } 12818 12819 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12820 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12821 } 12822 12823 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12824 SourceLocation CurrentLocation, 12825 CXXConversionDecl *Conv) { 12826 SynthesizedFunctionScope Scope(*this, Conv); 12827 assert(!Conv->getReturnType()->isUndeducedType()); 12828 12829 CXXRecordDecl *Lambda = Conv->getParent(); 12830 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12831 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12832 12833 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12834 CallOp = InstantiateFunctionDeclaration( 12835 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12836 if (!CallOp) 12837 return; 12838 12839 Invoker = InstantiateFunctionDeclaration( 12840 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12841 if (!Invoker) 12842 return; 12843 } 12844 12845 if (CallOp->isInvalidDecl()) 12846 return; 12847 12848 // Mark the call operator referenced (and add to pending instantiations 12849 // if necessary). 12850 // For both the conversion and static-invoker template specializations 12851 // we construct their body's in this function, so no need to add them 12852 // to the PendingInstantiations. 12853 MarkFunctionReferenced(CurrentLocation, CallOp); 12854 12855 // Fill in the __invoke function with a dummy implementation. IR generation 12856 // will fill in the actual details. Update its type in case it contained 12857 // an 'auto'. 12858 Invoker->markUsed(Context); 12859 Invoker->setReferenced(); 12860 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12861 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12862 12863 // Construct the body of the conversion function { return __invoke; }. 12864 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12865 VK_LValue, Conv->getLocation()).get(); 12866 assert(FunctionRef && "Can't refer to __invoke function?"); 12867 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12868 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12869 Conv->getLocation())); 12870 Conv->markUsed(Context); 12871 Conv->setReferenced(); 12872 12873 if (ASTMutationListener *L = getASTMutationListener()) { 12874 L->CompletedImplicitDefinition(Conv); 12875 L->CompletedImplicitDefinition(Invoker); 12876 } 12877 } 12878 12879 12880 12881 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12882 SourceLocation CurrentLocation, 12883 CXXConversionDecl *Conv) 12884 { 12885 assert(!Conv->getParent()->isGenericLambda()); 12886 12887 SynthesizedFunctionScope Scope(*this, Conv); 12888 12889 // Copy-initialize the lambda object as needed to capture it. 12890 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12891 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12892 12893 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12894 Conv->getLocation(), 12895 Conv, DerefThis); 12896 12897 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12898 // behavior. Note that only the general conversion function does this 12899 // (since it's unusable otherwise); in the case where we inline the 12900 // block literal, it has block literal lifetime semantics. 12901 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12902 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12903 CK_CopyAndAutoreleaseBlockObject, 12904 BuildBlock.get(), nullptr, VK_RValue); 12905 12906 if (BuildBlock.isInvalid()) { 12907 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12908 Conv->setInvalidDecl(); 12909 return; 12910 } 12911 12912 // Create the return statement that returns the block from the conversion 12913 // function. 12914 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12915 if (Return.isInvalid()) { 12916 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12917 Conv->setInvalidDecl(); 12918 return; 12919 } 12920 12921 // Set the body of the conversion function. 12922 Stmt *ReturnS = Return.get(); 12923 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12924 Conv->getLocation())); 12925 Conv->markUsed(Context); 12926 12927 // We're done; notify the mutation listener, if any. 12928 if (ASTMutationListener *L = getASTMutationListener()) { 12929 L->CompletedImplicitDefinition(Conv); 12930 } 12931 } 12932 12933 /// Determine whether the given list arguments contains exactly one 12934 /// "real" (non-default) argument. 12935 static bool hasOneRealArgument(MultiExprArg Args) { 12936 switch (Args.size()) { 12937 case 0: 12938 return false; 12939 12940 default: 12941 if (!Args[1]->isDefaultArgument()) 12942 return false; 12943 12944 LLVM_FALLTHROUGH; 12945 case 1: 12946 return !Args[0]->isDefaultArgument(); 12947 } 12948 12949 return false; 12950 } 12951 12952 ExprResult 12953 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12954 NamedDecl *FoundDecl, 12955 CXXConstructorDecl *Constructor, 12956 MultiExprArg ExprArgs, 12957 bool HadMultipleCandidates, 12958 bool IsListInitialization, 12959 bool IsStdInitListInitialization, 12960 bool RequiresZeroInit, 12961 unsigned ConstructKind, 12962 SourceRange ParenRange) { 12963 bool Elidable = false; 12964 12965 // C++0x [class.copy]p34: 12966 // When certain criteria are met, an implementation is allowed to 12967 // omit the copy/move construction of a class object, even if the 12968 // copy/move constructor and/or destructor for the object have 12969 // side effects. [...] 12970 // - when a temporary class object that has not been bound to a 12971 // reference (12.2) would be copied/moved to a class object 12972 // with the same cv-unqualified type, the copy/move operation 12973 // can be omitted by constructing the temporary object 12974 // directly into the target of the omitted copy/move 12975 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12976 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12977 Expr *SubExpr = ExprArgs[0]; 12978 Elidable = SubExpr->isTemporaryObject( 12979 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12980 } 12981 12982 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12983 FoundDecl, Constructor, 12984 Elidable, ExprArgs, HadMultipleCandidates, 12985 IsListInitialization, 12986 IsStdInitListInitialization, RequiresZeroInit, 12987 ConstructKind, ParenRange); 12988 } 12989 12990 ExprResult 12991 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12992 NamedDecl *FoundDecl, 12993 CXXConstructorDecl *Constructor, 12994 bool Elidable, 12995 MultiExprArg ExprArgs, 12996 bool HadMultipleCandidates, 12997 bool IsListInitialization, 12998 bool IsStdInitListInitialization, 12999 bool RequiresZeroInit, 13000 unsigned ConstructKind, 13001 SourceRange ParenRange) { 13002 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 13003 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 13004 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 13005 return ExprError(); 13006 } 13007 13008 return BuildCXXConstructExpr( 13009 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 13010 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 13011 RequiresZeroInit, ConstructKind, ParenRange); 13012 } 13013 13014 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 13015 /// including handling of its default argument expressions. 13016 ExprResult 13017 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13018 CXXConstructorDecl *Constructor, 13019 bool Elidable, 13020 MultiExprArg ExprArgs, 13021 bool HadMultipleCandidates, 13022 bool IsListInitialization, 13023 bool IsStdInitListInitialization, 13024 bool RequiresZeroInit, 13025 unsigned ConstructKind, 13026 SourceRange ParenRange) { 13027 assert(declaresSameEntity( 13028 Constructor->getParent(), 13029 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 13030 "given constructor for wrong type"); 13031 MarkFunctionReferenced(ConstructLoc, Constructor); 13032 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 13033 return ExprError(); 13034 13035 return CXXConstructExpr::Create( 13036 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 13037 ExprArgs, HadMultipleCandidates, IsListInitialization, 13038 IsStdInitListInitialization, RequiresZeroInit, 13039 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 13040 ParenRange); 13041 } 13042 13043 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 13044 assert(Field->hasInClassInitializer()); 13045 13046 // If we already have the in-class initializer nothing needs to be done. 13047 if (Field->getInClassInitializer()) 13048 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13049 13050 // If we might have already tried and failed to instantiate, don't try again. 13051 if (Field->isInvalidDecl()) 13052 return ExprError(); 13053 13054 // Maybe we haven't instantiated the in-class initializer. Go check the 13055 // pattern FieldDecl to see if it has one. 13056 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 13057 13058 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 13059 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 13060 DeclContext::lookup_result Lookup = 13061 ClassPattern->lookup(Field->getDeclName()); 13062 13063 // Lookup can return at most two results: the pattern for the field, or the 13064 // injected class name of the parent record. No other member can have the 13065 // same name as the field. 13066 // In modules mode, lookup can return multiple results (coming from 13067 // different modules). 13068 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 13069 "more than two lookup results for field name"); 13070 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 13071 if (!Pattern) { 13072 assert(isa<CXXRecordDecl>(Lookup[0]) && 13073 "cannot have other non-field member with same name"); 13074 for (auto L : Lookup) 13075 if (isa<FieldDecl>(L)) { 13076 Pattern = cast<FieldDecl>(L); 13077 break; 13078 } 13079 assert(Pattern && "We must have set the Pattern!"); 13080 } 13081 13082 if (!Pattern->hasInClassInitializer() || 13083 InstantiateInClassInitializer(Loc, Field, Pattern, 13084 getTemplateInstantiationArgs(Field))) { 13085 // Don't diagnose this again. 13086 Field->setInvalidDecl(); 13087 return ExprError(); 13088 } 13089 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13090 } 13091 13092 // DR1351: 13093 // If the brace-or-equal-initializer of a non-static data member 13094 // invokes a defaulted default constructor of its class or of an 13095 // enclosing class in a potentially evaluated subexpression, the 13096 // program is ill-formed. 13097 // 13098 // This resolution is unworkable: the exception specification of the 13099 // default constructor can be needed in an unevaluated context, in 13100 // particular, in the operand of a noexcept-expression, and we can be 13101 // unable to compute an exception specification for an enclosed class. 13102 // 13103 // Any attempt to resolve the exception specification of a defaulted default 13104 // constructor before the initializer is lexically complete will ultimately 13105 // come here at which point we can diagnose it. 13106 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 13107 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 13108 << OutermostClass << Field; 13109 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 13110 // Recover by marking the field invalid, unless we're in a SFINAE context. 13111 if (!isSFINAEContext()) 13112 Field->setInvalidDecl(); 13113 return ExprError(); 13114 } 13115 13116 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 13117 if (VD->isInvalidDecl()) return; 13118 13119 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 13120 if (ClassDecl->isInvalidDecl()) return; 13121 if (ClassDecl->hasIrrelevantDestructor()) return; 13122 if (ClassDecl->isDependentContext()) return; 13123 13124 if (VD->isNoDestroy(getASTContext())) 13125 return; 13126 13127 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13128 13129 // If this is an array, we'll require the destructor during initialization, so 13130 // we can skip over this. We still want to emit exit-time destructor warnings 13131 // though. 13132 if (!VD->getType()->isArrayType()) { 13133 MarkFunctionReferenced(VD->getLocation(), Destructor); 13134 CheckDestructorAccess(VD->getLocation(), Destructor, 13135 PDiag(diag::err_access_dtor_var) 13136 << VD->getDeclName() << VD->getType()); 13137 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 13138 } 13139 13140 if (Destructor->isTrivial()) return; 13141 if (!VD->hasGlobalStorage()) return; 13142 13143 // Emit warning for non-trivial dtor in global scope (a real global, 13144 // class-static, function-static). 13145 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 13146 13147 // TODO: this should be re-enabled for static locals by !CXAAtExit 13148 if (!VD->isStaticLocal()) 13149 Diag(VD->getLocation(), diag::warn_global_destructor); 13150 } 13151 13152 /// Given a constructor and the set of arguments provided for the 13153 /// constructor, convert the arguments and add any required default arguments 13154 /// to form a proper call to this constructor. 13155 /// 13156 /// \returns true if an error occurred, false otherwise. 13157 bool 13158 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 13159 MultiExprArg ArgsPtr, 13160 SourceLocation Loc, 13161 SmallVectorImpl<Expr*> &ConvertedArgs, 13162 bool AllowExplicit, 13163 bool IsListInitialization) { 13164 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 13165 unsigned NumArgs = ArgsPtr.size(); 13166 Expr **Args = ArgsPtr.data(); 13167 13168 const FunctionProtoType *Proto 13169 = Constructor->getType()->getAs<FunctionProtoType>(); 13170 assert(Proto && "Constructor without a prototype?"); 13171 unsigned NumParams = Proto->getNumParams(); 13172 13173 // If too few arguments are available, we'll fill in the rest with defaults. 13174 if (NumArgs < NumParams) 13175 ConvertedArgs.reserve(NumParams); 13176 else 13177 ConvertedArgs.reserve(NumArgs); 13178 13179 VariadicCallType CallType = 13180 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 13181 SmallVector<Expr *, 8> AllArgs; 13182 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 13183 Proto, 0, 13184 llvm::makeArrayRef(Args, NumArgs), 13185 AllArgs, 13186 CallType, AllowExplicit, 13187 IsListInitialization); 13188 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 13189 13190 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 13191 13192 CheckConstructorCall(Constructor, 13193 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 13194 Proto, Loc); 13195 13196 return Invalid; 13197 } 13198 13199 static inline bool 13200 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 13201 const FunctionDecl *FnDecl) { 13202 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 13203 if (isa<NamespaceDecl>(DC)) { 13204 return SemaRef.Diag(FnDecl->getLocation(), 13205 diag::err_operator_new_delete_declared_in_namespace) 13206 << FnDecl->getDeclName(); 13207 } 13208 13209 if (isa<TranslationUnitDecl>(DC) && 13210 FnDecl->getStorageClass() == SC_Static) { 13211 return SemaRef.Diag(FnDecl->getLocation(), 13212 diag::err_operator_new_delete_declared_static) 13213 << FnDecl->getDeclName(); 13214 } 13215 13216 return false; 13217 } 13218 13219 static QualType 13220 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13221 QualType QTy = PtrTy->getPointeeType(); 13222 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13223 return SemaRef.Context.getPointerType(QTy); 13224 } 13225 13226 static inline bool 13227 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13228 CanQualType ExpectedResultType, 13229 CanQualType ExpectedFirstParamType, 13230 unsigned DependentParamTypeDiag, 13231 unsigned InvalidParamTypeDiag) { 13232 QualType ResultType = 13233 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13234 13235 // Check that the result type is not dependent. 13236 if (ResultType->isDependentType()) 13237 return SemaRef.Diag(FnDecl->getLocation(), 13238 diag::err_operator_new_delete_dependent_result_type) 13239 << FnDecl->getDeclName() << ExpectedResultType; 13240 13241 // OpenCL C++: the operator is valid on any address space. 13242 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13243 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13244 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13245 } 13246 } 13247 13248 // Check that the result type is what we expect. 13249 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13250 return SemaRef.Diag(FnDecl->getLocation(), 13251 diag::err_operator_new_delete_invalid_result_type) 13252 << FnDecl->getDeclName() << ExpectedResultType; 13253 13254 // A function template must have at least 2 parameters. 13255 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13256 return SemaRef.Diag(FnDecl->getLocation(), 13257 diag::err_operator_new_delete_template_too_few_parameters) 13258 << FnDecl->getDeclName(); 13259 13260 // The function decl must have at least 1 parameter. 13261 if (FnDecl->getNumParams() == 0) 13262 return SemaRef.Diag(FnDecl->getLocation(), 13263 diag::err_operator_new_delete_too_few_parameters) 13264 << FnDecl->getDeclName(); 13265 13266 // Check the first parameter type is not dependent. 13267 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13268 if (FirstParamType->isDependentType()) 13269 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13270 << FnDecl->getDeclName() << ExpectedFirstParamType; 13271 13272 // Check that the first parameter type is what we expect. 13273 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13274 // OpenCL C++: the operator is valid on any address space. 13275 if (auto *PtrTy = 13276 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13277 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13278 } 13279 } 13280 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13281 ExpectedFirstParamType) 13282 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13283 << FnDecl->getDeclName() << ExpectedFirstParamType; 13284 13285 return false; 13286 } 13287 13288 static bool 13289 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13290 // C++ [basic.stc.dynamic.allocation]p1: 13291 // A program is ill-formed if an allocation function is declared in a 13292 // namespace scope other than global scope or declared static in global 13293 // scope. 13294 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13295 return true; 13296 13297 CanQualType SizeTy = 13298 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13299 13300 // C++ [basic.stc.dynamic.allocation]p1: 13301 // The return type shall be void*. The first parameter shall have type 13302 // std::size_t. 13303 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13304 SizeTy, 13305 diag::err_operator_new_dependent_param_type, 13306 diag::err_operator_new_param_type)) 13307 return true; 13308 13309 // C++ [basic.stc.dynamic.allocation]p1: 13310 // The first parameter shall not have an associated default argument. 13311 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13312 return SemaRef.Diag(FnDecl->getLocation(), 13313 diag::err_operator_new_default_arg) 13314 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13315 13316 return false; 13317 } 13318 13319 static bool 13320 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13321 // C++ [basic.stc.dynamic.deallocation]p1: 13322 // A program is ill-formed if deallocation functions are declared in a 13323 // namespace scope other than global scope or declared static in global 13324 // scope. 13325 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13326 return true; 13327 13328 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13329 13330 // C++ P0722: 13331 // Within a class C, the first parameter of a destroying operator delete 13332 // shall be of type C *. The first parameter of any other deallocation 13333 // function shall be of type void *. 13334 CanQualType ExpectedFirstParamType = 13335 MD && MD->isDestroyingOperatorDelete() 13336 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13337 SemaRef.Context.getRecordType(MD->getParent()))) 13338 : SemaRef.Context.VoidPtrTy; 13339 13340 // C++ [basic.stc.dynamic.deallocation]p2: 13341 // Each deallocation function shall return void 13342 if (CheckOperatorNewDeleteTypes( 13343 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13344 diag::err_operator_delete_dependent_param_type, 13345 diag::err_operator_delete_param_type)) 13346 return true; 13347 13348 // C++ P0722: 13349 // A destroying operator delete shall be a usual deallocation function. 13350 if (MD && !MD->getParent()->isDependentContext() && 13351 MD->isDestroyingOperatorDelete() && 13352 !SemaRef.isUsualDeallocationFunction(MD)) { 13353 SemaRef.Diag(MD->getLocation(), 13354 diag::err_destroying_operator_delete_not_usual); 13355 return true; 13356 } 13357 13358 return false; 13359 } 13360 13361 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13362 /// of this overloaded operator is well-formed. If so, returns false; 13363 /// otherwise, emits appropriate diagnostics and returns true. 13364 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13365 assert(FnDecl && FnDecl->isOverloadedOperator() && 13366 "Expected an overloaded operator declaration"); 13367 13368 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13369 13370 // C++ [over.oper]p5: 13371 // The allocation and deallocation functions, operator new, 13372 // operator new[], operator delete and operator delete[], are 13373 // described completely in 3.7.3. The attributes and restrictions 13374 // found in the rest of this subclause do not apply to them unless 13375 // explicitly stated in 3.7.3. 13376 if (Op == OO_Delete || Op == OO_Array_Delete) 13377 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13378 13379 if (Op == OO_New || Op == OO_Array_New) 13380 return CheckOperatorNewDeclaration(*this, FnDecl); 13381 13382 // C++ [over.oper]p6: 13383 // An operator function shall either be a non-static member 13384 // function or be a non-member function and have at least one 13385 // parameter whose type is a class, a reference to a class, an 13386 // enumeration, or a reference to an enumeration. 13387 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13388 if (MethodDecl->isStatic()) 13389 return Diag(FnDecl->getLocation(), 13390 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13391 } else { 13392 bool ClassOrEnumParam = false; 13393 for (auto Param : FnDecl->parameters()) { 13394 QualType ParamType = Param->getType().getNonReferenceType(); 13395 if (ParamType->isDependentType() || ParamType->isRecordType() || 13396 ParamType->isEnumeralType()) { 13397 ClassOrEnumParam = true; 13398 break; 13399 } 13400 } 13401 13402 if (!ClassOrEnumParam) 13403 return Diag(FnDecl->getLocation(), 13404 diag::err_operator_overload_needs_class_or_enum) 13405 << FnDecl->getDeclName(); 13406 } 13407 13408 // C++ [over.oper]p8: 13409 // An operator function cannot have default arguments (8.3.6), 13410 // except where explicitly stated below. 13411 // 13412 // Only the function-call operator allows default arguments 13413 // (C++ [over.call]p1). 13414 if (Op != OO_Call) { 13415 for (auto Param : FnDecl->parameters()) { 13416 if (Param->hasDefaultArg()) 13417 return Diag(Param->getLocation(), 13418 diag::err_operator_overload_default_arg) 13419 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13420 } 13421 } 13422 13423 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13424 { false, false, false } 13425 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13426 , { Unary, Binary, MemberOnly } 13427 #include "clang/Basic/OperatorKinds.def" 13428 }; 13429 13430 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13431 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13432 bool MustBeMemberOperator = OperatorUses[Op][2]; 13433 13434 // C++ [over.oper]p8: 13435 // [...] Operator functions cannot have more or fewer parameters 13436 // than the number required for the corresponding operator, as 13437 // described in the rest of this subclause. 13438 unsigned NumParams = FnDecl->getNumParams() 13439 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13440 if (Op != OO_Call && 13441 ((NumParams == 1 && !CanBeUnaryOperator) || 13442 (NumParams == 2 && !CanBeBinaryOperator) || 13443 (NumParams < 1) || (NumParams > 2))) { 13444 // We have the wrong number of parameters. 13445 unsigned ErrorKind; 13446 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13447 ErrorKind = 2; // 2 -> unary or binary. 13448 } else if (CanBeUnaryOperator) { 13449 ErrorKind = 0; // 0 -> unary 13450 } else { 13451 assert(CanBeBinaryOperator && 13452 "All non-call overloaded operators are unary or binary!"); 13453 ErrorKind = 1; // 1 -> binary 13454 } 13455 13456 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13457 << FnDecl->getDeclName() << NumParams << ErrorKind; 13458 } 13459 13460 // Overloaded operators other than operator() cannot be variadic. 13461 if (Op != OO_Call && 13462 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13463 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13464 << FnDecl->getDeclName(); 13465 } 13466 13467 // Some operators must be non-static member functions. 13468 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13469 return Diag(FnDecl->getLocation(), 13470 diag::err_operator_overload_must_be_member) 13471 << FnDecl->getDeclName(); 13472 } 13473 13474 // C++ [over.inc]p1: 13475 // The user-defined function called operator++ implements the 13476 // prefix and postfix ++ operator. If this function is a member 13477 // function with no parameters, or a non-member function with one 13478 // parameter of class or enumeration type, it defines the prefix 13479 // increment operator ++ for objects of that type. If the function 13480 // is a member function with one parameter (which shall be of type 13481 // int) or a non-member function with two parameters (the second 13482 // of which shall be of type int), it defines the postfix 13483 // increment operator ++ for objects of that type. 13484 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13485 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13486 QualType ParamType = LastParam->getType(); 13487 13488 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13489 !ParamType->isDependentType()) 13490 return Diag(LastParam->getLocation(), 13491 diag::err_operator_overload_post_incdec_must_be_int) 13492 << LastParam->getType() << (Op == OO_MinusMinus); 13493 } 13494 13495 return false; 13496 } 13497 13498 static bool 13499 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13500 FunctionTemplateDecl *TpDecl) { 13501 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13502 13503 // Must have one or two template parameters. 13504 if (TemplateParams->size() == 1) { 13505 NonTypeTemplateParmDecl *PmDecl = 13506 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13507 13508 // The template parameter must be a char parameter pack. 13509 if (PmDecl && PmDecl->isTemplateParameterPack() && 13510 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13511 return false; 13512 13513 } else if (TemplateParams->size() == 2) { 13514 TemplateTypeParmDecl *PmType = 13515 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13516 NonTypeTemplateParmDecl *PmArgs = 13517 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13518 13519 // The second template parameter must be a parameter pack with the 13520 // first template parameter as its type. 13521 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13522 PmArgs->isTemplateParameterPack()) { 13523 const TemplateTypeParmType *TArgs = 13524 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13525 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13526 TArgs->getIndex() == PmType->getIndex()) { 13527 if (!SemaRef.inTemplateInstantiation()) 13528 SemaRef.Diag(TpDecl->getLocation(), 13529 diag::ext_string_literal_operator_template); 13530 return false; 13531 } 13532 } 13533 } 13534 13535 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13536 diag::err_literal_operator_template) 13537 << TpDecl->getTemplateParameters()->getSourceRange(); 13538 return true; 13539 } 13540 13541 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13542 /// of this literal operator function is well-formed. If so, returns 13543 /// false; otherwise, emits appropriate diagnostics and returns true. 13544 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13545 if (isa<CXXMethodDecl>(FnDecl)) { 13546 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13547 << FnDecl->getDeclName(); 13548 return true; 13549 } 13550 13551 if (FnDecl->isExternC()) { 13552 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13553 if (const LinkageSpecDecl *LSD = 13554 FnDecl->getDeclContext()->getExternCContext()) 13555 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13556 return true; 13557 } 13558 13559 // This might be the definition of a literal operator template. 13560 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13561 13562 // This might be a specialization of a literal operator template. 13563 if (!TpDecl) 13564 TpDecl = FnDecl->getPrimaryTemplate(); 13565 13566 // template <char...> type operator "" name() and 13567 // template <class T, T...> type operator "" name() are the only valid 13568 // template signatures, and the only valid signatures with no parameters. 13569 if (TpDecl) { 13570 if (FnDecl->param_size() != 0) { 13571 Diag(FnDecl->getLocation(), 13572 diag::err_literal_operator_template_with_params); 13573 return true; 13574 } 13575 13576 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13577 return true; 13578 13579 } else if (FnDecl->param_size() == 1) { 13580 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13581 13582 QualType ParamType = Param->getType().getUnqualifiedType(); 13583 13584 // Only unsigned long long int, long double, any character type, and const 13585 // char * are allowed as the only parameters. 13586 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13587 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13588 Context.hasSameType(ParamType, Context.CharTy) || 13589 Context.hasSameType(ParamType, Context.WideCharTy) || 13590 Context.hasSameType(ParamType, Context.Char8Ty) || 13591 Context.hasSameType(ParamType, Context.Char16Ty) || 13592 Context.hasSameType(ParamType, Context.Char32Ty)) { 13593 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13594 QualType InnerType = Ptr->getPointeeType(); 13595 13596 // Pointer parameter must be a const char *. 13597 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13598 Context.CharTy) && 13599 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13600 Diag(Param->getSourceRange().getBegin(), 13601 diag::err_literal_operator_param) 13602 << ParamType << "'const char *'" << Param->getSourceRange(); 13603 return true; 13604 } 13605 13606 } else if (ParamType->isRealFloatingType()) { 13607 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13608 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13609 return true; 13610 13611 } else if (ParamType->isIntegerType()) { 13612 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13613 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13614 return true; 13615 13616 } else { 13617 Diag(Param->getSourceRange().getBegin(), 13618 diag::err_literal_operator_invalid_param) 13619 << ParamType << Param->getSourceRange(); 13620 return true; 13621 } 13622 13623 } else if (FnDecl->param_size() == 2) { 13624 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13625 13626 // First, verify that the first parameter is correct. 13627 13628 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13629 13630 // Two parameter function must have a pointer to const as a 13631 // first parameter; let's strip those qualifiers. 13632 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13633 13634 if (!PT) { 13635 Diag((*Param)->getSourceRange().getBegin(), 13636 diag::err_literal_operator_param) 13637 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13638 return true; 13639 } 13640 13641 QualType PointeeType = PT->getPointeeType(); 13642 // First parameter must be const 13643 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13644 Diag((*Param)->getSourceRange().getBegin(), 13645 diag::err_literal_operator_param) 13646 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13647 return true; 13648 } 13649 13650 QualType InnerType = PointeeType.getUnqualifiedType(); 13651 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13652 // const char32_t* are allowed as the first parameter to a two-parameter 13653 // function 13654 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13655 Context.hasSameType(InnerType, Context.WideCharTy) || 13656 Context.hasSameType(InnerType, Context.Char8Ty) || 13657 Context.hasSameType(InnerType, Context.Char16Ty) || 13658 Context.hasSameType(InnerType, Context.Char32Ty))) { 13659 Diag((*Param)->getSourceRange().getBegin(), 13660 diag::err_literal_operator_param) 13661 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13662 return true; 13663 } 13664 13665 // Move on to the second and final parameter. 13666 ++Param; 13667 13668 // The second parameter must be a std::size_t. 13669 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13670 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13671 Diag((*Param)->getSourceRange().getBegin(), 13672 diag::err_literal_operator_param) 13673 << SecondParamType << Context.getSizeType() 13674 << (*Param)->getSourceRange(); 13675 return true; 13676 } 13677 } else { 13678 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13679 return true; 13680 } 13681 13682 // Parameters are good. 13683 13684 // A parameter-declaration-clause containing a default argument is not 13685 // equivalent to any of the permitted forms. 13686 for (auto Param : FnDecl->parameters()) { 13687 if (Param->hasDefaultArg()) { 13688 Diag(Param->getDefaultArgRange().getBegin(), 13689 diag::err_literal_operator_default_argument) 13690 << Param->getDefaultArgRange(); 13691 break; 13692 } 13693 } 13694 13695 StringRef LiteralName 13696 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13697 if (LiteralName[0] != '_' && 13698 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13699 // C++11 [usrlit.suffix]p1: 13700 // Literal suffix identifiers that do not start with an underscore 13701 // are reserved for future standardization. 13702 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13703 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13704 } 13705 13706 return false; 13707 } 13708 13709 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13710 /// linkage specification, including the language and (if present) 13711 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13712 /// language string literal. LBraceLoc, if valid, provides the location of 13713 /// the '{' brace. Otherwise, this linkage specification does not 13714 /// have any braces. 13715 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13716 Expr *LangStr, 13717 SourceLocation LBraceLoc) { 13718 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13719 if (!Lit->isAscii()) { 13720 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13721 << LangStr->getSourceRange(); 13722 return nullptr; 13723 } 13724 13725 StringRef Lang = Lit->getString(); 13726 LinkageSpecDecl::LanguageIDs Language; 13727 if (Lang == "C") 13728 Language = LinkageSpecDecl::lang_c; 13729 else if (Lang == "C++") 13730 Language = LinkageSpecDecl::lang_cxx; 13731 else { 13732 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13733 << LangStr->getSourceRange(); 13734 return nullptr; 13735 } 13736 13737 // FIXME: Add all the various semantics of linkage specifications 13738 13739 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13740 LangStr->getExprLoc(), Language, 13741 LBraceLoc.isValid()); 13742 CurContext->addDecl(D); 13743 PushDeclContext(S, D); 13744 return D; 13745 } 13746 13747 /// ActOnFinishLinkageSpecification - Complete the definition of 13748 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13749 /// valid, it's the position of the closing '}' brace in a linkage 13750 /// specification that uses braces. 13751 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13752 Decl *LinkageSpec, 13753 SourceLocation RBraceLoc) { 13754 if (RBraceLoc.isValid()) { 13755 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13756 LSDecl->setRBraceLoc(RBraceLoc); 13757 } 13758 PopDeclContext(); 13759 return LinkageSpec; 13760 } 13761 13762 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13763 const ParsedAttributesView &AttrList, 13764 SourceLocation SemiLoc) { 13765 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13766 // Attribute declarations appertain to empty declaration so we handle 13767 // them here. 13768 ProcessDeclAttributeList(S, ED, AttrList); 13769 13770 CurContext->addDecl(ED); 13771 return ED; 13772 } 13773 13774 /// Perform semantic analysis for the variable declaration that 13775 /// occurs within a C++ catch clause, returning the newly-created 13776 /// variable. 13777 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13778 TypeSourceInfo *TInfo, 13779 SourceLocation StartLoc, 13780 SourceLocation Loc, 13781 IdentifierInfo *Name) { 13782 bool Invalid = false; 13783 QualType ExDeclType = TInfo->getType(); 13784 13785 // Arrays and functions decay. 13786 if (ExDeclType->isArrayType()) 13787 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13788 else if (ExDeclType->isFunctionType()) 13789 ExDeclType = Context.getPointerType(ExDeclType); 13790 13791 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13792 // The exception-declaration shall not denote a pointer or reference to an 13793 // incomplete type, other than [cv] void*. 13794 // N2844 forbids rvalue references. 13795 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13796 Diag(Loc, diag::err_catch_rvalue_ref); 13797 Invalid = true; 13798 } 13799 13800 if (ExDeclType->isVariablyModifiedType()) { 13801 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13802 Invalid = true; 13803 } 13804 13805 QualType BaseType = ExDeclType; 13806 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13807 unsigned DK = diag::err_catch_incomplete; 13808 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13809 BaseType = Ptr->getPointeeType(); 13810 Mode = 1; 13811 DK = diag::err_catch_incomplete_ptr; 13812 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13813 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13814 BaseType = Ref->getPointeeType(); 13815 Mode = 2; 13816 DK = diag::err_catch_incomplete_ref; 13817 } 13818 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13819 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13820 Invalid = true; 13821 13822 if (!Invalid && !ExDeclType->isDependentType() && 13823 RequireNonAbstractType(Loc, ExDeclType, 13824 diag::err_abstract_type_in_decl, 13825 AbstractVariableType)) 13826 Invalid = true; 13827 13828 // Only the non-fragile NeXT runtime currently supports C++ catches 13829 // of ObjC types, and no runtime supports catching ObjC types by value. 13830 if (!Invalid && getLangOpts().ObjC) { 13831 QualType T = ExDeclType; 13832 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13833 T = RT->getPointeeType(); 13834 13835 if (T->isObjCObjectType()) { 13836 Diag(Loc, diag::err_objc_object_catch); 13837 Invalid = true; 13838 } else if (T->isObjCObjectPointerType()) { 13839 // FIXME: should this be a test for macosx-fragile specifically? 13840 if (getLangOpts().ObjCRuntime.isFragile()) 13841 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13842 } 13843 } 13844 13845 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13846 ExDeclType, TInfo, SC_None); 13847 ExDecl->setExceptionVariable(true); 13848 13849 // In ARC, infer 'retaining' for variables of retainable type. 13850 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13851 Invalid = true; 13852 13853 if (!Invalid && !ExDeclType->isDependentType()) { 13854 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13855 // Insulate this from anything else we might currently be parsing. 13856 EnterExpressionEvaluationContext scope( 13857 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13858 13859 // C++ [except.handle]p16: 13860 // The object declared in an exception-declaration or, if the 13861 // exception-declaration does not specify a name, a temporary (12.2) is 13862 // copy-initialized (8.5) from the exception object. [...] 13863 // The object is destroyed when the handler exits, after the destruction 13864 // of any automatic objects initialized within the handler. 13865 // 13866 // We just pretend to initialize the object with itself, then make sure 13867 // it can be destroyed later. 13868 QualType initType = Context.getExceptionObjectType(ExDeclType); 13869 13870 InitializedEntity entity = 13871 InitializedEntity::InitializeVariable(ExDecl); 13872 InitializationKind initKind = 13873 InitializationKind::CreateCopy(Loc, SourceLocation()); 13874 13875 Expr *opaqueValue = 13876 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13877 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13878 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13879 if (result.isInvalid()) 13880 Invalid = true; 13881 else { 13882 // If the constructor used was non-trivial, set this as the 13883 // "initializer". 13884 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13885 if (!construct->getConstructor()->isTrivial()) { 13886 Expr *init = MaybeCreateExprWithCleanups(construct); 13887 ExDecl->setInit(init); 13888 } 13889 13890 // And make sure it's destructable. 13891 FinalizeVarWithDestructor(ExDecl, recordType); 13892 } 13893 } 13894 } 13895 13896 if (Invalid) 13897 ExDecl->setInvalidDecl(); 13898 13899 return ExDecl; 13900 } 13901 13902 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13903 /// handler. 13904 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13905 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13906 bool Invalid = D.isInvalidType(); 13907 13908 // Check for unexpanded parameter packs. 13909 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13910 UPPC_ExceptionType)) { 13911 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13912 D.getIdentifierLoc()); 13913 Invalid = true; 13914 } 13915 13916 IdentifierInfo *II = D.getIdentifier(); 13917 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13918 LookupOrdinaryName, 13919 ForVisibleRedeclaration)) { 13920 // The scope should be freshly made just for us. There is just no way 13921 // it contains any previous declaration, except for function parameters in 13922 // a function-try-block's catch statement. 13923 assert(!S->isDeclScope(PrevDecl)); 13924 if (isDeclInScope(PrevDecl, CurContext, S)) { 13925 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13926 << D.getIdentifier(); 13927 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13928 Invalid = true; 13929 } else if (PrevDecl->isTemplateParameter()) 13930 // Maybe we will complain about the shadowed template parameter. 13931 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13932 } 13933 13934 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13935 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13936 << D.getCXXScopeSpec().getRange(); 13937 Invalid = true; 13938 } 13939 13940 VarDecl *ExDecl = BuildExceptionDeclaration( 13941 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 13942 if (Invalid) 13943 ExDecl->setInvalidDecl(); 13944 13945 // Add the exception declaration into this scope. 13946 if (II) 13947 PushOnScopeChains(ExDecl, S); 13948 else 13949 CurContext->addDecl(ExDecl); 13950 13951 ProcessDeclAttributes(S, ExDecl, D); 13952 return ExDecl; 13953 } 13954 13955 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13956 Expr *AssertExpr, 13957 Expr *AssertMessageExpr, 13958 SourceLocation RParenLoc) { 13959 StringLiteral *AssertMessage = 13960 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13961 13962 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13963 return nullptr; 13964 13965 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13966 AssertMessage, RParenLoc, false); 13967 } 13968 13969 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13970 Expr *AssertExpr, 13971 StringLiteral *AssertMessage, 13972 SourceLocation RParenLoc, 13973 bool Failed) { 13974 assert(AssertExpr != nullptr && "Expected non-null condition"); 13975 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13976 !Failed) { 13977 // In a static_assert-declaration, the constant-expression shall be a 13978 // constant expression that can be contextually converted to bool. 13979 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13980 if (Converted.isInvalid()) 13981 Failed = true; 13982 else 13983 Converted = ConstantExpr::Create(Context, Converted.get()); 13984 13985 llvm::APSInt Cond; 13986 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13987 diag::err_static_assert_expression_is_not_constant, 13988 /*AllowFold=*/false).isInvalid()) 13989 Failed = true; 13990 13991 if (!Failed && !Cond) { 13992 SmallString<256> MsgBuffer; 13993 llvm::raw_svector_ostream Msg(MsgBuffer); 13994 if (AssertMessage) 13995 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13996 13997 Expr *InnerCond = nullptr; 13998 std::string InnerCondDescription; 13999 std::tie(InnerCond, InnerCondDescription) = 14000 findFailedBooleanCondition(Converted.get()); 14001 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 14002 && !isa<IntegerLiteral>(InnerCond)) { 14003 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 14004 << InnerCondDescription << !AssertMessage 14005 << Msg.str() << InnerCond->getSourceRange(); 14006 } else { 14007 Diag(StaticAssertLoc, diag::err_static_assert_failed) 14008 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 14009 } 14010 Failed = true; 14011 } 14012 } 14013 14014 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 14015 /*DiscardedValue*/false, 14016 /*IsConstexpr*/true); 14017 if (FullAssertExpr.isInvalid()) 14018 Failed = true; 14019 else 14020 AssertExpr = FullAssertExpr.get(); 14021 14022 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 14023 AssertExpr, AssertMessage, RParenLoc, 14024 Failed); 14025 14026 CurContext->addDecl(Decl); 14027 return Decl; 14028 } 14029 14030 /// Perform semantic analysis of the given friend type declaration. 14031 /// 14032 /// \returns A friend declaration that. 14033 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 14034 SourceLocation FriendLoc, 14035 TypeSourceInfo *TSInfo) { 14036 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 14037 14038 QualType T = TSInfo->getType(); 14039 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 14040 14041 // C++03 [class.friend]p2: 14042 // An elaborated-type-specifier shall be used in a friend declaration 14043 // for a class.* 14044 // 14045 // * The class-key of the elaborated-type-specifier is required. 14046 if (!CodeSynthesisContexts.empty()) { 14047 // Do not complain about the form of friend template types during any kind 14048 // of code synthesis. For template instantiation, we will have complained 14049 // when the template was defined. 14050 } else { 14051 if (!T->isElaboratedTypeSpecifier()) { 14052 // If we evaluated the type to a record type, suggest putting 14053 // a tag in front. 14054 if (const RecordType *RT = T->getAs<RecordType>()) { 14055 RecordDecl *RD = RT->getDecl(); 14056 14057 SmallString<16> InsertionText(" "); 14058 InsertionText += RD->getKindName(); 14059 14060 Diag(TypeRange.getBegin(), 14061 getLangOpts().CPlusPlus11 ? 14062 diag::warn_cxx98_compat_unelaborated_friend_type : 14063 diag::ext_unelaborated_friend_type) 14064 << (unsigned) RD->getTagKind() 14065 << T 14066 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 14067 InsertionText); 14068 } else { 14069 Diag(FriendLoc, 14070 getLangOpts().CPlusPlus11 ? 14071 diag::warn_cxx98_compat_nonclass_type_friend : 14072 diag::ext_nonclass_type_friend) 14073 << T 14074 << TypeRange; 14075 } 14076 } else if (T->getAs<EnumType>()) { 14077 Diag(FriendLoc, 14078 getLangOpts().CPlusPlus11 ? 14079 diag::warn_cxx98_compat_enum_friend : 14080 diag::ext_enum_friend) 14081 << T 14082 << TypeRange; 14083 } 14084 14085 // C++11 [class.friend]p3: 14086 // A friend declaration that does not declare a function shall have one 14087 // of the following forms: 14088 // friend elaborated-type-specifier ; 14089 // friend simple-type-specifier ; 14090 // friend typename-specifier ; 14091 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 14092 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 14093 } 14094 14095 // If the type specifier in a friend declaration designates a (possibly 14096 // cv-qualified) class type, that class is declared as a friend; otherwise, 14097 // the friend declaration is ignored. 14098 return FriendDecl::Create(Context, CurContext, 14099 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 14100 FriendLoc); 14101 } 14102 14103 /// Handle a friend tag declaration where the scope specifier was 14104 /// templated. 14105 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 14106 unsigned TagSpec, SourceLocation TagLoc, 14107 CXXScopeSpec &SS, IdentifierInfo *Name, 14108 SourceLocation NameLoc, 14109 const ParsedAttributesView &Attr, 14110 MultiTemplateParamsArg TempParamLists) { 14111 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14112 14113 bool IsMemberSpecialization = false; 14114 bool Invalid = false; 14115 14116 if (TemplateParameterList *TemplateParams = 14117 MatchTemplateParametersToScopeSpecifier( 14118 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 14119 IsMemberSpecialization, Invalid)) { 14120 if (TemplateParams->size() > 0) { 14121 // This is a declaration of a class template. 14122 if (Invalid) 14123 return nullptr; 14124 14125 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 14126 NameLoc, Attr, TemplateParams, AS_public, 14127 /*ModulePrivateLoc=*/SourceLocation(), 14128 FriendLoc, TempParamLists.size() - 1, 14129 TempParamLists.data()).get(); 14130 } else { 14131 // The "template<>" header is extraneous. 14132 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14133 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14134 IsMemberSpecialization = true; 14135 } 14136 } 14137 14138 if (Invalid) return nullptr; 14139 14140 bool isAllExplicitSpecializations = true; 14141 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 14142 if (TempParamLists[I]->size()) { 14143 isAllExplicitSpecializations = false; 14144 break; 14145 } 14146 } 14147 14148 // FIXME: don't ignore attributes. 14149 14150 // If it's explicit specializations all the way down, just forget 14151 // about the template header and build an appropriate non-templated 14152 // friend. TODO: for source fidelity, remember the headers. 14153 if (isAllExplicitSpecializations) { 14154 if (SS.isEmpty()) { 14155 bool Owned = false; 14156 bool IsDependent = false; 14157 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 14158 Attr, AS_public, 14159 /*ModulePrivateLoc=*/SourceLocation(), 14160 MultiTemplateParamsArg(), Owned, IsDependent, 14161 /*ScopedEnumKWLoc=*/SourceLocation(), 14162 /*ScopedEnumUsesClassTag=*/false, 14163 /*UnderlyingType=*/TypeResult(), 14164 /*IsTypeSpecifier=*/false, 14165 /*IsTemplateParamOrArg=*/false); 14166 } 14167 14168 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 14169 ElaboratedTypeKeyword Keyword 14170 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14171 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 14172 *Name, NameLoc); 14173 if (T.isNull()) 14174 return nullptr; 14175 14176 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14177 if (isa<DependentNameType>(T)) { 14178 DependentNameTypeLoc TL = 14179 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14180 TL.setElaboratedKeywordLoc(TagLoc); 14181 TL.setQualifierLoc(QualifierLoc); 14182 TL.setNameLoc(NameLoc); 14183 } else { 14184 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 14185 TL.setElaboratedKeywordLoc(TagLoc); 14186 TL.setQualifierLoc(QualifierLoc); 14187 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 14188 } 14189 14190 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14191 TSI, FriendLoc, TempParamLists); 14192 Friend->setAccess(AS_public); 14193 CurContext->addDecl(Friend); 14194 return Friend; 14195 } 14196 14197 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 14198 14199 14200 14201 // Handle the case of a templated-scope friend class. e.g. 14202 // template <class T> class A<T>::B; 14203 // FIXME: we don't support these right now. 14204 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 14205 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 14206 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14207 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 14208 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14209 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14210 TL.setElaboratedKeywordLoc(TagLoc); 14211 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14212 TL.setNameLoc(NameLoc); 14213 14214 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14215 TSI, FriendLoc, TempParamLists); 14216 Friend->setAccess(AS_public); 14217 Friend->setUnsupportedFriend(true); 14218 CurContext->addDecl(Friend); 14219 return Friend; 14220 } 14221 14222 /// Handle a friend type declaration. This works in tandem with 14223 /// ActOnTag. 14224 /// 14225 /// Notes on friend class templates: 14226 /// 14227 /// We generally treat friend class declarations as if they were 14228 /// declaring a class. So, for example, the elaborated type specifier 14229 /// in a friend declaration is required to obey the restrictions of a 14230 /// class-head (i.e. no typedefs in the scope chain), template 14231 /// parameters are required to match up with simple template-ids, &c. 14232 /// However, unlike when declaring a template specialization, it's 14233 /// okay to refer to a template specialization without an empty 14234 /// template parameter declaration, e.g. 14235 /// friend class A<T>::B<unsigned>; 14236 /// We permit this as a special case; if there are any template 14237 /// parameters present at all, require proper matching, i.e. 14238 /// template <> template \<class T> friend class A<int>::B; 14239 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14240 MultiTemplateParamsArg TempParams) { 14241 SourceLocation Loc = DS.getBeginLoc(); 14242 14243 assert(DS.isFriendSpecified()); 14244 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14245 14246 // C++ [class.friend]p3: 14247 // A friend declaration that does not declare a function shall have one of 14248 // the following forms: 14249 // friend elaborated-type-specifier ; 14250 // friend simple-type-specifier ; 14251 // friend typename-specifier ; 14252 // 14253 // Any declaration with a type qualifier does not have that form. (It's 14254 // legal to specify a qualified type as a friend, you just can't write the 14255 // keywords.) 14256 if (DS.getTypeQualifiers()) { 14257 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 14258 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 14259 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 14260 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 14261 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 14262 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 14263 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 14264 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 14265 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 14266 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 14267 } 14268 14269 // Try to convert the decl specifier to a type. This works for 14270 // friend templates because ActOnTag never produces a ClassTemplateDecl 14271 // for a TUK_Friend. 14272 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14273 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14274 QualType T = TSI->getType(); 14275 if (TheDeclarator.isInvalidType()) 14276 return nullptr; 14277 14278 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14279 return nullptr; 14280 14281 // This is definitely an error in C++98. It's probably meant to 14282 // be forbidden in C++0x, too, but the specification is just 14283 // poorly written. 14284 // 14285 // The problem is with declarations like the following: 14286 // template <T> friend A<T>::foo; 14287 // where deciding whether a class C is a friend or not now hinges 14288 // on whether there exists an instantiation of A that causes 14289 // 'foo' to equal C. There are restrictions on class-heads 14290 // (which we declare (by fiat) elaborated friend declarations to 14291 // be) that makes this tractable. 14292 // 14293 // FIXME: handle "template <> friend class A<T>;", which 14294 // is possibly well-formed? Who even knows? 14295 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14296 Diag(Loc, diag::err_tagless_friend_type_template) 14297 << DS.getSourceRange(); 14298 return nullptr; 14299 } 14300 14301 // C++98 [class.friend]p1: A friend of a class is a function 14302 // or class that is not a member of the class . . . 14303 // This is fixed in DR77, which just barely didn't make the C++03 14304 // deadline. It's also a very silly restriction that seriously 14305 // affects inner classes and which nobody else seems to implement; 14306 // thus we never diagnose it, not even in -pedantic. 14307 // 14308 // But note that we could warn about it: it's always useless to 14309 // friend one of your own members (it's not, however, worthless to 14310 // friend a member of an arbitrary specialization of your template). 14311 14312 Decl *D; 14313 if (!TempParams.empty()) 14314 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14315 TempParams, 14316 TSI, 14317 DS.getFriendSpecLoc()); 14318 else 14319 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14320 14321 if (!D) 14322 return nullptr; 14323 14324 D->setAccess(AS_public); 14325 CurContext->addDecl(D); 14326 14327 return D; 14328 } 14329 14330 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14331 MultiTemplateParamsArg TemplateParams) { 14332 const DeclSpec &DS = D.getDeclSpec(); 14333 14334 assert(DS.isFriendSpecified()); 14335 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14336 14337 SourceLocation Loc = D.getIdentifierLoc(); 14338 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14339 14340 // C++ [class.friend]p1 14341 // A friend of a class is a function or class.... 14342 // Note that this sees through typedefs, which is intended. 14343 // It *doesn't* see through dependent types, which is correct 14344 // according to [temp.arg.type]p3: 14345 // If a declaration acquires a function type through a 14346 // type dependent on a template-parameter and this causes 14347 // a declaration that does not use the syntactic form of a 14348 // function declarator to have a function type, the program 14349 // is ill-formed. 14350 if (!TInfo->getType()->isFunctionType()) { 14351 Diag(Loc, diag::err_unexpected_friend); 14352 14353 // It might be worthwhile to try to recover by creating an 14354 // appropriate declaration. 14355 return nullptr; 14356 } 14357 14358 // C++ [namespace.memdef]p3 14359 // - If a friend declaration in a non-local class first declares a 14360 // class or function, the friend class or function is a member 14361 // of the innermost enclosing namespace. 14362 // - The name of the friend is not found by simple name lookup 14363 // until a matching declaration is provided in that namespace 14364 // scope (either before or after the class declaration granting 14365 // friendship). 14366 // - If a friend function is called, its name may be found by the 14367 // name lookup that considers functions from namespaces and 14368 // classes associated with the types of the function arguments. 14369 // - When looking for a prior declaration of a class or a function 14370 // declared as a friend, scopes outside the innermost enclosing 14371 // namespace scope are not considered. 14372 14373 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14374 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14375 assert(NameInfo.getName()); 14376 14377 // Check for unexpanded parameter packs. 14378 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14379 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14380 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14381 return nullptr; 14382 14383 // The context we found the declaration in, or in which we should 14384 // create the declaration. 14385 DeclContext *DC; 14386 Scope *DCScope = S; 14387 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14388 ForExternalRedeclaration); 14389 14390 // There are five cases here. 14391 // - There's no scope specifier and we're in a local class. Only look 14392 // for functions declared in the immediately-enclosing block scope. 14393 // We recover from invalid scope qualifiers as if they just weren't there. 14394 FunctionDecl *FunctionContainingLocalClass = nullptr; 14395 if ((SS.isInvalid() || !SS.isSet()) && 14396 (FunctionContainingLocalClass = 14397 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14398 // C++11 [class.friend]p11: 14399 // If a friend declaration appears in a local class and the name 14400 // specified is an unqualified name, a prior declaration is 14401 // looked up without considering scopes that are outside the 14402 // innermost enclosing non-class scope. For a friend function 14403 // declaration, if there is no prior declaration, the program is 14404 // ill-formed. 14405 14406 // Find the innermost enclosing non-class scope. This is the block 14407 // scope containing the local class definition (or for a nested class, 14408 // the outer local class). 14409 DCScope = S->getFnParent(); 14410 14411 // Look up the function name in the scope. 14412 Previous.clear(LookupLocalFriendName); 14413 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14414 14415 if (!Previous.empty()) { 14416 // All possible previous declarations must have the same context: 14417 // either they were declared at block scope or they are members of 14418 // one of the enclosing local classes. 14419 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14420 } else { 14421 // This is ill-formed, but provide the context that we would have 14422 // declared the function in, if we were permitted to, for error recovery. 14423 DC = FunctionContainingLocalClass; 14424 } 14425 adjustContextForLocalExternDecl(DC); 14426 14427 // C++ [class.friend]p6: 14428 // A function can be defined in a friend declaration of a class if and 14429 // only if the class is a non-local class (9.8), the function name is 14430 // unqualified, and the function has namespace scope. 14431 if (D.isFunctionDefinition()) { 14432 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14433 } 14434 14435 // - There's no scope specifier, in which case we just go to the 14436 // appropriate scope and look for a function or function template 14437 // there as appropriate. 14438 } else if (SS.isInvalid() || !SS.isSet()) { 14439 // C++11 [namespace.memdef]p3: 14440 // If the name in a friend declaration is neither qualified nor 14441 // a template-id and the declaration is a function or an 14442 // elaborated-type-specifier, the lookup to determine whether 14443 // the entity has been previously declared shall not consider 14444 // any scopes outside the innermost enclosing namespace. 14445 bool isTemplateId = 14446 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14447 14448 // Find the appropriate context according to the above. 14449 DC = CurContext; 14450 14451 // Skip class contexts. If someone can cite chapter and verse 14452 // for this behavior, that would be nice --- it's what GCC and 14453 // EDG do, and it seems like a reasonable intent, but the spec 14454 // really only says that checks for unqualified existing 14455 // declarations should stop at the nearest enclosing namespace, 14456 // not that they should only consider the nearest enclosing 14457 // namespace. 14458 while (DC->isRecord()) 14459 DC = DC->getParent(); 14460 14461 DeclContext *LookupDC = DC; 14462 while (LookupDC->isTransparentContext()) 14463 LookupDC = LookupDC->getParent(); 14464 14465 while (true) { 14466 LookupQualifiedName(Previous, LookupDC); 14467 14468 if (!Previous.empty()) { 14469 DC = LookupDC; 14470 break; 14471 } 14472 14473 if (isTemplateId) { 14474 if (isa<TranslationUnitDecl>(LookupDC)) break; 14475 } else { 14476 if (LookupDC->isFileContext()) break; 14477 } 14478 LookupDC = LookupDC->getParent(); 14479 } 14480 14481 DCScope = getScopeForDeclContext(S, DC); 14482 14483 // - There's a non-dependent scope specifier, in which case we 14484 // compute it and do a previous lookup there for a function 14485 // or function template. 14486 } else if (!SS.getScopeRep()->isDependent()) { 14487 DC = computeDeclContext(SS); 14488 if (!DC) return nullptr; 14489 14490 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14491 14492 LookupQualifiedName(Previous, DC); 14493 14494 // C++ [class.friend]p1: A friend of a class is a function or 14495 // class that is not a member of the class . . . 14496 if (DC->Equals(CurContext)) 14497 Diag(DS.getFriendSpecLoc(), 14498 getLangOpts().CPlusPlus11 ? 14499 diag::warn_cxx98_compat_friend_is_member : 14500 diag::err_friend_is_member); 14501 14502 if (D.isFunctionDefinition()) { 14503 // C++ [class.friend]p6: 14504 // A function can be defined in a friend declaration of a class if and 14505 // only if the class is a non-local class (9.8), the function name is 14506 // unqualified, and the function has namespace scope. 14507 // 14508 // FIXME: We should only do this if the scope specifier names the 14509 // innermost enclosing namespace; otherwise the fixit changes the 14510 // meaning of the code. 14511 SemaDiagnosticBuilder DB 14512 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14513 14514 DB << SS.getScopeRep(); 14515 if (DC->isFileContext()) 14516 DB << FixItHint::CreateRemoval(SS.getRange()); 14517 SS.clear(); 14518 } 14519 14520 // - There's a scope specifier that does not match any template 14521 // parameter lists, in which case we use some arbitrary context, 14522 // create a method or method template, and wait for instantiation. 14523 // - There's a scope specifier that does match some template 14524 // parameter lists, which we don't handle right now. 14525 } else { 14526 if (D.isFunctionDefinition()) { 14527 // C++ [class.friend]p6: 14528 // A function can be defined in a friend declaration of a class if and 14529 // only if the class is a non-local class (9.8), the function name is 14530 // unqualified, and the function has namespace scope. 14531 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14532 << SS.getScopeRep(); 14533 } 14534 14535 DC = CurContext; 14536 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14537 } 14538 14539 if (!DC->isRecord()) { 14540 int DiagArg = -1; 14541 switch (D.getName().getKind()) { 14542 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14543 case UnqualifiedIdKind::IK_ConstructorName: 14544 DiagArg = 0; 14545 break; 14546 case UnqualifiedIdKind::IK_DestructorName: 14547 DiagArg = 1; 14548 break; 14549 case UnqualifiedIdKind::IK_ConversionFunctionId: 14550 DiagArg = 2; 14551 break; 14552 case UnqualifiedIdKind::IK_DeductionGuideName: 14553 DiagArg = 3; 14554 break; 14555 case UnqualifiedIdKind::IK_Identifier: 14556 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14557 case UnqualifiedIdKind::IK_LiteralOperatorId: 14558 case UnqualifiedIdKind::IK_OperatorFunctionId: 14559 case UnqualifiedIdKind::IK_TemplateId: 14560 break; 14561 } 14562 // This implies that it has to be an operator or function. 14563 if (DiagArg >= 0) { 14564 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14565 return nullptr; 14566 } 14567 } 14568 14569 // FIXME: This is an egregious hack to cope with cases where the scope stack 14570 // does not contain the declaration context, i.e., in an out-of-line 14571 // definition of a class. 14572 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14573 if (!DCScope) { 14574 FakeDCScope.setEntity(DC); 14575 DCScope = &FakeDCScope; 14576 } 14577 14578 bool AddToScope = true; 14579 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14580 TemplateParams, AddToScope); 14581 if (!ND) return nullptr; 14582 14583 assert(ND->getLexicalDeclContext() == CurContext); 14584 14585 // If we performed typo correction, we might have added a scope specifier 14586 // and changed the decl context. 14587 DC = ND->getDeclContext(); 14588 14589 // Add the function declaration to the appropriate lookup tables, 14590 // adjusting the redeclarations list as necessary. We don't 14591 // want to do this yet if the friending class is dependent. 14592 // 14593 // Also update the scope-based lookup if the target context's 14594 // lookup context is in lexical scope. 14595 if (!CurContext->isDependentContext()) { 14596 DC = DC->getRedeclContext(); 14597 DC->makeDeclVisibleInContext(ND); 14598 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14599 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14600 } 14601 14602 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14603 D.getIdentifierLoc(), ND, 14604 DS.getFriendSpecLoc()); 14605 FrD->setAccess(AS_public); 14606 CurContext->addDecl(FrD); 14607 14608 if (ND->isInvalidDecl()) { 14609 FrD->setInvalidDecl(); 14610 } else { 14611 if (DC->isRecord()) CheckFriendAccess(ND); 14612 14613 FunctionDecl *FD; 14614 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14615 FD = FTD->getTemplatedDecl(); 14616 else 14617 FD = cast<FunctionDecl>(ND); 14618 14619 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14620 // default argument expression, that declaration shall be a definition 14621 // and shall be the only declaration of the function or function 14622 // template in the translation unit. 14623 if (functionDeclHasDefaultArgument(FD)) { 14624 // We can't look at FD->getPreviousDecl() because it may not have been set 14625 // if we're in a dependent context. If the function is known to be a 14626 // redeclaration, we will have narrowed Previous down to the right decl. 14627 if (D.isRedeclaration()) { 14628 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14629 Diag(Previous.getRepresentativeDecl()->getLocation(), 14630 diag::note_previous_declaration); 14631 } else if (!D.isFunctionDefinition()) 14632 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14633 } 14634 14635 // Mark templated-scope function declarations as unsupported. 14636 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14637 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14638 << SS.getScopeRep() << SS.getRange() 14639 << cast<CXXRecordDecl>(CurContext); 14640 FrD->setUnsupportedFriend(true); 14641 } 14642 } 14643 14644 return ND; 14645 } 14646 14647 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14648 AdjustDeclIfTemplate(Dcl); 14649 14650 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14651 if (!Fn) { 14652 Diag(DelLoc, diag::err_deleted_non_function); 14653 return; 14654 } 14655 14656 // Deleted function does not have a body. 14657 Fn->setWillHaveBody(false); 14658 14659 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14660 // Don't consider the implicit declaration we generate for explicit 14661 // specializations. FIXME: Do not generate these implicit declarations. 14662 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14663 Prev->getPreviousDecl()) && 14664 !Prev->isDefined()) { 14665 Diag(DelLoc, diag::err_deleted_decl_not_first); 14666 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14667 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14668 : diag::note_previous_declaration); 14669 } 14670 // If the declaration wasn't the first, we delete the function anyway for 14671 // recovery. 14672 Fn = Fn->getCanonicalDecl(); 14673 } 14674 14675 // dllimport/dllexport cannot be deleted. 14676 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14677 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14678 Fn->setInvalidDecl(); 14679 } 14680 14681 if (Fn->isDeleted()) 14682 return; 14683 14684 // See if we're deleting a function which is already known to override a 14685 // non-deleted virtual function. 14686 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14687 bool IssuedDiagnostic = false; 14688 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14689 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14690 if (!IssuedDiagnostic) { 14691 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14692 IssuedDiagnostic = true; 14693 } 14694 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14695 } 14696 } 14697 // If this function was implicitly deleted because it was defaulted, 14698 // explain why it was deleted. 14699 if (IssuedDiagnostic && MD->isDefaulted()) 14700 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14701 /*Diagnose*/true); 14702 } 14703 14704 // C++11 [basic.start.main]p3: 14705 // A program that defines main as deleted [...] is ill-formed. 14706 if (Fn->isMain()) 14707 Diag(DelLoc, diag::err_deleted_main); 14708 14709 // C++11 [dcl.fct.def.delete]p4: 14710 // A deleted function is implicitly inline. 14711 Fn->setImplicitlyInline(); 14712 Fn->setDeletedAsWritten(); 14713 } 14714 14715 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14716 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14717 14718 if (MD) { 14719 if (MD->getParent()->isDependentType()) { 14720 MD->setDefaulted(); 14721 MD->setExplicitlyDefaulted(); 14722 return; 14723 } 14724 14725 CXXSpecialMember Member = getSpecialMember(MD); 14726 if (Member == CXXInvalid) { 14727 if (!MD->isInvalidDecl()) 14728 Diag(DefaultLoc, diag::err_default_special_members); 14729 return; 14730 } 14731 14732 MD->setDefaulted(); 14733 MD->setExplicitlyDefaulted(); 14734 14735 // Unset that we will have a body for this function. We might not, 14736 // if it turns out to be trivial, and we don't need this marking now 14737 // that we've marked it as defaulted. 14738 MD->setWillHaveBody(false); 14739 14740 // If this definition appears within the record, do the checking when 14741 // the record is complete. 14742 const FunctionDecl *Primary = MD; 14743 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14744 // Ask the template instantiation pattern that actually had the 14745 // '= default' on it. 14746 Primary = Pattern; 14747 14748 // If the method was defaulted on its first declaration, we will have 14749 // already performed the checking in CheckCompletedCXXClass. Such a 14750 // declaration doesn't trigger an implicit definition. 14751 if (Primary->getCanonicalDecl()->isDefaulted()) 14752 return; 14753 14754 CheckExplicitlyDefaultedSpecialMember(MD); 14755 14756 if (!MD->isInvalidDecl()) 14757 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14758 } else { 14759 Diag(DefaultLoc, diag::err_default_special_members); 14760 } 14761 } 14762 14763 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14764 for (Stmt *SubStmt : S->children()) { 14765 if (!SubStmt) 14766 continue; 14767 if (isa<ReturnStmt>(SubStmt)) 14768 Self.Diag(SubStmt->getBeginLoc(), 14769 diag::err_return_in_constructor_handler); 14770 if (!isa<Expr>(SubStmt)) 14771 SearchForReturnInStmt(Self, SubStmt); 14772 } 14773 } 14774 14775 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14776 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14777 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14778 SearchForReturnInStmt(*this, Handler); 14779 } 14780 } 14781 14782 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14783 const CXXMethodDecl *Old) { 14784 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14785 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14786 14787 if (OldFT->hasExtParameterInfos()) { 14788 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14789 // A parameter of the overriding method should be annotated with noescape 14790 // if the corresponding parameter of the overridden method is annotated. 14791 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14792 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14793 Diag(New->getParamDecl(I)->getLocation(), 14794 diag::warn_overriding_method_missing_noescape); 14795 Diag(Old->getParamDecl(I)->getLocation(), 14796 diag::note_overridden_marked_noescape); 14797 } 14798 } 14799 14800 // Virtual overrides must have the same code_seg. 14801 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 14802 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 14803 if ((NewCSA || OldCSA) && 14804 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 14805 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 14806 Diag(Old->getLocation(), diag::note_previous_declaration); 14807 return true; 14808 } 14809 14810 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14811 14812 // If the calling conventions match, everything is fine 14813 if (NewCC == OldCC) 14814 return false; 14815 14816 // If the calling conventions mismatch because the new function is static, 14817 // suppress the calling convention mismatch error; the error about static 14818 // function override (err_static_overrides_virtual from 14819 // Sema::CheckFunctionDeclaration) is more clear. 14820 if (New->getStorageClass() == SC_Static) 14821 return false; 14822 14823 Diag(New->getLocation(), 14824 diag::err_conflicting_overriding_cc_attributes) 14825 << New->getDeclName() << New->getType() << Old->getType(); 14826 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14827 return true; 14828 } 14829 14830 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14831 const CXXMethodDecl *Old) { 14832 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14833 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14834 14835 if (Context.hasSameType(NewTy, OldTy) || 14836 NewTy->isDependentType() || OldTy->isDependentType()) 14837 return false; 14838 14839 // Check if the return types are covariant 14840 QualType NewClassTy, OldClassTy; 14841 14842 /// Both types must be pointers or references to classes. 14843 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14844 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14845 NewClassTy = NewPT->getPointeeType(); 14846 OldClassTy = OldPT->getPointeeType(); 14847 } 14848 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14849 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14850 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14851 NewClassTy = NewRT->getPointeeType(); 14852 OldClassTy = OldRT->getPointeeType(); 14853 } 14854 } 14855 } 14856 14857 // The return types aren't either both pointers or references to a class type. 14858 if (NewClassTy.isNull()) { 14859 Diag(New->getLocation(), 14860 diag::err_different_return_type_for_overriding_virtual_function) 14861 << New->getDeclName() << NewTy << OldTy 14862 << New->getReturnTypeSourceRange(); 14863 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14864 << Old->getReturnTypeSourceRange(); 14865 14866 return true; 14867 } 14868 14869 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14870 // C++14 [class.virtual]p8: 14871 // If the class type in the covariant return type of D::f differs from 14872 // that of B::f, the class type in the return type of D::f shall be 14873 // complete at the point of declaration of D::f or shall be the class 14874 // type D. 14875 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14876 if (!RT->isBeingDefined() && 14877 RequireCompleteType(New->getLocation(), NewClassTy, 14878 diag::err_covariant_return_incomplete, 14879 New->getDeclName())) 14880 return true; 14881 } 14882 14883 // Check if the new class derives from the old class. 14884 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14885 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14886 << New->getDeclName() << NewTy << OldTy 14887 << New->getReturnTypeSourceRange(); 14888 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14889 << Old->getReturnTypeSourceRange(); 14890 return true; 14891 } 14892 14893 // Check if we the conversion from derived to base is valid. 14894 if (CheckDerivedToBaseConversion( 14895 NewClassTy, OldClassTy, 14896 diag::err_covariant_return_inaccessible_base, 14897 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14898 New->getLocation(), New->getReturnTypeSourceRange(), 14899 New->getDeclName(), nullptr)) { 14900 // FIXME: this note won't trigger for delayed access control 14901 // diagnostics, and it's impossible to get an undelayed error 14902 // here from access control during the original parse because 14903 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14904 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14905 << Old->getReturnTypeSourceRange(); 14906 return true; 14907 } 14908 } 14909 14910 // The qualifiers of the return types must be the same. 14911 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14912 Diag(New->getLocation(), 14913 diag::err_covariant_return_type_different_qualifications) 14914 << New->getDeclName() << NewTy << OldTy 14915 << New->getReturnTypeSourceRange(); 14916 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14917 << Old->getReturnTypeSourceRange(); 14918 return true; 14919 } 14920 14921 14922 // The new class type must have the same or less qualifiers as the old type. 14923 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14924 Diag(New->getLocation(), 14925 diag::err_covariant_return_type_class_type_more_qualified) 14926 << New->getDeclName() << NewTy << OldTy 14927 << New->getReturnTypeSourceRange(); 14928 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14929 << Old->getReturnTypeSourceRange(); 14930 return true; 14931 } 14932 14933 return false; 14934 } 14935 14936 /// Mark the given method pure. 14937 /// 14938 /// \param Method the method to be marked pure. 14939 /// 14940 /// \param InitRange the source range that covers the "0" initializer. 14941 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14942 SourceLocation EndLoc = InitRange.getEnd(); 14943 if (EndLoc.isValid()) 14944 Method->setRangeEnd(EndLoc); 14945 14946 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14947 Method->setPure(); 14948 return false; 14949 } 14950 14951 if (!Method->isInvalidDecl()) 14952 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14953 << Method->getDeclName() << InitRange; 14954 return true; 14955 } 14956 14957 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14958 if (D->getFriendObjectKind()) 14959 Diag(D->getLocation(), diag::err_pure_friend); 14960 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14961 CheckPureMethod(M, ZeroLoc); 14962 else 14963 Diag(D->getLocation(), diag::err_illegal_initializer); 14964 } 14965 14966 /// Determine whether the given declaration is a global variable or 14967 /// static data member. 14968 static bool isNonlocalVariable(const Decl *D) { 14969 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14970 return Var->hasGlobalStorage(); 14971 14972 return false; 14973 } 14974 14975 /// Invoked when we are about to parse an initializer for the declaration 14976 /// 'Dcl'. 14977 /// 14978 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14979 /// static data member of class X, names should be looked up in the scope of 14980 /// class X. If the declaration had a scope specifier, a scope will have 14981 /// been created and passed in for this purpose. Otherwise, S will be null. 14982 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14983 // If there is no declaration, there was an error parsing it. 14984 if (!D || D->isInvalidDecl()) 14985 return; 14986 14987 // We will always have a nested name specifier here, but this declaration 14988 // might not be out of line if the specifier names the current namespace: 14989 // extern int n; 14990 // int ::n = 0; 14991 if (S && D->isOutOfLine()) 14992 EnterDeclaratorContext(S, D->getDeclContext()); 14993 14994 // If we are parsing the initializer for a static data member, push a 14995 // new expression evaluation context that is associated with this static 14996 // data member. 14997 if (isNonlocalVariable(D)) 14998 PushExpressionEvaluationContext( 14999 ExpressionEvaluationContext::PotentiallyEvaluated, D); 15000 } 15001 15002 /// Invoked after we are finished parsing an initializer for the declaration D. 15003 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 15004 // If there is no declaration, there was an error parsing it. 15005 if (!D || D->isInvalidDecl()) 15006 return; 15007 15008 if (isNonlocalVariable(D)) 15009 PopExpressionEvaluationContext(); 15010 15011 if (S && D->isOutOfLine()) 15012 ExitDeclaratorContext(S); 15013 } 15014 15015 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 15016 /// C++ if/switch/while/for statement. 15017 /// e.g: "if (int x = f()) {...}" 15018 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 15019 // C++ 6.4p2: 15020 // The declarator shall not specify a function or an array. 15021 // The type-specifier-seq shall not contain typedef and shall not declare a 15022 // new class or enumeration. 15023 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 15024 "Parser allowed 'typedef' as storage class of condition decl."); 15025 15026 Decl *Dcl = ActOnDeclarator(S, D); 15027 if (!Dcl) 15028 return true; 15029 15030 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 15031 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 15032 << D.getSourceRange(); 15033 return true; 15034 } 15035 15036 return Dcl; 15037 } 15038 15039 void Sema::LoadExternalVTableUses() { 15040 if (!ExternalSource) 15041 return; 15042 15043 SmallVector<ExternalVTableUse, 4> VTables; 15044 ExternalSource->ReadUsedVTables(VTables); 15045 SmallVector<VTableUse, 4> NewUses; 15046 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 15047 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 15048 = VTablesUsed.find(VTables[I].Record); 15049 // Even if a definition wasn't required before, it may be required now. 15050 if (Pos != VTablesUsed.end()) { 15051 if (!Pos->second && VTables[I].DefinitionRequired) 15052 Pos->second = true; 15053 continue; 15054 } 15055 15056 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 15057 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 15058 } 15059 15060 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 15061 } 15062 15063 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 15064 bool DefinitionRequired) { 15065 // Ignore any vtable uses in unevaluated operands or for classes that do 15066 // not have a vtable. 15067 if (!Class->isDynamicClass() || Class->isDependentContext() || 15068 CurContext->isDependentContext() || isUnevaluatedContext()) 15069 return; 15070 // Do not mark as used if compiling for the device outside of the target 15071 // region. 15072 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 15073 !isInOpenMPDeclareTargetContext() && 15074 !isInOpenMPTargetExecutionDirective()) { 15075 if (!DefinitionRequired) 15076 MarkVirtualMembersReferenced(Loc, Class); 15077 return; 15078 } 15079 15080 // Try to insert this class into the map. 15081 LoadExternalVTableUses(); 15082 Class = Class->getCanonicalDecl(); 15083 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 15084 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 15085 if (!Pos.second) { 15086 // If we already had an entry, check to see if we are promoting this vtable 15087 // to require a definition. If so, we need to reappend to the VTableUses 15088 // list, since we may have already processed the first entry. 15089 if (DefinitionRequired && !Pos.first->second) { 15090 Pos.first->second = true; 15091 } else { 15092 // Otherwise, we can early exit. 15093 return; 15094 } 15095 } else { 15096 // The Microsoft ABI requires that we perform the destructor body 15097 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 15098 // the deleting destructor is emitted with the vtable, not with the 15099 // destructor definition as in the Itanium ABI. 15100 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15101 CXXDestructorDecl *DD = Class->getDestructor(); 15102 if (DD && DD->isVirtual() && !DD->isDeleted()) { 15103 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 15104 // If this is an out-of-line declaration, marking it referenced will 15105 // not do anything. Manually call CheckDestructor to look up operator 15106 // delete(). 15107 ContextRAII SavedContext(*this, DD); 15108 CheckDestructor(DD); 15109 } else { 15110 MarkFunctionReferenced(Loc, Class->getDestructor()); 15111 } 15112 } 15113 } 15114 } 15115 15116 // Local classes need to have their virtual members marked 15117 // immediately. For all other classes, we mark their virtual members 15118 // at the end of the translation unit. 15119 if (Class->isLocalClass()) 15120 MarkVirtualMembersReferenced(Loc, Class); 15121 else 15122 VTableUses.push_back(std::make_pair(Class, Loc)); 15123 } 15124 15125 bool Sema::DefineUsedVTables() { 15126 LoadExternalVTableUses(); 15127 if (VTableUses.empty()) 15128 return false; 15129 15130 // Note: The VTableUses vector could grow as a result of marking 15131 // the members of a class as "used", so we check the size each 15132 // time through the loop and prefer indices (which are stable) to 15133 // iterators (which are not). 15134 bool DefinedAnything = false; 15135 for (unsigned I = 0; I != VTableUses.size(); ++I) { 15136 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 15137 if (!Class) 15138 continue; 15139 TemplateSpecializationKind ClassTSK = 15140 Class->getTemplateSpecializationKind(); 15141 15142 SourceLocation Loc = VTableUses[I].second; 15143 15144 bool DefineVTable = true; 15145 15146 // If this class has a key function, but that key function is 15147 // defined in another translation unit, we don't need to emit the 15148 // vtable even though we're using it. 15149 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 15150 if (KeyFunction && !KeyFunction->hasBody()) { 15151 // The key function is in another translation unit. 15152 DefineVTable = false; 15153 TemplateSpecializationKind TSK = 15154 KeyFunction->getTemplateSpecializationKind(); 15155 assert(TSK != TSK_ExplicitInstantiationDefinition && 15156 TSK != TSK_ImplicitInstantiation && 15157 "Instantiations don't have key functions"); 15158 (void)TSK; 15159 } else if (!KeyFunction) { 15160 // If we have a class with no key function that is the subject 15161 // of an explicit instantiation declaration, suppress the 15162 // vtable; it will live with the explicit instantiation 15163 // definition. 15164 bool IsExplicitInstantiationDeclaration = 15165 ClassTSK == TSK_ExplicitInstantiationDeclaration; 15166 for (auto R : Class->redecls()) { 15167 TemplateSpecializationKind TSK 15168 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 15169 if (TSK == TSK_ExplicitInstantiationDeclaration) 15170 IsExplicitInstantiationDeclaration = true; 15171 else if (TSK == TSK_ExplicitInstantiationDefinition) { 15172 IsExplicitInstantiationDeclaration = false; 15173 break; 15174 } 15175 } 15176 15177 if (IsExplicitInstantiationDeclaration) 15178 DefineVTable = false; 15179 } 15180 15181 // The exception specifications for all virtual members may be needed even 15182 // if we are not providing an authoritative form of the vtable in this TU. 15183 // We may choose to emit it available_externally anyway. 15184 if (!DefineVTable) { 15185 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 15186 continue; 15187 } 15188 15189 // Mark all of the virtual members of this class as referenced, so 15190 // that we can build a vtable. Then, tell the AST consumer that a 15191 // vtable for this class is required. 15192 DefinedAnything = true; 15193 MarkVirtualMembersReferenced(Loc, Class); 15194 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 15195 if (VTablesUsed[Canonical]) 15196 Consumer.HandleVTable(Class); 15197 15198 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 15199 // no key function or the key function is inlined. Don't warn in C++ ABIs 15200 // that lack key functions, since the user won't be able to make one. 15201 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 15202 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 15203 const FunctionDecl *KeyFunctionDef = nullptr; 15204 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 15205 KeyFunctionDef->isInlined())) { 15206 Diag(Class->getLocation(), 15207 ClassTSK == TSK_ExplicitInstantiationDefinition 15208 ? diag::warn_weak_template_vtable 15209 : diag::warn_weak_vtable) 15210 << Class; 15211 } 15212 } 15213 } 15214 VTableUses.clear(); 15215 15216 return DefinedAnything; 15217 } 15218 15219 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 15220 const CXXRecordDecl *RD) { 15221 for (const auto *I : RD->methods()) 15222 if (I->isVirtual() && !I->isPure()) 15223 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 15224 } 15225 15226 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 15227 const CXXRecordDecl *RD, 15228 bool ConstexprOnly) { 15229 // Mark all functions which will appear in RD's vtable as used. 15230 CXXFinalOverriderMap FinalOverriders; 15231 RD->getFinalOverriders(FinalOverriders); 15232 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 15233 E = FinalOverriders.end(); 15234 I != E; ++I) { 15235 for (OverridingMethods::const_iterator OI = I->second.begin(), 15236 OE = I->second.end(); 15237 OI != OE; ++OI) { 15238 assert(OI->second.size() > 0 && "no final overrider"); 15239 CXXMethodDecl *Overrider = OI->second.front().Method; 15240 15241 // C++ [basic.def.odr]p2: 15242 // [...] A virtual member function is used if it is not pure. [...] 15243 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 15244 MarkFunctionReferenced(Loc, Overrider); 15245 } 15246 } 15247 15248 // Only classes that have virtual bases need a VTT. 15249 if (RD->getNumVBases() == 0) 15250 return; 15251 15252 for (const auto &I : RD->bases()) { 15253 const CXXRecordDecl *Base = 15254 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15255 if (Base->getNumVBases() == 0) 15256 continue; 15257 MarkVirtualMembersReferenced(Loc, Base); 15258 } 15259 } 15260 15261 /// SetIvarInitializers - This routine builds initialization ASTs for the 15262 /// Objective-C implementation whose ivars need be initialized. 15263 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15264 if (!getLangOpts().CPlusPlus) 15265 return; 15266 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15267 SmallVector<ObjCIvarDecl*, 8> ivars; 15268 CollectIvarsToConstructOrDestruct(OID, ivars); 15269 if (ivars.empty()) 15270 return; 15271 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15272 for (unsigned i = 0; i < ivars.size(); i++) { 15273 FieldDecl *Field = ivars[i]; 15274 if (Field->isInvalidDecl()) 15275 continue; 15276 15277 CXXCtorInitializer *Member; 15278 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15279 InitializationKind InitKind = 15280 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15281 15282 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15283 ExprResult MemberInit = 15284 InitSeq.Perform(*this, InitEntity, InitKind, None); 15285 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15286 // Note, MemberInit could actually come back empty if no initialization 15287 // is required (e.g., because it would call a trivial default constructor) 15288 if (!MemberInit.get() || MemberInit.isInvalid()) 15289 continue; 15290 15291 Member = 15292 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15293 SourceLocation(), 15294 MemberInit.getAs<Expr>(), 15295 SourceLocation()); 15296 AllToInit.push_back(Member); 15297 15298 // Be sure that the destructor is accessible and is marked as referenced. 15299 if (const RecordType *RecordTy = 15300 Context.getBaseElementType(Field->getType()) 15301 ->getAs<RecordType>()) { 15302 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15303 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15304 MarkFunctionReferenced(Field->getLocation(), Destructor); 15305 CheckDestructorAccess(Field->getLocation(), Destructor, 15306 PDiag(diag::err_access_dtor_ivar) 15307 << Context.getBaseElementType(Field->getType())); 15308 } 15309 } 15310 } 15311 ObjCImplementation->setIvarInitializers(Context, 15312 AllToInit.data(), AllToInit.size()); 15313 } 15314 } 15315 15316 static 15317 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15318 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15319 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15320 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15321 Sema &S) { 15322 if (Ctor->isInvalidDecl()) 15323 return; 15324 15325 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15326 15327 // Target may not be determinable yet, for instance if this is a dependent 15328 // call in an uninstantiated template. 15329 if (Target) { 15330 const FunctionDecl *FNTarget = nullptr; 15331 (void)Target->hasBody(FNTarget); 15332 Target = const_cast<CXXConstructorDecl*>( 15333 cast_or_null<CXXConstructorDecl>(FNTarget)); 15334 } 15335 15336 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15337 // Avoid dereferencing a null pointer here. 15338 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15339 15340 if (!Current.insert(Canonical).second) 15341 return; 15342 15343 // We know that beyond here, we aren't chaining into a cycle. 15344 if (!Target || !Target->isDelegatingConstructor() || 15345 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15346 Valid.insert(Current.begin(), Current.end()); 15347 Current.clear(); 15348 // We've hit a cycle. 15349 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15350 Current.count(TCanonical)) { 15351 // If we haven't diagnosed this cycle yet, do so now. 15352 if (!Invalid.count(TCanonical)) { 15353 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15354 diag::warn_delegating_ctor_cycle) 15355 << Ctor; 15356 15357 // Don't add a note for a function delegating directly to itself. 15358 if (TCanonical != Canonical) 15359 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15360 15361 CXXConstructorDecl *C = Target; 15362 while (C->getCanonicalDecl() != Canonical) { 15363 const FunctionDecl *FNTarget = nullptr; 15364 (void)C->getTargetConstructor()->hasBody(FNTarget); 15365 assert(FNTarget && "Ctor cycle through bodiless function"); 15366 15367 C = const_cast<CXXConstructorDecl*>( 15368 cast<CXXConstructorDecl>(FNTarget)); 15369 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15370 } 15371 } 15372 15373 Invalid.insert(Current.begin(), Current.end()); 15374 Current.clear(); 15375 } else { 15376 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15377 } 15378 } 15379 15380 15381 void Sema::CheckDelegatingCtorCycles() { 15382 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15383 15384 for (DelegatingCtorDeclsType::iterator 15385 I = DelegatingCtorDecls.begin(ExternalSource), 15386 E = DelegatingCtorDecls.end(); 15387 I != E; ++I) 15388 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15389 15390 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15391 (*CI)->setInvalidDecl(); 15392 } 15393 15394 namespace { 15395 /// AST visitor that finds references to the 'this' expression. 15396 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15397 Sema &S; 15398 15399 public: 15400 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15401 15402 bool VisitCXXThisExpr(CXXThisExpr *E) { 15403 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15404 << E->isImplicit(); 15405 return false; 15406 } 15407 }; 15408 } 15409 15410 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15411 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15412 if (!TSInfo) 15413 return false; 15414 15415 TypeLoc TL = TSInfo->getTypeLoc(); 15416 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15417 if (!ProtoTL) 15418 return false; 15419 15420 // C++11 [expr.prim.general]p3: 15421 // [The expression this] shall not appear before the optional 15422 // cv-qualifier-seq and it shall not appear within the declaration of a 15423 // static member function (although its type and value category are defined 15424 // within a static member function as they are within a non-static member 15425 // function). [ Note: this is because declaration matching does not occur 15426 // until the complete declarator is known. - end note ] 15427 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15428 FindCXXThisExpr Finder(*this); 15429 15430 // If the return type came after the cv-qualifier-seq, check it now. 15431 if (Proto->hasTrailingReturn() && 15432 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15433 return true; 15434 15435 // Check the exception specification. 15436 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15437 return true; 15438 15439 return checkThisInStaticMemberFunctionAttributes(Method); 15440 } 15441 15442 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15443 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15444 if (!TSInfo) 15445 return false; 15446 15447 TypeLoc TL = TSInfo->getTypeLoc(); 15448 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15449 if (!ProtoTL) 15450 return false; 15451 15452 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15453 FindCXXThisExpr Finder(*this); 15454 15455 switch (Proto->getExceptionSpecType()) { 15456 case EST_Unparsed: 15457 case EST_Uninstantiated: 15458 case EST_Unevaluated: 15459 case EST_BasicNoexcept: 15460 case EST_DynamicNone: 15461 case EST_MSAny: 15462 case EST_None: 15463 break; 15464 15465 case EST_DependentNoexcept: 15466 case EST_NoexceptFalse: 15467 case EST_NoexceptTrue: 15468 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15469 return true; 15470 LLVM_FALLTHROUGH; 15471 15472 case EST_Dynamic: 15473 for (const auto &E : Proto->exceptions()) { 15474 if (!Finder.TraverseType(E)) 15475 return true; 15476 } 15477 break; 15478 } 15479 15480 return false; 15481 } 15482 15483 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15484 FindCXXThisExpr Finder(*this); 15485 15486 // Check attributes. 15487 for (const auto *A : Method->attrs()) { 15488 // FIXME: This should be emitted by tblgen. 15489 Expr *Arg = nullptr; 15490 ArrayRef<Expr *> Args; 15491 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15492 Arg = G->getArg(); 15493 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15494 Arg = G->getArg(); 15495 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15496 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15497 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15498 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15499 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15500 Arg = ETLF->getSuccessValue(); 15501 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15502 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15503 Arg = STLF->getSuccessValue(); 15504 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15505 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15506 Arg = LR->getArg(); 15507 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15508 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15509 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15510 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15511 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15512 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15513 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15514 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15515 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15516 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15517 15518 if (Arg && !Finder.TraverseStmt(Arg)) 15519 return true; 15520 15521 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15522 if (!Finder.TraverseStmt(Args[I])) 15523 return true; 15524 } 15525 } 15526 15527 return false; 15528 } 15529 15530 void Sema::checkExceptionSpecification( 15531 bool IsTopLevel, ExceptionSpecificationType EST, 15532 ArrayRef<ParsedType> DynamicExceptions, 15533 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15534 SmallVectorImpl<QualType> &Exceptions, 15535 FunctionProtoType::ExceptionSpecInfo &ESI) { 15536 Exceptions.clear(); 15537 ESI.Type = EST; 15538 if (EST == EST_Dynamic) { 15539 Exceptions.reserve(DynamicExceptions.size()); 15540 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15541 // FIXME: Preserve type source info. 15542 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15543 15544 if (IsTopLevel) { 15545 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15546 collectUnexpandedParameterPacks(ET, Unexpanded); 15547 if (!Unexpanded.empty()) { 15548 DiagnoseUnexpandedParameterPacks( 15549 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15550 Unexpanded); 15551 continue; 15552 } 15553 } 15554 15555 // Check that the type is valid for an exception spec, and 15556 // drop it if not. 15557 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15558 Exceptions.push_back(ET); 15559 } 15560 ESI.Exceptions = Exceptions; 15561 return; 15562 } 15563 15564 if (isComputedNoexcept(EST)) { 15565 assert((NoexceptExpr->isTypeDependent() || 15566 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15567 Context.BoolTy) && 15568 "Parser should have made sure that the expression is boolean"); 15569 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15570 ESI.Type = EST_BasicNoexcept; 15571 return; 15572 } 15573 15574 ESI.NoexceptExpr = NoexceptExpr; 15575 return; 15576 } 15577 } 15578 15579 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15580 ExceptionSpecificationType EST, 15581 SourceRange SpecificationRange, 15582 ArrayRef<ParsedType> DynamicExceptions, 15583 ArrayRef<SourceRange> DynamicExceptionRanges, 15584 Expr *NoexceptExpr) { 15585 if (!MethodD) 15586 return; 15587 15588 // Dig out the method we're referring to. 15589 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15590 MethodD = FunTmpl->getTemplatedDecl(); 15591 15592 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15593 if (!Method) 15594 return; 15595 15596 // Check the exception specification. 15597 llvm::SmallVector<QualType, 4> Exceptions; 15598 FunctionProtoType::ExceptionSpecInfo ESI; 15599 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15600 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15601 ESI); 15602 15603 // Update the exception specification on the function type. 15604 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15605 15606 if (Method->isStatic()) 15607 checkThisInStaticMemberFunctionExceptionSpec(Method); 15608 15609 if (Method->isVirtual()) { 15610 // Check overrides, which we previously had to delay. 15611 for (const CXXMethodDecl *O : Method->overridden_methods()) 15612 CheckOverridingFunctionExceptionSpec(Method, O); 15613 } 15614 } 15615 15616 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15617 /// 15618 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15619 SourceLocation DeclStart, Declarator &D, 15620 Expr *BitWidth, 15621 InClassInitStyle InitStyle, 15622 AccessSpecifier AS, 15623 const ParsedAttr &MSPropertyAttr) { 15624 IdentifierInfo *II = D.getIdentifier(); 15625 if (!II) { 15626 Diag(DeclStart, diag::err_anonymous_property); 15627 return nullptr; 15628 } 15629 SourceLocation Loc = D.getIdentifierLoc(); 15630 15631 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15632 QualType T = TInfo->getType(); 15633 if (getLangOpts().CPlusPlus) { 15634 CheckExtraCXXDefaultArguments(D); 15635 15636 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15637 UPPC_DataMemberType)) { 15638 D.setInvalidType(); 15639 T = Context.IntTy; 15640 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15641 } 15642 } 15643 15644 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15645 15646 if (D.getDeclSpec().isInlineSpecified()) 15647 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15648 << getLangOpts().CPlusPlus17; 15649 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15650 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15651 diag::err_invalid_thread) 15652 << DeclSpec::getSpecifierName(TSCS); 15653 15654 // Check to see if this name was declared as a member previously 15655 NamedDecl *PrevDecl = nullptr; 15656 LookupResult Previous(*this, II, Loc, LookupMemberName, 15657 ForVisibleRedeclaration); 15658 LookupName(Previous, S); 15659 switch (Previous.getResultKind()) { 15660 case LookupResult::Found: 15661 case LookupResult::FoundUnresolvedValue: 15662 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15663 break; 15664 15665 case LookupResult::FoundOverloaded: 15666 PrevDecl = Previous.getRepresentativeDecl(); 15667 break; 15668 15669 case LookupResult::NotFound: 15670 case LookupResult::NotFoundInCurrentInstantiation: 15671 case LookupResult::Ambiguous: 15672 break; 15673 } 15674 15675 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15676 // Maybe we will complain about the shadowed template parameter. 15677 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15678 // Just pretend that we didn't see the previous declaration. 15679 PrevDecl = nullptr; 15680 } 15681 15682 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15683 PrevDecl = nullptr; 15684 15685 SourceLocation TSSL = D.getBeginLoc(); 15686 MSPropertyDecl *NewPD = 15687 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 15688 MSPropertyAttr.getPropertyDataGetter(), 15689 MSPropertyAttr.getPropertyDataSetter()); 15690 ProcessDeclAttributes(TUScope, NewPD, D); 15691 NewPD->setAccess(AS); 15692 15693 if (NewPD->isInvalidDecl()) 15694 Record->setInvalidDecl(); 15695 15696 if (D.getDeclSpec().isModulePrivateSpecified()) 15697 NewPD->setModulePrivate(); 15698 15699 if (NewPD->isInvalidDecl() && PrevDecl) { 15700 // Don't introduce NewFD into scope; there's already something 15701 // with the same name in the same scope. 15702 } else if (II) { 15703 PushOnScopeChains(NewPD, S); 15704 } else 15705 Record->addDecl(NewPD); 15706 15707 return NewPD; 15708 } 15709