1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for C++ declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.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->getLocStart(), 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->getLocStart(), 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->getLocStart(), 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->getLocStart(), 147 diag::err_lambda_capture_default_arg); 148 } 149 } 150 151 void 152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 153 const CXXMethodDecl *Method) { 154 // If we have an MSAny spec already, don't bother. 155 if (!Method || ComputedEST == EST_MSAny) 156 return; 157 158 const FunctionProtoType *Proto 159 = Method->getType()->getAs<FunctionProtoType>(); 160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 161 if (!Proto) 162 return; 163 164 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 165 166 // If we have a throw-all spec at this point, ignore the function. 167 if (ComputedEST == EST_None) 168 return; 169 170 switch(EST) { 171 // If this function can throw any exceptions, make a note of that. 172 case EST_MSAny: 173 case EST_None: 174 ClearExceptions(); 175 ComputedEST = EST; 176 return; 177 // FIXME: If the call to this decl is using any of its default arguments, we 178 // need to search them for potentially-throwing calls. 179 // If this function has a basic noexcept, it doesn't affect the outcome. 180 case EST_BasicNoexcept: 181 return; 182 // If we're still at noexcept(true) and there's a nothrow() callee, 183 // change to that specification. 184 case EST_DynamicNone: 185 if (ComputedEST == EST_BasicNoexcept) 186 ComputedEST = EST_DynamicNone; 187 return; 188 // Check out noexcept specs. 189 case EST_ComputedNoexcept: 190 { 191 FunctionProtoType::NoexceptResult NR = 192 Proto->getNoexceptSpec(Self->Context); 193 assert(NR != FunctionProtoType::NR_NoNoexcept && 194 "Must have noexcept result for EST_ComputedNoexcept."); 195 assert(NR != FunctionProtoType::NR_Dependent && 196 "Should not generate implicit declarations for dependent cases, " 197 "and don't know how to handle them anyway."); 198 // noexcept(false) -> no spec on the new function 199 if (NR == FunctionProtoType::NR_Throw) { 200 ClearExceptions(); 201 ComputedEST = EST_None; 202 } 203 // noexcept(true) won't change anything either. 204 return; 205 } 206 default: 207 break; 208 } 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // C++11 [dcl.fct.default]p3 321 // A default argument expression [...] shall not be specified for a 322 // parameter pack. 323 if (Param->isParameterPack()) { 324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 325 << DefaultArg->getSourceRange(); 326 return; 327 } 328 329 // Check that the default argument is well-formed 330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 331 if (DefaultArgChecker.Visit(DefaultArg)) { 332 Param->setInvalidDecl(); 333 return; 334 } 335 336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 337 } 338 339 /// ActOnParamUnparsedDefaultArgument - We've seen a default 340 /// argument for a function parameter, but we can't parse it yet 341 /// because we're inside a class definition. Note that this default 342 /// argument will be parsed later. 343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 344 SourceLocation EqualLoc, 345 SourceLocation ArgLoc) { 346 if (!param) 347 return; 348 349 ParmVarDecl *Param = cast<ParmVarDecl>(param); 350 Param->setUnparsedDefaultArg(); 351 UnparsedDefaultArgLocs[Param] = ArgLoc; 352 } 353 354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 355 /// the default argument for the parameter param failed. 356 void Sema::ActOnParamDefaultArgumentError(Decl *param, 357 SourceLocation EqualLoc) { 358 if (!param) 359 return; 360 361 ParmVarDecl *Param = cast<ParmVarDecl>(param); 362 Param->setInvalidDecl(); 363 UnparsedDefaultArgLocs.erase(Param); 364 Param->setDefaultArg(new(Context) 365 OpaqueValueExpr(EqualLoc, 366 Param->getType().getNonReferenceType(), 367 VK_RValue)); 368 } 369 370 /// CheckExtraCXXDefaultArguments - Check for any extra default 371 /// arguments in the declarator, which is not a function declaration 372 /// or definition and therefore is not permitted to have default 373 /// arguments. This routine should be invoked for every declarator 374 /// that is not a function declaration or definition. 375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 376 // C++ [dcl.fct.default]p3 377 // A default argument expression shall be specified only in the 378 // parameter-declaration-clause of a function declaration or in a 379 // template-parameter (14.1). It shall not be specified for a 380 // parameter pack. If it is specified in a 381 // parameter-declaration-clause, it shall not occur within a 382 // declarator or abstract-declarator of a parameter-declaration. 383 bool MightBeFunction = D.isFunctionDeclarationContext(); 384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 385 DeclaratorChunk &chunk = D.getTypeObject(i); 386 if (chunk.Kind == DeclaratorChunk::Function) { 387 if (MightBeFunction) { 388 // This is a function declaration. It can have default arguments, but 389 // keep looking in case its return type is a function type with default 390 // arguments. 391 MightBeFunction = false; 392 continue; 393 } 394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 395 ++argIdx) { 396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 397 if (Param->hasUnparsedDefaultArg()) { 398 CachedTokens *Toks = 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 delete Toks; 408 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 409 } else if (Param->getDefaultArg()) { 410 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 411 << Param->getDefaultArg()->getSourceRange(); 412 Param->setDefaultArg(nullptr); 413 } 414 } 415 } else if (chunk.Kind != DeclaratorChunk::Paren) { 416 MightBeFunction = false; 417 } 418 } 419 } 420 421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 422 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 423 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 424 if (!PVD->hasDefaultArg()) 425 return false; 426 if (!PVD->hasInheritedDefaultArg()) 427 return true; 428 } 429 return false; 430 } 431 432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 433 /// function, once we already know that they have the same 434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 435 /// error, false otherwise. 436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 437 Scope *S) { 438 bool Invalid = false; 439 440 // The declaration context corresponding to the scope is the semantic 441 // parent, unless this is a local function declaration, in which case 442 // it is that surrounding function. 443 DeclContext *ScopeDC = New->isLocalExternDecl() 444 ? New->getLexicalDeclContext() 445 : New->getDeclContext(); 446 447 // Find the previous declaration for the purpose of default arguments. 448 FunctionDecl *PrevForDefaultArgs = Old; 449 for (/**/; PrevForDefaultArgs; 450 // Don't bother looking back past the latest decl if this is a local 451 // extern declaration; nothing else could work. 452 PrevForDefaultArgs = New->isLocalExternDecl() 453 ? nullptr 454 : PrevForDefaultArgs->getPreviousDecl()) { 455 // Ignore hidden declarations. 456 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 457 continue; 458 459 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 460 !New->isCXXClassMember()) { 461 // Ignore default arguments of old decl if they are not in 462 // the same scope and this is not an out-of-line definition of 463 // a member function. 464 continue; 465 } 466 467 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 468 // If only one of these is a local function declaration, then they are 469 // declared in different scopes, even though isDeclInScope may think 470 // they're in the same scope. (If both are local, the scope check is 471 // sufficent, and if neither is local, then they are in the same scope.) 472 continue; 473 } 474 475 // We found the right previous declaration. 476 break; 477 } 478 479 // C++ [dcl.fct.default]p4: 480 // For non-template functions, default arguments can be added in 481 // later declarations of a function in the same 482 // scope. Declarations in different scopes have completely 483 // distinct sets of default arguments. That is, declarations in 484 // inner scopes do not acquire default arguments from 485 // declarations in outer scopes, and vice versa. In a given 486 // function declaration, all parameters subsequent to a 487 // parameter with a default argument shall have default 488 // arguments supplied in this or previous declarations. A 489 // default argument shall not be redefined by a later 490 // declaration (not even to the same value). 491 // 492 // C++ [dcl.fct.default]p6: 493 // Except for member functions of class templates, the default arguments 494 // in a member function definition that appears outside of the class 495 // definition are added to the set of default arguments provided by the 496 // member function declaration in the class definition. 497 for (unsigned p = 0, NumParams = PrevForDefaultArgs 498 ? PrevForDefaultArgs->getNumParams() 499 : 0; 500 p < NumParams; ++p) { 501 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 502 ParmVarDecl *NewParam = New->getParamDecl(p); 503 504 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 505 bool NewParamHasDfl = NewParam->hasDefaultArg(); 506 507 if (OldParamHasDfl && NewParamHasDfl) { 508 unsigned DiagDefaultParamID = 509 diag::err_param_default_argument_redefinition; 510 511 // MSVC accepts that default parameters be redefined for member functions 512 // of template class. The new default parameter's value is ignored. 513 Invalid = true; 514 if (getLangOpts().MicrosoftExt) { 515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 516 if (MD && MD->getParent()->getDescribedClassTemplate()) { 517 // Merge the old default argument into the new parameter. 518 NewParam->setHasInheritedDefaultArg(); 519 if (OldParam->hasUninstantiatedDefaultArg()) 520 NewParam->setUninstantiatedDefaultArg( 521 OldParam->getUninstantiatedDefaultArg()); 522 else 523 NewParam->setDefaultArg(OldParam->getInit()); 524 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 525 Invalid = false; 526 } 527 } 528 529 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 530 // hint here. Alternatively, we could walk the type-source information 531 // for NewParam to find the last source location in the type... but it 532 // isn't worth the effort right now. This is the kind of test case that 533 // is hard to get right: 534 // int f(int); 535 // void g(int (*fp)(int) = f); 536 // void g(int (*fp)(int) = &f); 537 Diag(NewParam->getLocation(), DiagDefaultParamID) 538 << NewParam->getDefaultArgRange(); 539 540 // Look for the function declaration where the default argument was 541 // actually written, which may be a declaration prior to Old. 542 for (auto Older = PrevForDefaultArgs; 543 OldParam->hasInheritedDefaultArg(); /**/) { 544 Older = Older->getPreviousDecl(); 545 OldParam = Older->getParamDecl(p); 546 } 547 548 Diag(OldParam->getLocation(), diag::note_previous_definition) 549 << OldParam->getDefaultArgRange(); 550 } else if (OldParamHasDfl) { 551 // Merge the old default argument into the new parameter. 552 // It's important to use getInit() here; getDefaultArg() 553 // strips off any top-level ExprWithCleanups. 554 NewParam->setHasInheritedDefaultArg(); 555 if (OldParam->hasUnparsedDefaultArg()) 556 NewParam->setUnparsedDefaultArg(); 557 else if (OldParam->hasUninstantiatedDefaultArg()) 558 NewParam->setUninstantiatedDefaultArg( 559 OldParam->getUninstantiatedDefaultArg()); 560 else 561 NewParam->setDefaultArg(OldParam->getInit()); 562 } else if (NewParamHasDfl) { 563 if (New->getDescribedFunctionTemplate()) { 564 // Paragraph 4, quoted above, only applies to non-template functions. 565 Diag(NewParam->getLocation(), 566 diag::err_param_default_argument_template_redecl) 567 << NewParam->getDefaultArgRange(); 568 Diag(PrevForDefaultArgs->getLocation(), 569 diag::note_template_prev_declaration) 570 << false; 571 } else if (New->getTemplateSpecializationKind() 572 != TSK_ImplicitInstantiation && 573 New->getTemplateSpecializationKind() != TSK_Undeclared) { 574 // C++ [temp.expr.spec]p21: 575 // Default function arguments shall not be specified in a declaration 576 // or a definition for one of the following explicit specializations: 577 // - the explicit specialization of a function template; 578 // - the explicit specialization of a member function template; 579 // - the explicit specialization of a member function of a class 580 // template where the class template specialization to which the 581 // member function specialization belongs is implicitly 582 // instantiated. 583 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 584 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 585 << New->getDeclName() 586 << NewParam->getDefaultArgRange(); 587 } else if (New->getDeclContext()->isDependentContext()) { 588 // C++ [dcl.fct.default]p6 (DR217): 589 // Default arguments for a member function of a class template shall 590 // be specified on the initial declaration of the member function 591 // within the class template. 592 // 593 // Reading the tea leaves a bit in DR217 and its reference to DR205 594 // leads me to the conclusion that one cannot add default function 595 // arguments for an out-of-line definition of a member function of a 596 // dependent type. 597 int WhichKind = 2; 598 if (CXXRecordDecl *Record 599 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 600 if (Record->getDescribedClassTemplate()) 601 WhichKind = 0; 602 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 603 WhichKind = 1; 604 else 605 WhichKind = 2; 606 } 607 608 Diag(NewParam->getLocation(), 609 diag::err_param_default_argument_member_template_redecl) 610 << WhichKind 611 << NewParam->getDefaultArgRange(); 612 } 613 } 614 } 615 616 // DR1344: If a default argument is added outside a class definition and that 617 // default argument makes the function a special member function, the program 618 // is ill-formed. This can only happen for constructors. 619 if (isa<CXXConstructorDecl>(New) && 620 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 621 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 622 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 623 if (NewSM != OldSM) { 624 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 625 assert(NewParam->hasDefaultArg()); 626 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 627 << NewParam->getDefaultArgRange() << NewSM; 628 Diag(Old->getLocation(), diag::note_previous_declaration); 629 } 630 } 631 632 const FunctionDecl *Def; 633 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 634 // template has a constexpr specifier then all its declarations shall 635 // contain the constexpr specifier. 636 if (New->isConstexpr() != Old->isConstexpr()) { 637 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 638 << New << New->isConstexpr(); 639 Diag(Old->getLocation(), diag::note_previous_declaration); 640 Invalid = true; 641 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 642 Old->isDefined(Def)) { 643 // C++11 [dcl.fcn.spec]p4: 644 // If the definition of a function appears in a translation unit before its 645 // first declaration as inline, the program is ill-formed. 646 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 647 Diag(Def->getLocation(), diag::note_previous_definition); 648 Invalid = true; 649 } 650 651 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 652 // argument expression, that declaration shall be a definition and shall be 653 // the only declaration of the function or function template in the 654 // translation unit. 655 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 656 functionDeclHasDefaultArgument(Old)) { 657 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 658 Diag(Old->getLocation(), diag::note_previous_declaration); 659 Invalid = true; 660 } 661 662 return Invalid; 663 } 664 665 NamedDecl * 666 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 667 MultiTemplateParamsArg TemplateParamLists) { 668 assert(D.isDecompositionDeclarator()); 669 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 670 671 // The syntax only allows a decomposition declarator as a simple-declaration 672 // or a for-range-declaration, but we parse it in more cases than that. 673 if (!D.mayHaveDecompositionDeclarator()) { 674 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 675 << Decomp.getSourceRange(); 676 return nullptr; 677 } 678 679 if (!TemplateParamLists.empty()) { 680 // FIXME: There's no rule against this, but there are also no rules that 681 // would actually make it usable, so we reject it for now. 682 Diag(TemplateParamLists.front()->getTemplateLoc(), 683 diag::err_decomp_decl_template); 684 return nullptr; 685 } 686 687 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z 688 ? diag::warn_cxx14_compat_decomp_decl 689 : diag::ext_decomp_decl) 690 << Decomp.getSourceRange(); 691 692 // The semantic context is always just the current context. 693 DeclContext *const DC = CurContext; 694 695 // C++1z [dcl.dcl]/8: 696 // The decl-specifier-seq shall contain only the type-specifier auto 697 // and cv-qualifiers. 698 auto &DS = D.getDeclSpec(); 699 { 700 SmallVector<StringRef, 8> BadSpecifiers; 701 SmallVector<SourceLocation, 8> BadSpecifierLocs; 702 if (auto SCS = DS.getStorageClassSpec()) { 703 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 704 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 705 } 706 if (auto TSCS = DS.getThreadStorageClassSpec()) { 707 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 708 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 709 } 710 if (DS.isConstexprSpecified()) { 711 BadSpecifiers.push_back("constexpr"); 712 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 713 } 714 if (DS.isInlineSpecified()) { 715 BadSpecifiers.push_back("inline"); 716 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 717 } 718 if (!BadSpecifiers.empty()) { 719 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 720 Err << (int)BadSpecifiers.size() 721 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 722 // Don't add FixItHints to remove the specifiers; we do still respect 723 // them when building the underlying variable. 724 for (auto Loc : BadSpecifierLocs) 725 Err << SourceRange(Loc, Loc); 726 } 727 // We can't recover from it being declared as a typedef. 728 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 729 return nullptr; 730 } 731 732 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 733 QualType R = TInfo->getType(); 734 735 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 736 UPPC_DeclarationType)) 737 D.setInvalidType(); 738 739 // The syntax only allows a single ref-qualifier prior to the decomposition 740 // declarator. No other declarator chunks are permitted. Also check the type 741 // specifier here. 742 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 743 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 744 (D.getNumTypeObjects() == 1 && 745 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 746 Diag(Decomp.getLSquareLoc(), 747 (D.hasGroupingParens() || 748 (D.getNumTypeObjects() && 749 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 750 ? diag::err_decomp_decl_parens 751 : diag::err_decomp_decl_type) 752 << R; 753 754 // In most cases, there's no actual problem with an explicitly-specified 755 // type, but a function type won't work here, and ActOnVariableDeclarator 756 // shouldn't be called for such a type. 757 if (R->isFunctionType()) 758 D.setInvalidType(); 759 } 760 761 // Build the BindingDecls. 762 SmallVector<BindingDecl*, 8> Bindings; 763 764 // Build the BindingDecls. 765 for (auto &B : D.getDecompositionDeclarator().bindings()) { 766 // Check for name conflicts. 767 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 768 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 769 ForRedeclaration); 770 LookupName(Previous, S, 771 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 772 773 // It's not permitted to shadow a template parameter name. 774 if (Previous.isSingleResult() && 775 Previous.getFoundDecl()->isTemplateParameter()) { 776 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 777 Previous.getFoundDecl()); 778 Previous.clear(); 779 } 780 781 bool ConsiderLinkage = DC->isFunctionOrMethod() && 782 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 783 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 784 /*AllowInlineNamespace*/false); 785 if (!Previous.empty()) { 786 auto *Old = Previous.getRepresentativeDecl(); 787 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 788 Diag(Old->getLocation(), diag::note_previous_definition); 789 } 790 791 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 792 PushOnScopeChains(BD, S, true); 793 Bindings.push_back(BD); 794 ParsingInitForAutoVars.insert(BD); 795 } 796 797 // There are no prior lookup results for the variable itself, because it 798 // is unnamed. 799 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 800 Decomp.getLSquareLoc()); 801 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 802 803 // Build the variable that holds the non-decomposed object. 804 bool AddToScope = true; 805 NamedDecl *New = 806 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 807 MultiTemplateParamsArg(), AddToScope, Bindings); 808 CurContext->addHiddenDecl(New); 809 810 if (isInOpenMPDeclareTargetContext()) 811 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 812 813 return New; 814 } 815 816 static bool checkSimpleDecomposition( 817 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 818 QualType DecompType, llvm::APSInt NumElems, QualType ElemType, 819 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 820 if ((int64_t)Bindings.size() != NumElems) { 821 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 822 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 823 << (NumElems < Bindings.size()); 824 return true; 825 } 826 827 unsigned I = 0; 828 for (auto *B : Bindings) { 829 SourceLocation Loc = B->getLocation(); 830 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 831 if (E.isInvalid()) 832 return true; 833 E = GetInit(Loc, E.get(), I++); 834 if (E.isInvalid()) 835 return true; 836 B->setBinding(ElemType, E.get()); 837 } 838 839 return false; 840 } 841 842 static bool checkArrayLikeDecomposition(Sema &S, 843 ArrayRef<BindingDecl *> Bindings, 844 ValueDecl *Src, QualType DecompType, 845 llvm::APSInt NumElems, 846 QualType ElemType) { 847 return checkSimpleDecomposition( 848 S, Bindings, Src, DecompType, NumElems, ElemType, 849 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 850 ExprResult E = S.ActOnIntegerConstant(Loc, I); 851 if (E.isInvalid()) 852 return ExprError(); 853 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 854 }); 855 } 856 857 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 858 ValueDecl *Src, QualType DecompType, 859 const ConstantArrayType *CAT) { 860 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 861 llvm::APSInt(CAT->getSize()), 862 CAT->getElementType()); 863 } 864 865 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 866 ValueDecl *Src, QualType DecompType, 867 const VectorType *VT) { 868 return checkArrayLikeDecomposition( 869 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 870 S.Context.getQualifiedType(VT->getElementType(), 871 DecompType.getQualifiers())); 872 } 873 874 static bool checkComplexDecomposition(Sema &S, 875 ArrayRef<BindingDecl *> Bindings, 876 ValueDecl *Src, QualType DecompType, 877 const ComplexType *CT) { 878 return checkSimpleDecomposition( 879 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 880 S.Context.getQualifiedType(CT->getElementType(), 881 DecompType.getQualifiers()), 882 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 883 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 884 }); 885 } 886 887 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 888 TemplateArgumentListInfo &Args) { 889 SmallString<128> SS; 890 llvm::raw_svector_ostream OS(SS); 891 bool First = true; 892 for (auto &Arg : Args.arguments()) { 893 if (!First) 894 OS << ", "; 895 Arg.getArgument().print(PrintingPolicy, OS); 896 First = false; 897 } 898 return OS.str(); 899 } 900 901 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 902 SourceLocation Loc, StringRef Trait, 903 TemplateArgumentListInfo &Args, 904 unsigned DiagID) { 905 auto DiagnoseMissing = [&] { 906 if (DiagID) 907 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 908 Args); 909 return true; 910 }; 911 912 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 913 NamespaceDecl *Std = S.getStdNamespace(); 914 if (!Std) 915 return DiagnoseMissing(); 916 917 // Look up the trait itself, within namespace std. We can diagnose various 918 // problems with this lookup even if we've been asked to not diagnose a 919 // missing specialization, because this can only fail if the user has been 920 // declaring their own names in namespace std or we don't support the 921 // standard library implementation in use. 922 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 923 Loc, Sema::LookupOrdinaryName); 924 if (!S.LookupQualifiedName(Result, Std)) 925 return DiagnoseMissing(); 926 if (Result.isAmbiguous()) 927 return true; 928 929 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 930 if (!TraitTD) { 931 Result.suppressDiagnostics(); 932 NamedDecl *Found = *Result.begin(); 933 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 934 S.Diag(Found->getLocation(), diag::note_declared_at); 935 return true; 936 } 937 938 // Build the template-id. 939 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 940 if (TraitTy.isNull()) 941 return true; 942 if (!S.isCompleteType(Loc, TraitTy)) { 943 if (DiagID) 944 S.RequireCompleteType( 945 Loc, TraitTy, DiagID, 946 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 947 return true; 948 } 949 950 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 951 assert(RD && "specialization of class template is not a class?"); 952 953 // Look up the member of the trait type. 954 S.LookupQualifiedName(TraitMemberLookup, RD); 955 return TraitMemberLookup.isAmbiguous(); 956 } 957 958 static TemplateArgumentLoc 959 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 960 uint64_t I) { 961 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 962 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 963 } 964 965 static TemplateArgumentLoc 966 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 967 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 968 } 969 970 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 971 972 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 973 llvm::APSInt &Size) { 974 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated); 975 976 DeclarationName Value = S.PP.getIdentifierInfo("value"); 977 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 978 979 // Form template argument list for tuple_size<T>. 980 TemplateArgumentListInfo Args(Loc, Loc); 981 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 982 983 // If there's no tuple_size specialization, it's not tuple-like. 984 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 985 return IsTupleLike::NotTupleLike; 986 987 // FIXME: According to the standard, we're not supposed to diagnose if any 988 // of the steps below fail (or if lookup for ::value is ambiguous or otherwise 989 // results in an error), but this is subject to a pending CWG issue / NB 990 // comment, which says we do diagnose if tuple_size<T> is complete but 991 // tuple_size<T>::value is not an ICE. 992 993 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 994 LookupResult &R; 995 TemplateArgumentListInfo &Args; 996 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 997 : R(R), Args(Args) {} 998 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 999 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1000 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1001 } 1002 } Diagnoser(R, Args); 1003 1004 if (R.empty()) { 1005 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1006 return IsTupleLike::Error; 1007 } 1008 1009 ExprResult E = 1010 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1011 if (E.isInvalid()) 1012 return IsTupleLike::Error; 1013 1014 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1015 if (E.isInvalid()) 1016 return IsTupleLike::Error; 1017 1018 return IsTupleLike::TupleLike; 1019 } 1020 1021 /// \return std::tuple_element<I, T>::type. 1022 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1023 unsigned I, QualType T) { 1024 // Form template argument list for tuple_element<I, T>. 1025 TemplateArgumentListInfo Args(Loc, Loc); 1026 Args.addArgument( 1027 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1028 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1029 1030 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1031 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1032 if (lookupStdTypeTraitMember( 1033 S, R, Loc, "tuple_element", Args, 1034 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1035 return QualType(); 1036 1037 auto *TD = R.getAsSingle<TypeDecl>(); 1038 if (!TD) { 1039 R.suppressDiagnostics(); 1040 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1041 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1042 if (!R.empty()) 1043 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1044 return QualType(); 1045 } 1046 1047 return S.Context.getTypeDeclType(TD); 1048 } 1049 1050 namespace { 1051 struct BindingDiagnosticTrap { 1052 Sema &S; 1053 DiagnosticErrorTrap Trap; 1054 BindingDecl *BD; 1055 1056 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1057 : S(S), Trap(S.Diags), BD(BD) {} 1058 ~BindingDiagnosticTrap() { 1059 if (Trap.hasErrorOccurred()) 1060 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1061 } 1062 }; 1063 } 1064 1065 static bool checkTupleLikeDecomposition(Sema &S, 1066 ArrayRef<BindingDecl *> Bindings, 1067 VarDecl *Src, QualType DecompType, 1068 llvm::APSInt TupleSize) { 1069 if ((int64_t)Bindings.size() != TupleSize) { 1070 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1071 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1072 << (TupleSize < Bindings.size()); 1073 return true; 1074 } 1075 1076 if (Bindings.empty()) 1077 return false; 1078 1079 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1080 1081 // [dcl.decomp]p3: 1082 // The unqualified-id get is looked up in the scope of E by class member 1083 // access lookup 1084 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1085 bool UseMemberGet = false; 1086 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1087 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1088 S.LookupQualifiedName(MemberGet, RD); 1089 if (MemberGet.isAmbiguous()) 1090 return true; 1091 UseMemberGet = !MemberGet.empty(); 1092 S.FilterAcceptableTemplateNames(MemberGet); 1093 } 1094 1095 unsigned I = 0; 1096 for (auto *B : Bindings) { 1097 BindingDiagnosticTrap Trap(S, B); 1098 SourceLocation Loc = B->getLocation(); 1099 1100 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1101 if (E.isInvalid()) 1102 return true; 1103 1104 // e is an lvalue if the type of the entity is an lvalue reference and 1105 // an xvalue otherwise 1106 if (!Src->getType()->isLValueReferenceType()) 1107 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1108 E.get(), nullptr, VK_XValue); 1109 1110 TemplateArgumentListInfo Args(Loc, Loc); 1111 Args.addArgument( 1112 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1113 1114 if (UseMemberGet) { 1115 // if [lookup of member get] finds at least one declaration, the 1116 // initializer is e.get<i-1>(). 1117 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1118 CXXScopeSpec(), SourceLocation(), nullptr, 1119 MemberGet, &Args, nullptr); 1120 if (E.isInvalid()) 1121 return true; 1122 1123 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1124 } else { 1125 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1126 // in the associated namespaces. 1127 Expr *Get = UnresolvedLookupExpr::Create( 1128 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1129 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1130 UnresolvedSetIterator(), UnresolvedSetIterator()); 1131 1132 Expr *Arg = E.get(); 1133 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1134 } 1135 if (E.isInvalid()) 1136 return true; 1137 Expr *Init = E.get(); 1138 1139 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1140 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1141 if (T.isNull()) 1142 return true; 1143 1144 // each vi is a variable of type "reference to T" initialized with the 1145 // initializer, where the reference is an lvalue reference if the 1146 // initializer is an lvalue and an rvalue reference otherwise 1147 QualType RefType = 1148 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1149 if (RefType.isNull()) 1150 return true; 1151 auto *RefVD = VarDecl::Create( 1152 S.Context, Src->getDeclContext(), Loc, Loc, 1153 B->getDeclName().getAsIdentifierInfo(), RefType, 1154 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1155 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1156 RefVD->setTSCSpec(Src->getTSCSpec()); 1157 RefVD->setImplicit(); 1158 if (Src->isInlineSpecified()) 1159 RefVD->setInlineSpecified(); 1160 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1161 1162 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1163 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1164 InitializationSequence Seq(S, Entity, Kind, Init); 1165 E = Seq.Perform(S, Entity, Kind, Init); 1166 if (E.isInvalid()) 1167 return true; 1168 E = S.ActOnFinishFullExpr(E.get(), Loc); 1169 if (E.isInvalid()) 1170 return true; 1171 RefVD->setInit(E.get()); 1172 RefVD->checkInitIsICE(); 1173 1174 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1175 DeclarationNameInfo(B->getDeclName(), Loc), 1176 RefVD); 1177 if (E.isInvalid()) 1178 return true; 1179 1180 B->setBinding(T, E.get()); 1181 I++; 1182 } 1183 1184 return false; 1185 } 1186 1187 /// Find the base class to decompose in a built-in decomposition of a class type. 1188 /// This base class search is, unfortunately, not quite like any other that we 1189 /// perform anywhere else in C++. 1190 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1191 SourceLocation Loc, 1192 const CXXRecordDecl *RD, 1193 CXXCastPath &BasePath) { 1194 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1195 CXXBasePath &Path) { 1196 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1197 }; 1198 1199 const CXXRecordDecl *ClassWithFields = nullptr; 1200 if (RD->hasDirectFields()) 1201 // [dcl.decomp]p4: 1202 // Otherwise, all of E's non-static data members shall be public direct 1203 // members of E ... 1204 ClassWithFields = RD; 1205 else { 1206 // ... or of ... 1207 CXXBasePaths Paths; 1208 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1209 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1210 // If no classes have fields, just decompose RD itself. (This will work 1211 // if and only if zero bindings were provided.) 1212 return RD; 1213 } 1214 1215 CXXBasePath *BestPath = nullptr; 1216 for (auto &P : Paths) { 1217 if (!BestPath) 1218 BestPath = &P; 1219 else if (!S.Context.hasSameType(P.back().Base->getType(), 1220 BestPath->back().Base->getType())) { 1221 // ... the same ... 1222 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1223 << false << RD << BestPath->back().Base->getType() 1224 << P.back().Base->getType(); 1225 return nullptr; 1226 } else if (P.Access < BestPath->Access) { 1227 BestPath = &P; 1228 } 1229 } 1230 1231 // ... unambiguous ... 1232 QualType BaseType = BestPath->back().Base->getType(); 1233 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1234 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1235 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1236 return nullptr; 1237 } 1238 1239 // ... public base class of E. 1240 if (BestPath->Access != AS_public) { 1241 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1242 << RD << BaseType; 1243 for (auto &BS : *BestPath) { 1244 if (BS.Base->getAccessSpecifier() != AS_public) { 1245 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1246 << (BS.Base->getAccessSpecifier() == AS_protected) 1247 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1248 break; 1249 } 1250 } 1251 return nullptr; 1252 } 1253 1254 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1255 S.BuildBasePathArray(Paths, BasePath); 1256 } 1257 1258 // The above search did not check whether the selected class itself has base 1259 // classes with fields, so check that now. 1260 CXXBasePaths Paths; 1261 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1262 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1263 << (ClassWithFields == RD) << RD << ClassWithFields 1264 << Paths.front().back().Base->getType(); 1265 return nullptr; 1266 } 1267 1268 return ClassWithFields; 1269 } 1270 1271 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1272 ValueDecl *Src, QualType DecompType, 1273 const CXXRecordDecl *RD) { 1274 CXXCastPath BasePath; 1275 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1276 if (!RD) 1277 return true; 1278 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1279 DecompType.getQualifiers()); 1280 1281 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1282 unsigned NumFields = 1283 std::count_if(RD->field_begin(), RD->field_end(), 1284 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1285 assert(Bindings.size() != NumFields); 1286 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1287 << DecompType << (unsigned)Bindings.size() << NumFields 1288 << (NumFields < Bindings.size()); 1289 return true; 1290 }; 1291 1292 // all of E's non-static data members shall be public [...] members, 1293 // E shall not have an anonymous union member, ... 1294 unsigned I = 0; 1295 for (auto *FD : RD->fields()) { 1296 if (FD->isUnnamedBitfield()) 1297 continue; 1298 1299 if (FD->isAnonymousStructOrUnion()) { 1300 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1301 << DecompType << FD->getType()->isUnionType(); 1302 S.Diag(FD->getLocation(), diag::note_declared_at); 1303 return true; 1304 } 1305 1306 // We have a real field to bind. 1307 if (I >= Bindings.size()) 1308 return DiagnoseBadNumberOfBindings(); 1309 auto *B = Bindings[I++]; 1310 1311 SourceLocation Loc = B->getLocation(); 1312 if (FD->getAccess() != AS_public) { 1313 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1314 1315 // Determine whether the access specifier was explicit. 1316 bool Implicit = true; 1317 for (const auto *D : RD->decls()) { 1318 if (declaresSameEntity(D, FD)) 1319 break; 1320 if (isa<AccessSpecDecl>(D)) { 1321 Implicit = false; 1322 break; 1323 } 1324 } 1325 1326 S.Diag(FD->getLocation(), diag::note_access_natural) 1327 << (FD->getAccess() == AS_protected) << Implicit; 1328 return true; 1329 } 1330 1331 // Initialize the binding to Src.FD. 1332 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1333 if (E.isInvalid()) 1334 return true; 1335 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1336 VK_LValue, &BasePath); 1337 if (E.isInvalid()) 1338 return true; 1339 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1340 CXXScopeSpec(), FD, 1341 DeclAccessPair::make(FD, FD->getAccess()), 1342 DeclarationNameInfo(FD->getDeclName(), Loc)); 1343 if (E.isInvalid()) 1344 return true; 1345 1346 // If the type of the member is T, the referenced type is cv T, where cv is 1347 // the cv-qualification of the decomposition expression. 1348 // 1349 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1350 // 'const' to the type of the field. 1351 Qualifiers Q = DecompType.getQualifiers(); 1352 if (FD->isMutable()) 1353 Q.removeConst(); 1354 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1355 } 1356 1357 if (I != Bindings.size()) 1358 return DiagnoseBadNumberOfBindings(); 1359 1360 return false; 1361 } 1362 1363 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1364 QualType DecompType = DD->getType(); 1365 1366 // If the type of the decomposition is dependent, then so is the type of 1367 // each binding. 1368 if (DecompType->isDependentType()) { 1369 for (auto *B : DD->bindings()) 1370 B->setType(Context.DependentTy); 1371 return; 1372 } 1373 1374 DecompType = DecompType.getNonReferenceType(); 1375 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1376 1377 // C++1z [dcl.decomp]/2: 1378 // If E is an array type [...] 1379 // As an extension, we also support decomposition of built-in complex and 1380 // vector types. 1381 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1382 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1383 DD->setInvalidDecl(); 1384 return; 1385 } 1386 if (auto *VT = DecompType->getAs<VectorType>()) { 1387 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1388 DD->setInvalidDecl(); 1389 return; 1390 } 1391 if (auto *CT = DecompType->getAs<ComplexType>()) { 1392 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1393 DD->setInvalidDecl(); 1394 return; 1395 } 1396 1397 // C++1z [dcl.decomp]/3: 1398 // if the expression std::tuple_size<E>::value is a well-formed integral 1399 // constant expression, [...] 1400 llvm::APSInt TupleSize(32); 1401 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1402 case IsTupleLike::Error: 1403 DD->setInvalidDecl(); 1404 return; 1405 1406 case IsTupleLike::TupleLike: 1407 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1408 DD->setInvalidDecl(); 1409 return; 1410 1411 case IsTupleLike::NotTupleLike: 1412 break; 1413 } 1414 1415 // C++1z [dcl.dcl]/8: 1416 // [E shall be of array or non-union class type] 1417 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1418 if (!RD || RD->isUnion()) { 1419 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1420 << DD << !RD << DecompType; 1421 DD->setInvalidDecl(); 1422 return; 1423 } 1424 1425 // C++1z [dcl.decomp]/4: 1426 // all of E's non-static data members shall be [...] direct members of 1427 // E or of the same unambiguous public base class of E, ... 1428 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1429 DD->setInvalidDecl(); 1430 } 1431 1432 /// \brief Merge the exception specifications of two variable declarations. 1433 /// 1434 /// This is called when there's a redeclaration of a VarDecl. The function 1435 /// checks if the redeclaration might have an exception specification and 1436 /// validates compatibility and merges the specs if necessary. 1437 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1438 // Shortcut if exceptions are disabled. 1439 if (!getLangOpts().CXXExceptions) 1440 return; 1441 1442 assert(Context.hasSameType(New->getType(), Old->getType()) && 1443 "Should only be called if types are otherwise the same."); 1444 1445 QualType NewType = New->getType(); 1446 QualType OldType = Old->getType(); 1447 1448 // We're only interested in pointers and references to functions, as well 1449 // as pointers to member functions. 1450 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1451 NewType = R->getPointeeType(); 1452 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1453 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1454 NewType = P->getPointeeType(); 1455 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1456 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1457 NewType = M->getPointeeType(); 1458 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1459 } 1460 1461 if (!NewType->isFunctionProtoType()) 1462 return; 1463 1464 // There's lots of special cases for functions. For function pointers, system 1465 // libraries are hopefully not as broken so that we don't need these 1466 // workarounds. 1467 if (CheckEquivalentExceptionSpec( 1468 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1469 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1470 New->setInvalidDecl(); 1471 } 1472 } 1473 1474 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1475 /// function declaration are well-formed according to C++ 1476 /// [dcl.fct.default]. 1477 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1478 unsigned NumParams = FD->getNumParams(); 1479 unsigned p; 1480 1481 // Find first parameter with a default argument 1482 for (p = 0; p < NumParams; ++p) { 1483 ParmVarDecl *Param = FD->getParamDecl(p); 1484 if (Param->hasDefaultArg()) 1485 break; 1486 } 1487 1488 // C++11 [dcl.fct.default]p4: 1489 // In a given function declaration, each parameter subsequent to a parameter 1490 // with a default argument shall have a default argument supplied in this or 1491 // a previous declaration or shall be a function parameter pack. A default 1492 // argument shall not be redefined by a later declaration (not even to the 1493 // same value). 1494 unsigned LastMissingDefaultArg = 0; 1495 for (; p < NumParams; ++p) { 1496 ParmVarDecl *Param = FD->getParamDecl(p); 1497 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1498 if (Param->isInvalidDecl()) 1499 /* We already complained about this parameter. */; 1500 else if (Param->getIdentifier()) 1501 Diag(Param->getLocation(), 1502 diag::err_param_default_argument_missing_name) 1503 << Param->getIdentifier(); 1504 else 1505 Diag(Param->getLocation(), 1506 diag::err_param_default_argument_missing); 1507 1508 LastMissingDefaultArg = p; 1509 } 1510 } 1511 1512 if (LastMissingDefaultArg > 0) { 1513 // Some default arguments were missing. Clear out all of the 1514 // default arguments up to (and including) the last missing 1515 // default argument, so that we leave the function parameters 1516 // in a semantically valid state. 1517 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1518 ParmVarDecl *Param = FD->getParamDecl(p); 1519 if (Param->hasDefaultArg()) { 1520 Param->setDefaultArg(nullptr); 1521 } 1522 } 1523 } 1524 } 1525 1526 // CheckConstexprParameterTypes - Check whether a function's parameter types 1527 // are all literal types. If so, return true. If not, produce a suitable 1528 // diagnostic and return false. 1529 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1530 const FunctionDecl *FD) { 1531 unsigned ArgIndex = 0; 1532 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1533 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1534 e = FT->param_type_end(); 1535 i != e; ++i, ++ArgIndex) { 1536 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1537 SourceLocation ParamLoc = PD->getLocation(); 1538 if (!(*i)->isDependentType() && 1539 SemaRef.RequireLiteralType(ParamLoc, *i, 1540 diag::err_constexpr_non_literal_param, 1541 ArgIndex+1, PD->getSourceRange(), 1542 isa<CXXConstructorDecl>(FD))) 1543 return false; 1544 } 1545 return true; 1546 } 1547 1548 /// \brief Get diagnostic %select index for tag kind for 1549 /// record diagnostic message. 1550 /// WARNING: Indexes apply to particular diagnostics only! 1551 /// 1552 /// \returns diagnostic %select index. 1553 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1554 switch (Tag) { 1555 case TTK_Struct: return 0; 1556 case TTK_Interface: return 1; 1557 case TTK_Class: return 2; 1558 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1559 } 1560 } 1561 1562 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1563 // the requirements of a constexpr function definition or a constexpr 1564 // constructor definition. If so, return true. If not, produce appropriate 1565 // diagnostics and return false. 1566 // 1567 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1568 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1569 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1570 if (MD && MD->isInstance()) { 1571 // C++11 [dcl.constexpr]p4: 1572 // The definition of a constexpr constructor shall satisfy the following 1573 // constraints: 1574 // - the class shall not have any virtual base classes; 1575 const CXXRecordDecl *RD = MD->getParent(); 1576 if (RD->getNumVBases()) { 1577 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1578 << isa<CXXConstructorDecl>(NewFD) 1579 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1580 for (const auto &I : RD->vbases()) 1581 Diag(I.getLocStart(), 1582 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1583 return false; 1584 } 1585 } 1586 1587 if (!isa<CXXConstructorDecl>(NewFD)) { 1588 // C++11 [dcl.constexpr]p3: 1589 // The definition of a constexpr function shall satisfy the following 1590 // constraints: 1591 // - it shall not be virtual; 1592 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1593 if (Method && Method->isVirtual()) { 1594 Method = Method->getCanonicalDecl(); 1595 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1596 1597 // If it's not obvious why this function is virtual, find an overridden 1598 // function which uses the 'virtual' keyword. 1599 const CXXMethodDecl *WrittenVirtual = Method; 1600 while (!WrittenVirtual->isVirtualAsWritten()) 1601 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1602 if (WrittenVirtual != Method) 1603 Diag(WrittenVirtual->getLocation(), 1604 diag::note_overridden_virtual_function); 1605 return false; 1606 } 1607 1608 // - its return type shall be a literal type; 1609 QualType RT = NewFD->getReturnType(); 1610 if (!RT->isDependentType() && 1611 RequireLiteralType(NewFD->getLocation(), RT, 1612 diag::err_constexpr_non_literal_return)) 1613 return false; 1614 } 1615 1616 // - each of its parameter types shall be a literal type; 1617 if (!CheckConstexprParameterTypes(*this, NewFD)) 1618 return false; 1619 1620 return true; 1621 } 1622 1623 /// Check the given declaration statement is legal within a constexpr function 1624 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1625 /// 1626 /// \return true if the body is OK (maybe only as an extension), false if we 1627 /// have diagnosed a problem. 1628 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1629 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1630 // C++11 [dcl.constexpr]p3 and p4: 1631 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1632 // contain only 1633 for (const auto *DclIt : DS->decls()) { 1634 switch (DclIt->getKind()) { 1635 case Decl::StaticAssert: 1636 case Decl::Using: 1637 case Decl::UsingShadow: 1638 case Decl::UsingDirective: 1639 case Decl::UnresolvedUsingTypename: 1640 case Decl::UnresolvedUsingValue: 1641 // - static_assert-declarations 1642 // - using-declarations, 1643 // - using-directives, 1644 continue; 1645 1646 case Decl::Typedef: 1647 case Decl::TypeAlias: { 1648 // - typedef declarations and alias-declarations that do not define 1649 // classes or enumerations, 1650 const auto *TN = cast<TypedefNameDecl>(DclIt); 1651 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1652 // Don't allow variably-modified types in constexpr functions. 1653 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1654 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1655 << TL.getSourceRange() << TL.getType() 1656 << isa<CXXConstructorDecl>(Dcl); 1657 return false; 1658 } 1659 continue; 1660 } 1661 1662 case Decl::Enum: 1663 case Decl::CXXRecord: 1664 // C++1y allows types to be defined, not just declared. 1665 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1666 SemaRef.Diag(DS->getLocStart(), 1667 SemaRef.getLangOpts().CPlusPlus14 1668 ? diag::warn_cxx11_compat_constexpr_type_definition 1669 : diag::ext_constexpr_type_definition) 1670 << isa<CXXConstructorDecl>(Dcl); 1671 continue; 1672 1673 case Decl::EnumConstant: 1674 case Decl::IndirectField: 1675 case Decl::ParmVar: 1676 // These can only appear with other declarations which are banned in 1677 // C++11 and permitted in C++1y, so ignore them. 1678 continue; 1679 1680 case Decl::Var: 1681 case Decl::Decomposition: { 1682 // C++1y [dcl.constexpr]p3 allows anything except: 1683 // a definition of a variable of non-literal type or of static or 1684 // thread storage duration or for which no initialization is performed. 1685 const auto *VD = cast<VarDecl>(DclIt); 1686 if (VD->isThisDeclarationADefinition()) { 1687 if (VD->isStaticLocal()) { 1688 SemaRef.Diag(VD->getLocation(), 1689 diag::err_constexpr_local_var_static) 1690 << isa<CXXConstructorDecl>(Dcl) 1691 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1692 return false; 1693 } 1694 if (!VD->getType()->isDependentType() && 1695 SemaRef.RequireLiteralType( 1696 VD->getLocation(), VD->getType(), 1697 diag::err_constexpr_local_var_non_literal_type, 1698 isa<CXXConstructorDecl>(Dcl))) 1699 return false; 1700 if (!VD->getType()->isDependentType() && 1701 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1702 SemaRef.Diag(VD->getLocation(), 1703 diag::err_constexpr_local_var_no_init) 1704 << isa<CXXConstructorDecl>(Dcl); 1705 return false; 1706 } 1707 } 1708 SemaRef.Diag(VD->getLocation(), 1709 SemaRef.getLangOpts().CPlusPlus14 1710 ? diag::warn_cxx11_compat_constexpr_local_var 1711 : diag::ext_constexpr_local_var) 1712 << isa<CXXConstructorDecl>(Dcl); 1713 continue; 1714 } 1715 1716 case Decl::NamespaceAlias: 1717 case Decl::Function: 1718 // These are disallowed in C++11 and permitted in C++1y. Allow them 1719 // everywhere as an extension. 1720 if (!Cxx1yLoc.isValid()) 1721 Cxx1yLoc = DS->getLocStart(); 1722 continue; 1723 1724 default: 1725 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1726 << isa<CXXConstructorDecl>(Dcl); 1727 return false; 1728 } 1729 } 1730 1731 return true; 1732 } 1733 1734 /// Check that the given field is initialized within a constexpr constructor. 1735 /// 1736 /// \param Dcl The constexpr constructor being checked. 1737 /// \param Field The field being checked. This may be a member of an anonymous 1738 /// struct or union nested within the class being checked. 1739 /// \param Inits All declarations, including anonymous struct/union members and 1740 /// indirect members, for which any initialization was provided. 1741 /// \param Diagnosed Set to true if an error is produced. 1742 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1743 const FunctionDecl *Dcl, 1744 FieldDecl *Field, 1745 llvm::SmallSet<Decl*, 16> &Inits, 1746 bool &Diagnosed) { 1747 if (Field->isInvalidDecl()) 1748 return; 1749 1750 if (Field->isUnnamedBitfield()) 1751 return; 1752 1753 // Anonymous unions with no variant members and empty anonymous structs do not 1754 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1755 // indirect fields don't need initializing. 1756 if (Field->isAnonymousStructOrUnion() && 1757 (Field->getType()->isUnionType() 1758 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1759 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1760 return; 1761 1762 if (!Inits.count(Field)) { 1763 if (!Diagnosed) { 1764 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1765 Diagnosed = true; 1766 } 1767 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1768 } else if (Field->isAnonymousStructOrUnion()) { 1769 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1770 for (auto *I : RD->fields()) 1771 // If an anonymous union contains an anonymous struct of which any member 1772 // is initialized, all members must be initialized. 1773 if (!RD->isUnion() || Inits.count(I)) 1774 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1775 } 1776 } 1777 1778 /// Check the provided statement is allowed in a constexpr function 1779 /// definition. 1780 static bool 1781 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1782 SmallVectorImpl<SourceLocation> &ReturnStmts, 1783 SourceLocation &Cxx1yLoc) { 1784 // - its function-body shall be [...] a compound-statement that contains only 1785 switch (S->getStmtClass()) { 1786 case Stmt::NullStmtClass: 1787 // - null statements, 1788 return true; 1789 1790 case Stmt::DeclStmtClass: 1791 // - static_assert-declarations 1792 // - using-declarations, 1793 // - using-directives, 1794 // - typedef declarations and alias-declarations that do not define 1795 // classes or enumerations, 1796 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1797 return false; 1798 return true; 1799 1800 case Stmt::ReturnStmtClass: 1801 // - and exactly one return statement; 1802 if (isa<CXXConstructorDecl>(Dcl)) { 1803 // C++1y allows return statements in constexpr constructors. 1804 if (!Cxx1yLoc.isValid()) 1805 Cxx1yLoc = S->getLocStart(); 1806 return true; 1807 } 1808 1809 ReturnStmts.push_back(S->getLocStart()); 1810 return true; 1811 1812 case Stmt::CompoundStmtClass: { 1813 // C++1y allows compound-statements. 1814 if (!Cxx1yLoc.isValid()) 1815 Cxx1yLoc = S->getLocStart(); 1816 1817 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1818 for (auto *BodyIt : CompStmt->body()) { 1819 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1820 Cxx1yLoc)) 1821 return false; 1822 } 1823 return true; 1824 } 1825 1826 case Stmt::AttributedStmtClass: 1827 if (!Cxx1yLoc.isValid()) 1828 Cxx1yLoc = S->getLocStart(); 1829 return true; 1830 1831 case Stmt::IfStmtClass: { 1832 // C++1y allows if-statements. 1833 if (!Cxx1yLoc.isValid()) 1834 Cxx1yLoc = S->getLocStart(); 1835 1836 IfStmt *If = cast<IfStmt>(S); 1837 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1838 Cxx1yLoc)) 1839 return false; 1840 if (If->getElse() && 1841 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1842 Cxx1yLoc)) 1843 return false; 1844 return true; 1845 } 1846 1847 case Stmt::WhileStmtClass: 1848 case Stmt::DoStmtClass: 1849 case Stmt::ForStmtClass: 1850 case Stmt::CXXForRangeStmtClass: 1851 case Stmt::ContinueStmtClass: 1852 // C++1y allows all of these. We don't allow them as extensions in C++11, 1853 // because they don't make sense without variable mutation. 1854 if (!SemaRef.getLangOpts().CPlusPlus14) 1855 break; 1856 if (!Cxx1yLoc.isValid()) 1857 Cxx1yLoc = S->getLocStart(); 1858 for (Stmt *SubStmt : S->children()) 1859 if (SubStmt && 1860 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1861 Cxx1yLoc)) 1862 return false; 1863 return true; 1864 1865 case Stmt::SwitchStmtClass: 1866 case Stmt::CaseStmtClass: 1867 case Stmt::DefaultStmtClass: 1868 case Stmt::BreakStmtClass: 1869 // C++1y allows switch-statements, and since they don't need variable 1870 // mutation, we can reasonably allow them in C++11 as an extension. 1871 if (!Cxx1yLoc.isValid()) 1872 Cxx1yLoc = S->getLocStart(); 1873 for (Stmt *SubStmt : S->children()) 1874 if (SubStmt && 1875 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1876 Cxx1yLoc)) 1877 return false; 1878 return true; 1879 1880 default: 1881 if (!isa<Expr>(S)) 1882 break; 1883 1884 // C++1y allows expression-statements. 1885 if (!Cxx1yLoc.isValid()) 1886 Cxx1yLoc = S->getLocStart(); 1887 return true; 1888 } 1889 1890 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1891 << isa<CXXConstructorDecl>(Dcl); 1892 return false; 1893 } 1894 1895 /// Check the body for the given constexpr function declaration only contains 1896 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1897 /// 1898 /// \return true if the body is OK, false if we have diagnosed a problem. 1899 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1900 if (isa<CXXTryStmt>(Body)) { 1901 // C++11 [dcl.constexpr]p3: 1902 // The definition of a constexpr function shall satisfy the following 1903 // constraints: [...] 1904 // - its function-body shall be = delete, = default, or a 1905 // compound-statement 1906 // 1907 // C++11 [dcl.constexpr]p4: 1908 // In the definition of a constexpr constructor, [...] 1909 // - its function-body shall not be a function-try-block; 1910 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1911 << isa<CXXConstructorDecl>(Dcl); 1912 return false; 1913 } 1914 1915 SmallVector<SourceLocation, 4> ReturnStmts; 1916 1917 // - its function-body shall be [...] a compound-statement that contains only 1918 // [... list of cases ...] 1919 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1920 SourceLocation Cxx1yLoc; 1921 for (auto *BodyIt : CompBody->body()) { 1922 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1923 return false; 1924 } 1925 1926 if (Cxx1yLoc.isValid()) 1927 Diag(Cxx1yLoc, 1928 getLangOpts().CPlusPlus14 1929 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1930 : diag::ext_constexpr_body_invalid_stmt) 1931 << isa<CXXConstructorDecl>(Dcl); 1932 1933 if (const CXXConstructorDecl *Constructor 1934 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1935 const CXXRecordDecl *RD = Constructor->getParent(); 1936 // DR1359: 1937 // - every non-variant non-static data member and base class sub-object 1938 // shall be initialized; 1939 // DR1460: 1940 // - if the class is a union having variant members, exactly one of them 1941 // shall be initialized; 1942 if (RD->isUnion()) { 1943 if (Constructor->getNumCtorInitializers() == 0 && 1944 RD->hasVariantMembers()) { 1945 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1946 return false; 1947 } 1948 } else if (!Constructor->isDependentContext() && 1949 !Constructor->isDelegatingConstructor()) { 1950 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1951 1952 // Skip detailed checking if we have enough initializers, and we would 1953 // allow at most one initializer per member. 1954 bool AnyAnonStructUnionMembers = false; 1955 unsigned Fields = 0; 1956 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1957 E = RD->field_end(); I != E; ++I, ++Fields) { 1958 if (I->isAnonymousStructOrUnion()) { 1959 AnyAnonStructUnionMembers = true; 1960 break; 1961 } 1962 } 1963 // DR1460: 1964 // - if the class is a union-like class, but is not a union, for each of 1965 // its anonymous union members having variant members, exactly one of 1966 // them shall be initialized; 1967 if (AnyAnonStructUnionMembers || 1968 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1969 // Check initialization of non-static data members. Base classes are 1970 // always initialized so do not need to be checked. Dependent bases 1971 // might not have initializers in the member initializer list. 1972 llvm::SmallSet<Decl*, 16> Inits; 1973 for (const auto *I: Constructor->inits()) { 1974 if (FieldDecl *FD = I->getMember()) 1975 Inits.insert(FD); 1976 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1977 Inits.insert(ID->chain_begin(), ID->chain_end()); 1978 } 1979 1980 bool Diagnosed = false; 1981 for (auto *I : RD->fields()) 1982 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1983 if (Diagnosed) 1984 return false; 1985 } 1986 } 1987 } else { 1988 if (ReturnStmts.empty()) { 1989 // C++1y doesn't require constexpr functions to contain a 'return' 1990 // statement. We still do, unless the return type might be void, because 1991 // otherwise if there's no return statement, the function cannot 1992 // be used in a core constant expression. 1993 bool OK = getLangOpts().CPlusPlus14 && 1994 (Dcl->getReturnType()->isVoidType() || 1995 Dcl->getReturnType()->isDependentType()); 1996 Diag(Dcl->getLocation(), 1997 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1998 : diag::err_constexpr_body_no_return); 1999 if (!OK) 2000 return false; 2001 } else if (ReturnStmts.size() > 1) { 2002 Diag(ReturnStmts.back(), 2003 getLangOpts().CPlusPlus14 2004 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2005 : diag::ext_constexpr_body_multiple_return); 2006 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2007 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2008 } 2009 } 2010 2011 // C++11 [dcl.constexpr]p5: 2012 // if no function argument values exist such that the function invocation 2013 // substitution would produce a constant expression, the program is 2014 // ill-formed; no diagnostic required. 2015 // C++11 [dcl.constexpr]p3: 2016 // - every constructor call and implicit conversion used in initializing the 2017 // return value shall be one of those allowed in a constant expression. 2018 // C++11 [dcl.constexpr]p4: 2019 // - every constructor involved in initializing non-static data members and 2020 // base class sub-objects shall be a constexpr constructor. 2021 SmallVector<PartialDiagnosticAt, 8> Diags; 2022 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2023 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2024 << isa<CXXConstructorDecl>(Dcl); 2025 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2026 Diag(Diags[I].first, Diags[I].second); 2027 // Don't return false here: we allow this for compatibility in 2028 // system headers. 2029 } 2030 2031 return true; 2032 } 2033 2034 /// isCurrentClassName - Determine whether the identifier II is the 2035 /// name of the class type currently being defined. In the case of 2036 /// nested classes, this will only return true if II is the name of 2037 /// the innermost class. 2038 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2039 const CXXScopeSpec *SS) { 2040 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2041 2042 CXXRecordDecl *CurDecl; 2043 if (SS && SS->isSet() && !SS->isInvalid()) { 2044 DeclContext *DC = computeDeclContext(*SS, true); 2045 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2046 } else 2047 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2048 2049 if (CurDecl && CurDecl->getIdentifier()) 2050 return &II == CurDecl->getIdentifier(); 2051 return false; 2052 } 2053 2054 /// \brief Determine whether the identifier II is a typo for the name of 2055 /// the class type currently being defined. If so, update it to the identifier 2056 /// that should have been used. 2057 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2058 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2059 2060 if (!getLangOpts().SpellChecking) 2061 return false; 2062 2063 CXXRecordDecl *CurDecl; 2064 if (SS && SS->isSet() && !SS->isInvalid()) { 2065 DeclContext *DC = computeDeclContext(*SS, true); 2066 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2067 } else 2068 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2069 2070 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2071 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2072 < II->getLength()) { 2073 II = CurDecl->getIdentifier(); 2074 return true; 2075 } 2076 2077 return false; 2078 } 2079 2080 /// \brief Determine whether the given class is a base class of the given 2081 /// class, including looking at dependent bases. 2082 static bool findCircularInheritance(const CXXRecordDecl *Class, 2083 const CXXRecordDecl *Current) { 2084 SmallVector<const CXXRecordDecl*, 8> Queue; 2085 2086 Class = Class->getCanonicalDecl(); 2087 while (true) { 2088 for (const auto &I : Current->bases()) { 2089 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2090 if (!Base) 2091 continue; 2092 2093 Base = Base->getDefinition(); 2094 if (!Base) 2095 continue; 2096 2097 if (Base->getCanonicalDecl() == Class) 2098 return true; 2099 2100 Queue.push_back(Base); 2101 } 2102 2103 if (Queue.empty()) 2104 return false; 2105 2106 Current = Queue.pop_back_val(); 2107 } 2108 2109 return false; 2110 } 2111 2112 /// \brief Check the validity of a C++ base class specifier. 2113 /// 2114 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2115 /// and returns NULL otherwise. 2116 CXXBaseSpecifier * 2117 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2118 SourceRange SpecifierRange, 2119 bool Virtual, AccessSpecifier Access, 2120 TypeSourceInfo *TInfo, 2121 SourceLocation EllipsisLoc) { 2122 QualType BaseType = TInfo->getType(); 2123 2124 // C++ [class.union]p1: 2125 // A union shall not have base classes. 2126 if (Class->isUnion()) { 2127 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2128 << SpecifierRange; 2129 return nullptr; 2130 } 2131 2132 if (EllipsisLoc.isValid() && 2133 !TInfo->getType()->containsUnexpandedParameterPack()) { 2134 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2135 << TInfo->getTypeLoc().getSourceRange(); 2136 EllipsisLoc = SourceLocation(); 2137 } 2138 2139 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2140 2141 if (BaseType->isDependentType()) { 2142 // Make sure that we don't have circular inheritance among our dependent 2143 // bases. For non-dependent bases, the check for completeness below handles 2144 // this. 2145 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2146 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2147 ((BaseDecl = BaseDecl->getDefinition()) && 2148 findCircularInheritance(Class, BaseDecl))) { 2149 Diag(BaseLoc, diag::err_circular_inheritance) 2150 << BaseType << Context.getTypeDeclType(Class); 2151 2152 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2153 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2154 << BaseType; 2155 2156 return nullptr; 2157 } 2158 } 2159 2160 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2161 Class->getTagKind() == TTK_Class, 2162 Access, TInfo, EllipsisLoc); 2163 } 2164 2165 // Base specifiers must be record types. 2166 if (!BaseType->isRecordType()) { 2167 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2168 return nullptr; 2169 } 2170 2171 // C++ [class.union]p1: 2172 // A union shall not be used as a base class. 2173 if (BaseType->isUnionType()) { 2174 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2175 return nullptr; 2176 } 2177 2178 // For the MS ABI, propagate DLL attributes to base class templates. 2179 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2180 if (Attr *ClassAttr = getDLLAttr(Class)) { 2181 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2182 BaseType->getAsCXXRecordDecl())) { 2183 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2184 BaseLoc); 2185 } 2186 } 2187 } 2188 2189 // C++ [class.derived]p2: 2190 // The class-name in a base-specifier shall not be an incompletely 2191 // defined class. 2192 if (RequireCompleteType(BaseLoc, BaseType, 2193 diag::err_incomplete_base_class, SpecifierRange)) { 2194 Class->setInvalidDecl(); 2195 return nullptr; 2196 } 2197 2198 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2199 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2200 assert(BaseDecl && "Record type has no declaration"); 2201 BaseDecl = BaseDecl->getDefinition(); 2202 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2203 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2204 assert(CXXBaseDecl && "Base type is not a C++ type"); 2205 2206 // A class which contains a flexible array member is not suitable for use as a 2207 // base class: 2208 // - If the layout determines that a base comes before another base, 2209 // the flexible array member would index into the subsequent base. 2210 // - If the layout determines that base comes before the derived class, 2211 // the flexible array member would index into the derived class. 2212 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2213 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2214 << CXXBaseDecl->getDeclName(); 2215 return nullptr; 2216 } 2217 2218 // C++ [class]p3: 2219 // If a class is marked final and it appears as a base-type-specifier in 2220 // base-clause, the program is ill-formed. 2221 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2222 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2223 << CXXBaseDecl->getDeclName() 2224 << FA->isSpelledAsSealed(); 2225 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2226 << CXXBaseDecl->getDeclName() << FA->getRange(); 2227 return nullptr; 2228 } 2229 2230 if (BaseDecl->isInvalidDecl()) 2231 Class->setInvalidDecl(); 2232 2233 // Create the base specifier. 2234 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2235 Class->getTagKind() == TTK_Class, 2236 Access, TInfo, EllipsisLoc); 2237 } 2238 2239 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2240 /// one entry in the base class list of a class specifier, for 2241 /// example: 2242 /// class foo : public bar, virtual private baz { 2243 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2244 BaseResult 2245 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2246 ParsedAttributes &Attributes, 2247 bool Virtual, AccessSpecifier Access, 2248 ParsedType basetype, SourceLocation BaseLoc, 2249 SourceLocation EllipsisLoc) { 2250 if (!classdecl) 2251 return true; 2252 2253 AdjustDeclIfTemplate(classdecl); 2254 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2255 if (!Class) 2256 return true; 2257 2258 // We haven't yet attached the base specifiers. 2259 Class->setIsParsingBaseSpecifiers(); 2260 2261 // We do not support any C++11 attributes on base-specifiers yet. 2262 // Diagnose any attributes we see. 2263 if (!Attributes.empty()) { 2264 for (AttributeList *Attr = Attributes.getList(); Attr; 2265 Attr = Attr->getNext()) { 2266 if (Attr->isInvalid() || 2267 Attr->getKind() == AttributeList::IgnoredAttribute) 2268 continue; 2269 Diag(Attr->getLoc(), 2270 Attr->getKind() == AttributeList::UnknownAttribute 2271 ? diag::warn_unknown_attribute_ignored 2272 : diag::err_base_specifier_attribute) 2273 << Attr->getName(); 2274 } 2275 } 2276 2277 TypeSourceInfo *TInfo = nullptr; 2278 GetTypeFromParser(basetype, &TInfo); 2279 2280 if (EllipsisLoc.isInvalid() && 2281 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2282 UPPC_BaseType)) 2283 return true; 2284 2285 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2286 Virtual, Access, TInfo, 2287 EllipsisLoc)) 2288 return BaseSpec; 2289 else 2290 Class->setInvalidDecl(); 2291 2292 return true; 2293 } 2294 2295 /// Use small set to collect indirect bases. As this is only used 2296 /// locally, there's no need to abstract the small size parameter. 2297 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2298 2299 /// \brief Recursively add the bases of Type. Don't add Type itself. 2300 static void 2301 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2302 const QualType &Type) 2303 { 2304 // Even though the incoming type is a base, it might not be 2305 // a class -- it could be a template parm, for instance. 2306 if (auto Rec = Type->getAs<RecordType>()) { 2307 auto Decl = Rec->getAsCXXRecordDecl(); 2308 2309 // Iterate over its bases. 2310 for (const auto &BaseSpec : Decl->bases()) { 2311 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2312 .getUnqualifiedType(); 2313 if (Set.insert(Base).second) 2314 // If we've not already seen it, recurse. 2315 NoteIndirectBases(Context, Set, Base); 2316 } 2317 } 2318 } 2319 2320 /// \brief Performs the actual work of attaching the given base class 2321 /// specifiers to a C++ class. 2322 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2323 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2324 if (Bases.empty()) 2325 return false; 2326 2327 // Used to keep track of which base types we have already seen, so 2328 // that we can properly diagnose redundant direct base types. Note 2329 // that the key is always the unqualified canonical type of the base 2330 // class. 2331 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2332 2333 // Used to track indirect bases so we can see if a direct base is 2334 // ambiguous. 2335 IndirectBaseSet IndirectBaseTypes; 2336 2337 // Copy non-redundant base specifiers into permanent storage. 2338 unsigned NumGoodBases = 0; 2339 bool Invalid = false; 2340 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2341 QualType NewBaseType 2342 = Context.getCanonicalType(Bases[idx]->getType()); 2343 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2344 2345 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2346 if (KnownBase) { 2347 // C++ [class.mi]p3: 2348 // A class shall not be specified as a direct base class of a 2349 // derived class more than once. 2350 Diag(Bases[idx]->getLocStart(), 2351 diag::err_duplicate_base_class) 2352 << KnownBase->getType() 2353 << Bases[idx]->getSourceRange(); 2354 2355 // Delete the duplicate base class specifier; we're going to 2356 // overwrite its pointer later. 2357 Context.Deallocate(Bases[idx]); 2358 2359 Invalid = true; 2360 } else { 2361 // Okay, add this new base class. 2362 KnownBase = Bases[idx]; 2363 Bases[NumGoodBases++] = Bases[idx]; 2364 2365 // Note this base's direct & indirect bases, if there could be ambiguity. 2366 if (Bases.size() > 1) 2367 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2368 2369 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2370 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2371 if (Class->isInterface() && 2372 (!RD->isInterface() || 2373 KnownBase->getAccessSpecifier() != AS_public)) { 2374 // The Microsoft extension __interface does not permit bases that 2375 // are not themselves public interfaces. 2376 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2377 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 2378 << RD->getSourceRange(); 2379 Invalid = true; 2380 } 2381 if (RD->hasAttr<WeakAttr>()) 2382 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2383 } 2384 } 2385 } 2386 2387 // Attach the remaining base class specifiers to the derived class. 2388 Class->setBases(Bases.data(), NumGoodBases); 2389 2390 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2391 // Check whether this direct base is inaccessible due to ambiguity. 2392 QualType BaseType = Bases[idx]->getType(); 2393 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2394 .getUnqualifiedType(); 2395 2396 if (IndirectBaseTypes.count(CanonicalBase)) { 2397 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2398 /*DetectVirtual=*/true); 2399 bool found 2400 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2401 assert(found); 2402 (void)found; 2403 2404 if (Paths.isAmbiguous(CanonicalBase)) 2405 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2406 << BaseType << getAmbiguousPathsDisplayString(Paths) 2407 << Bases[idx]->getSourceRange(); 2408 else 2409 assert(Bases[idx]->isVirtual()); 2410 } 2411 2412 // Delete the base class specifier, since its data has been copied 2413 // into the CXXRecordDecl. 2414 Context.Deallocate(Bases[idx]); 2415 } 2416 2417 return Invalid; 2418 } 2419 2420 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2421 /// class, after checking whether there are any duplicate base 2422 /// classes. 2423 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2424 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2425 if (!ClassDecl || Bases.empty()) 2426 return; 2427 2428 AdjustDeclIfTemplate(ClassDecl); 2429 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2430 } 2431 2432 /// \brief Determine whether the type \p Derived is a C++ class that is 2433 /// derived from the type \p Base. 2434 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2435 if (!getLangOpts().CPlusPlus) 2436 return false; 2437 2438 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2439 if (!DerivedRD) 2440 return false; 2441 2442 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2443 if (!BaseRD) 2444 return false; 2445 2446 // If either the base or the derived type is invalid, don't try to 2447 // check whether one is derived from the other. 2448 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2449 return false; 2450 2451 // FIXME: In a modules build, do we need the entire path to be visible for us 2452 // to be able to use the inheritance relationship? 2453 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2454 return false; 2455 2456 return DerivedRD->isDerivedFrom(BaseRD); 2457 } 2458 2459 /// \brief Determine whether the type \p Derived is a C++ class that is 2460 /// derived from the type \p Base. 2461 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2462 CXXBasePaths &Paths) { 2463 if (!getLangOpts().CPlusPlus) 2464 return false; 2465 2466 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2467 if (!DerivedRD) 2468 return false; 2469 2470 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2471 if (!BaseRD) 2472 return false; 2473 2474 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2475 return false; 2476 2477 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2478 } 2479 2480 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2481 CXXCastPath &BasePathArray) { 2482 assert(BasePathArray.empty() && "Base path array must be empty!"); 2483 assert(Paths.isRecordingPaths() && "Must record paths!"); 2484 2485 const CXXBasePath &Path = Paths.front(); 2486 2487 // We first go backward and check if we have a virtual base. 2488 // FIXME: It would be better if CXXBasePath had the base specifier for 2489 // the nearest virtual base. 2490 unsigned Start = 0; 2491 for (unsigned I = Path.size(); I != 0; --I) { 2492 if (Path[I - 1].Base->isVirtual()) { 2493 Start = I - 1; 2494 break; 2495 } 2496 } 2497 2498 // Now add all bases. 2499 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2500 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2501 } 2502 2503 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2504 /// conversion (where Derived and Base are class types) is 2505 /// well-formed, meaning that the conversion is unambiguous (and 2506 /// that all of the base classes are accessible). Returns true 2507 /// and emits a diagnostic if the code is ill-formed, returns false 2508 /// otherwise. Loc is the location where this routine should point to 2509 /// if there is an error, and Range is the source range to highlight 2510 /// if there is an error. 2511 /// 2512 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2513 /// diagnostic for the respective type of error will be suppressed, but the 2514 /// check for ill-formed code will still be performed. 2515 bool 2516 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2517 unsigned InaccessibleBaseID, 2518 unsigned AmbigiousBaseConvID, 2519 SourceLocation Loc, SourceRange Range, 2520 DeclarationName Name, 2521 CXXCastPath *BasePath, 2522 bool IgnoreAccess) { 2523 // First, determine whether the path from Derived to Base is 2524 // ambiguous. This is slightly more expensive than checking whether 2525 // the Derived to Base conversion exists, because here we need to 2526 // explore multiple paths to determine if there is an ambiguity. 2527 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2528 /*DetectVirtual=*/false); 2529 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2530 assert(DerivationOkay && 2531 "Can only be used with a derived-to-base conversion"); 2532 (void)DerivationOkay; 2533 2534 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 2535 if (!IgnoreAccess) { 2536 // Check that the base class can be accessed. 2537 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 2538 InaccessibleBaseID)) { 2539 case AR_inaccessible: 2540 return true; 2541 case AR_accessible: 2542 case AR_dependent: 2543 case AR_delayed: 2544 break; 2545 } 2546 } 2547 2548 // Build a base path if necessary. 2549 if (BasePath) 2550 BuildBasePathArray(Paths, *BasePath); 2551 return false; 2552 } 2553 2554 if (AmbigiousBaseConvID) { 2555 // We know that the derived-to-base conversion is ambiguous, and 2556 // we're going to produce a diagnostic. Perform the derived-to-base 2557 // search just one more time to compute all of the possible paths so 2558 // that we can print them out. This is more expensive than any of 2559 // the previous derived-to-base checks we've done, but at this point 2560 // performance isn't as much of an issue. 2561 Paths.clear(); 2562 Paths.setRecordingPaths(true); 2563 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2564 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2565 (void)StillOkay; 2566 2567 // Build up a textual representation of the ambiguous paths, e.g., 2568 // D -> B -> A, that will be used to illustrate the ambiguous 2569 // conversions in the diagnostic. We only print one of the paths 2570 // to each base class subobject. 2571 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2572 2573 Diag(Loc, AmbigiousBaseConvID) 2574 << Derived << Base << PathDisplayStr << Range << Name; 2575 } 2576 return true; 2577 } 2578 2579 bool 2580 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2581 SourceLocation Loc, SourceRange Range, 2582 CXXCastPath *BasePath, 2583 bool IgnoreAccess) { 2584 return CheckDerivedToBaseConversion( 2585 Derived, Base, diag::err_upcast_to_inaccessible_base, 2586 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2587 BasePath, IgnoreAccess); 2588 } 2589 2590 2591 /// @brief Builds a string representing ambiguous paths from a 2592 /// specific derived class to different subobjects of the same base 2593 /// class. 2594 /// 2595 /// This function builds a string that can be used in error messages 2596 /// to show the different paths that one can take through the 2597 /// inheritance hierarchy to go from the derived class to different 2598 /// subobjects of a base class. The result looks something like this: 2599 /// @code 2600 /// struct D -> struct B -> struct A 2601 /// struct D -> struct C -> struct A 2602 /// @endcode 2603 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2604 std::string PathDisplayStr; 2605 std::set<unsigned> DisplayedPaths; 2606 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2607 Path != Paths.end(); ++Path) { 2608 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2609 // We haven't displayed a path to this particular base 2610 // class subobject yet. 2611 PathDisplayStr += "\n "; 2612 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2613 for (CXXBasePath::const_iterator Element = Path->begin(); 2614 Element != Path->end(); ++Element) 2615 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2616 } 2617 } 2618 2619 return PathDisplayStr; 2620 } 2621 2622 //===----------------------------------------------------------------------===// 2623 // C++ class member Handling 2624 //===----------------------------------------------------------------------===// 2625 2626 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2627 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2628 SourceLocation ASLoc, 2629 SourceLocation ColonLoc, 2630 AttributeList *Attrs) { 2631 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2632 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2633 ASLoc, ColonLoc); 2634 CurContext->addHiddenDecl(ASDecl); 2635 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2636 } 2637 2638 /// CheckOverrideControl - Check C++11 override control semantics. 2639 void Sema::CheckOverrideControl(NamedDecl *D) { 2640 if (D->isInvalidDecl()) 2641 return; 2642 2643 // We only care about "override" and "final" declarations. 2644 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2645 return; 2646 2647 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2648 2649 // We can't check dependent instance methods. 2650 if (MD && MD->isInstance() && 2651 (MD->getParent()->hasAnyDependentBases() || 2652 MD->getType()->isDependentType())) 2653 return; 2654 2655 if (MD && !MD->isVirtual()) { 2656 // If we have a non-virtual method, check if if hides a virtual method. 2657 // (In that case, it's most likely the method has the wrong type.) 2658 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2659 FindHiddenVirtualMethods(MD, OverloadedMethods); 2660 2661 if (!OverloadedMethods.empty()) { 2662 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2663 Diag(OA->getLocation(), 2664 diag::override_keyword_hides_virtual_member_function) 2665 << "override" << (OverloadedMethods.size() > 1); 2666 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2667 Diag(FA->getLocation(), 2668 diag::override_keyword_hides_virtual_member_function) 2669 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2670 << (OverloadedMethods.size() > 1); 2671 } 2672 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2673 MD->setInvalidDecl(); 2674 return; 2675 } 2676 // Fall through into the general case diagnostic. 2677 // FIXME: We might want to attempt typo correction here. 2678 } 2679 2680 if (!MD || !MD->isVirtual()) { 2681 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2682 Diag(OA->getLocation(), 2683 diag::override_keyword_only_allowed_on_virtual_member_functions) 2684 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2685 D->dropAttr<OverrideAttr>(); 2686 } 2687 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2688 Diag(FA->getLocation(), 2689 diag::override_keyword_only_allowed_on_virtual_member_functions) 2690 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2691 << FixItHint::CreateRemoval(FA->getLocation()); 2692 D->dropAttr<FinalAttr>(); 2693 } 2694 return; 2695 } 2696 2697 // C++11 [class.virtual]p5: 2698 // If a function is marked with the virt-specifier override and 2699 // does not override a member function of a base class, the program is 2700 // ill-formed. 2701 bool HasOverriddenMethods = 2702 MD->begin_overridden_methods() != MD->end_overridden_methods(); 2703 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2704 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2705 << MD->getDeclName(); 2706 } 2707 2708 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2709 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2710 return; 2711 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2712 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 2713 isa<CXXDestructorDecl>(MD)) 2714 return; 2715 2716 SourceLocation Loc = MD->getLocation(); 2717 SourceLocation SpellingLoc = Loc; 2718 if (getSourceManager().isMacroArgExpansion(Loc)) 2719 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 2720 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2721 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2722 return; 2723 2724 if (MD->size_overridden_methods() > 0) { 2725 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 2726 << MD->getDeclName(); 2727 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2728 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2729 } 2730 } 2731 2732 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2733 /// function overrides a virtual member function marked 'final', according to 2734 /// C++11 [class.virtual]p4. 2735 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2736 const CXXMethodDecl *Old) { 2737 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2738 if (!FA) 2739 return false; 2740 2741 Diag(New->getLocation(), diag::err_final_function_overridden) 2742 << New->getDeclName() 2743 << FA->isSpelledAsSealed(); 2744 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2745 return true; 2746 } 2747 2748 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2749 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2750 // FIXME: Destruction of ObjC lifetime types has side-effects. 2751 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2752 return !RD->isCompleteDefinition() || 2753 !RD->hasTrivialDefaultConstructor() || 2754 !RD->hasTrivialDestructor(); 2755 return false; 2756 } 2757 2758 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2759 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2760 if (it->isDeclspecPropertyAttribute()) 2761 return it; 2762 return nullptr; 2763 } 2764 2765 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2766 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2767 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2768 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2769 /// present (but parsing it has been deferred). 2770 NamedDecl * 2771 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2772 MultiTemplateParamsArg TemplateParameterLists, 2773 Expr *BW, const VirtSpecifiers &VS, 2774 InClassInitStyle InitStyle) { 2775 const DeclSpec &DS = D.getDeclSpec(); 2776 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2777 DeclarationName Name = NameInfo.getName(); 2778 SourceLocation Loc = NameInfo.getLoc(); 2779 2780 // For anonymous bitfields, the location should point to the type. 2781 if (Loc.isInvalid()) 2782 Loc = D.getLocStart(); 2783 2784 Expr *BitWidth = static_cast<Expr*>(BW); 2785 2786 assert(isa<CXXRecordDecl>(CurContext)); 2787 assert(!DS.isFriendSpecified()); 2788 2789 bool isFunc = D.isDeclarationOfFunction(); 2790 2791 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2792 // The Microsoft extension __interface only permits public member functions 2793 // and prohibits constructors, destructors, operators, non-public member 2794 // functions, static methods and data members. 2795 unsigned InvalidDecl; 2796 bool ShowDeclName = true; 2797 if (!isFunc) 2798 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2799 else if (AS != AS_public) 2800 InvalidDecl = 2; 2801 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2802 InvalidDecl = 3; 2803 else switch (Name.getNameKind()) { 2804 case DeclarationName::CXXConstructorName: 2805 InvalidDecl = 4; 2806 ShowDeclName = false; 2807 break; 2808 2809 case DeclarationName::CXXDestructorName: 2810 InvalidDecl = 5; 2811 ShowDeclName = false; 2812 break; 2813 2814 case DeclarationName::CXXOperatorName: 2815 case DeclarationName::CXXConversionFunctionName: 2816 InvalidDecl = 6; 2817 break; 2818 2819 default: 2820 InvalidDecl = 0; 2821 break; 2822 } 2823 2824 if (InvalidDecl) { 2825 if (ShowDeclName) 2826 Diag(Loc, diag::err_invalid_member_in_interface) 2827 << (InvalidDecl-1) << Name; 2828 else 2829 Diag(Loc, diag::err_invalid_member_in_interface) 2830 << (InvalidDecl-1) << ""; 2831 return nullptr; 2832 } 2833 } 2834 2835 // C++ 9.2p6: A member shall not be declared to have automatic storage 2836 // duration (auto, register) or with the extern storage-class-specifier. 2837 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2838 // data members and cannot be applied to names declared const or static, 2839 // and cannot be applied to reference members. 2840 switch (DS.getStorageClassSpec()) { 2841 case DeclSpec::SCS_unspecified: 2842 case DeclSpec::SCS_typedef: 2843 case DeclSpec::SCS_static: 2844 break; 2845 case DeclSpec::SCS_mutable: 2846 if (isFunc) { 2847 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2848 2849 // FIXME: It would be nicer if the keyword was ignored only for this 2850 // declarator. Otherwise we could get follow-up errors. 2851 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2852 } 2853 break; 2854 default: 2855 Diag(DS.getStorageClassSpecLoc(), 2856 diag::err_storageclass_invalid_for_member); 2857 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2858 break; 2859 } 2860 2861 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2862 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2863 !isFunc); 2864 2865 if (DS.isConstexprSpecified() && isInstField) { 2866 SemaDiagnosticBuilder B = 2867 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2868 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2869 if (InitStyle == ICIS_NoInit) { 2870 B << 0 << 0; 2871 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2872 B << FixItHint::CreateRemoval(ConstexprLoc); 2873 else { 2874 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2875 D.getMutableDeclSpec().ClearConstexprSpec(); 2876 const char *PrevSpec; 2877 unsigned DiagID; 2878 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2879 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2880 (void)Failed; 2881 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2882 } 2883 } else { 2884 B << 1; 2885 const char *PrevSpec; 2886 unsigned DiagID; 2887 if (D.getMutableDeclSpec().SetStorageClassSpec( 2888 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2889 Context.getPrintingPolicy())) { 2890 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2891 "This is the only DeclSpec that should fail to be applied"); 2892 B << 1; 2893 } else { 2894 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2895 isInstField = false; 2896 } 2897 } 2898 } 2899 2900 NamedDecl *Member; 2901 if (isInstField) { 2902 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2903 2904 // Data members must have identifiers for names. 2905 if (!Name.isIdentifier()) { 2906 Diag(Loc, diag::err_bad_variable_name) 2907 << Name; 2908 return nullptr; 2909 } 2910 2911 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2912 2913 // Member field could not be with "template" keyword. 2914 // So TemplateParameterLists should be empty in this case. 2915 if (TemplateParameterLists.size()) { 2916 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2917 if (TemplateParams->size()) { 2918 // There is no such thing as a member field template. 2919 Diag(D.getIdentifierLoc(), diag::err_template_member) 2920 << II 2921 << SourceRange(TemplateParams->getTemplateLoc(), 2922 TemplateParams->getRAngleLoc()); 2923 } else { 2924 // There is an extraneous 'template<>' for this member. 2925 Diag(TemplateParams->getTemplateLoc(), 2926 diag::err_template_member_noparams) 2927 << II 2928 << SourceRange(TemplateParams->getTemplateLoc(), 2929 TemplateParams->getRAngleLoc()); 2930 } 2931 return nullptr; 2932 } 2933 2934 if (SS.isSet() && !SS.isInvalid()) { 2935 // The user provided a superfluous scope specifier inside a class 2936 // definition: 2937 // 2938 // class X { 2939 // int X::member; 2940 // }; 2941 if (DeclContext *DC = computeDeclContext(SS, false)) 2942 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2943 else 2944 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2945 << Name << SS.getRange(); 2946 2947 SS.clear(); 2948 } 2949 2950 AttributeList *MSPropertyAttr = 2951 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2952 if (MSPropertyAttr) { 2953 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2954 BitWidth, InitStyle, AS, MSPropertyAttr); 2955 if (!Member) 2956 return nullptr; 2957 isInstField = false; 2958 } else { 2959 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2960 BitWidth, InitStyle, AS); 2961 if (!Member) 2962 return nullptr; 2963 } 2964 } else { 2965 Member = HandleDeclarator(S, D, TemplateParameterLists); 2966 if (!Member) 2967 return nullptr; 2968 2969 // Non-instance-fields can't have a bitfield. 2970 if (BitWidth) { 2971 if (Member->isInvalidDecl()) { 2972 // don't emit another diagnostic. 2973 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2974 // C++ 9.6p3: A bit-field shall not be a static member. 2975 // "static member 'A' cannot be a bit-field" 2976 Diag(Loc, diag::err_static_not_bitfield) 2977 << Name << BitWidth->getSourceRange(); 2978 } else if (isa<TypedefDecl>(Member)) { 2979 // "typedef member 'x' cannot be a bit-field" 2980 Diag(Loc, diag::err_typedef_not_bitfield) 2981 << Name << BitWidth->getSourceRange(); 2982 } else { 2983 // A function typedef ("typedef int f(); f a;"). 2984 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2985 Diag(Loc, diag::err_not_integral_type_bitfield) 2986 << Name << cast<ValueDecl>(Member)->getType() 2987 << BitWidth->getSourceRange(); 2988 } 2989 2990 BitWidth = nullptr; 2991 Member->setInvalidDecl(); 2992 } 2993 2994 Member->setAccess(AS); 2995 2996 // If we have declared a member function template or static data member 2997 // template, set the access of the templated declaration as well. 2998 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2999 FunTmpl->getTemplatedDecl()->setAccess(AS); 3000 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3001 VarTmpl->getTemplatedDecl()->setAccess(AS); 3002 } 3003 3004 if (VS.isOverrideSpecified()) 3005 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3006 if (VS.isFinalSpecified()) 3007 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3008 VS.isFinalSpelledSealed())); 3009 3010 if (VS.getLastLocation().isValid()) { 3011 // Update the end location of a method that has a virt-specifiers. 3012 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3013 MD->setRangeEnd(VS.getLastLocation()); 3014 } 3015 3016 CheckOverrideControl(Member); 3017 3018 assert((Name || isInstField) && "No identifier for non-field ?"); 3019 3020 if (isInstField) { 3021 FieldDecl *FD = cast<FieldDecl>(Member); 3022 FieldCollector->Add(FD); 3023 3024 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3025 // Remember all explicit private FieldDecls that have a name, no side 3026 // effects and are not part of a dependent type declaration. 3027 if (!FD->isImplicit() && FD->getDeclName() && 3028 FD->getAccess() == AS_private && 3029 !FD->hasAttr<UnusedAttr>() && 3030 !FD->getParent()->isDependentContext() && 3031 !InitializationHasSideEffects(*FD)) 3032 UnusedPrivateFields.insert(FD); 3033 } 3034 } 3035 3036 return Member; 3037 } 3038 3039 namespace { 3040 class UninitializedFieldVisitor 3041 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3042 Sema &S; 3043 // List of Decls to generate a warning on. Also remove Decls that become 3044 // initialized. 3045 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3046 // List of base classes of the record. Classes are removed after their 3047 // initializers. 3048 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3049 // Vector of decls to be removed from the Decl set prior to visiting the 3050 // nodes. These Decls may have been initialized in the prior initializer. 3051 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3052 // If non-null, add a note to the warning pointing back to the constructor. 3053 const CXXConstructorDecl *Constructor; 3054 // Variables to hold state when processing an initializer list. When 3055 // InitList is true, special case initialization of FieldDecls matching 3056 // InitListFieldDecl. 3057 bool InitList; 3058 FieldDecl *InitListFieldDecl; 3059 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3060 3061 public: 3062 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3063 UninitializedFieldVisitor(Sema &S, 3064 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3065 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3066 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3067 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3068 3069 // Returns true if the use of ME is not an uninitialized use. 3070 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3071 bool CheckReferenceOnly) { 3072 llvm::SmallVector<FieldDecl*, 4> Fields; 3073 bool ReferenceField = false; 3074 while (ME) { 3075 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3076 if (!FD) 3077 return false; 3078 Fields.push_back(FD); 3079 if (FD->getType()->isReferenceType()) 3080 ReferenceField = true; 3081 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3082 } 3083 3084 // Binding a reference to an unintialized field is not an 3085 // uninitialized use. 3086 if (CheckReferenceOnly && !ReferenceField) 3087 return true; 3088 3089 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3090 // Discard the first field since it is the field decl that is being 3091 // initialized. 3092 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3093 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3094 } 3095 3096 for (auto UsedIter = UsedFieldIndex.begin(), 3097 UsedEnd = UsedFieldIndex.end(), 3098 OrigIter = InitFieldIndex.begin(), 3099 OrigEnd = InitFieldIndex.end(); 3100 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3101 if (*UsedIter < *OrigIter) 3102 return true; 3103 if (*UsedIter > *OrigIter) 3104 break; 3105 } 3106 3107 return false; 3108 } 3109 3110 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3111 bool AddressOf) { 3112 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3113 return; 3114 3115 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3116 // or union. 3117 MemberExpr *FieldME = ME; 3118 3119 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3120 3121 Expr *Base = ME; 3122 while (MemberExpr *SubME = 3123 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3124 3125 if (isa<VarDecl>(SubME->getMemberDecl())) 3126 return; 3127 3128 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3129 if (!FD->isAnonymousStructOrUnion()) 3130 FieldME = SubME; 3131 3132 if (!FieldME->getType().isPODType(S.Context)) 3133 AllPODFields = false; 3134 3135 Base = SubME->getBase(); 3136 } 3137 3138 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3139 return; 3140 3141 if (AddressOf && AllPODFields) 3142 return; 3143 3144 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3145 3146 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3147 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3148 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3149 } 3150 3151 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3152 QualType T = BaseCast->getType(); 3153 if (T->isPointerType() && 3154 BaseClasses.count(T->getPointeeType())) { 3155 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3156 << T->getPointeeType() << FoundVD; 3157 } 3158 } 3159 } 3160 3161 if (!Decls.count(FoundVD)) 3162 return; 3163 3164 const bool IsReference = FoundVD->getType()->isReferenceType(); 3165 3166 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3167 // Special checking for initializer lists. 3168 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3169 return; 3170 } 3171 } else { 3172 // Prevent double warnings on use of unbounded references. 3173 if (CheckReferenceOnly && !IsReference) 3174 return; 3175 } 3176 3177 unsigned diag = IsReference 3178 ? diag::warn_reference_field_is_uninit 3179 : diag::warn_field_is_uninit; 3180 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3181 if (Constructor) 3182 S.Diag(Constructor->getLocation(), 3183 diag::note_uninit_in_this_constructor) 3184 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3185 3186 } 3187 3188 void HandleValue(Expr *E, bool AddressOf) { 3189 E = E->IgnoreParens(); 3190 3191 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3192 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3193 AddressOf /*AddressOf*/); 3194 return; 3195 } 3196 3197 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3198 Visit(CO->getCond()); 3199 HandleValue(CO->getTrueExpr(), AddressOf); 3200 HandleValue(CO->getFalseExpr(), AddressOf); 3201 return; 3202 } 3203 3204 if (BinaryConditionalOperator *BCO = 3205 dyn_cast<BinaryConditionalOperator>(E)) { 3206 Visit(BCO->getCond()); 3207 HandleValue(BCO->getFalseExpr(), AddressOf); 3208 return; 3209 } 3210 3211 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3212 HandleValue(OVE->getSourceExpr(), AddressOf); 3213 return; 3214 } 3215 3216 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3217 switch (BO->getOpcode()) { 3218 default: 3219 break; 3220 case(BO_PtrMemD): 3221 case(BO_PtrMemI): 3222 HandleValue(BO->getLHS(), AddressOf); 3223 Visit(BO->getRHS()); 3224 return; 3225 case(BO_Comma): 3226 Visit(BO->getLHS()); 3227 HandleValue(BO->getRHS(), AddressOf); 3228 return; 3229 } 3230 } 3231 3232 Visit(E); 3233 } 3234 3235 void CheckInitListExpr(InitListExpr *ILE) { 3236 InitFieldIndex.push_back(0); 3237 for (auto Child : ILE->children()) { 3238 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3239 CheckInitListExpr(SubList); 3240 } else { 3241 Visit(Child); 3242 } 3243 ++InitFieldIndex.back(); 3244 } 3245 InitFieldIndex.pop_back(); 3246 } 3247 3248 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3249 FieldDecl *Field, const Type *BaseClass) { 3250 // Remove Decls that may have been initialized in the previous 3251 // initializer. 3252 for (ValueDecl* VD : DeclsToRemove) 3253 Decls.erase(VD); 3254 DeclsToRemove.clear(); 3255 3256 Constructor = FieldConstructor; 3257 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3258 3259 if (ILE && Field) { 3260 InitList = true; 3261 InitListFieldDecl = Field; 3262 InitFieldIndex.clear(); 3263 CheckInitListExpr(ILE); 3264 } else { 3265 InitList = false; 3266 Visit(E); 3267 } 3268 3269 if (Field) 3270 Decls.erase(Field); 3271 if (BaseClass) 3272 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3273 } 3274 3275 void VisitMemberExpr(MemberExpr *ME) { 3276 // All uses of unbounded reference fields will warn. 3277 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3278 } 3279 3280 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3281 if (E->getCastKind() == CK_LValueToRValue) { 3282 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3283 return; 3284 } 3285 3286 Inherited::VisitImplicitCastExpr(E); 3287 } 3288 3289 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3290 if (E->getConstructor()->isCopyConstructor()) { 3291 Expr *ArgExpr = E->getArg(0); 3292 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3293 if (ILE->getNumInits() == 1) 3294 ArgExpr = ILE->getInit(0); 3295 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3296 if (ICE->getCastKind() == CK_NoOp) 3297 ArgExpr = ICE->getSubExpr(); 3298 HandleValue(ArgExpr, false /*AddressOf*/); 3299 return; 3300 } 3301 Inherited::VisitCXXConstructExpr(E); 3302 } 3303 3304 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3305 Expr *Callee = E->getCallee(); 3306 if (isa<MemberExpr>(Callee)) { 3307 HandleValue(Callee, false /*AddressOf*/); 3308 for (auto Arg : E->arguments()) 3309 Visit(Arg); 3310 return; 3311 } 3312 3313 Inherited::VisitCXXMemberCallExpr(E); 3314 } 3315 3316 void VisitCallExpr(CallExpr *E) { 3317 // Treat std::move as a use. 3318 if (E->getNumArgs() == 1) { 3319 if (FunctionDecl *FD = E->getDirectCallee()) { 3320 if (FD->isInStdNamespace() && FD->getIdentifier() && 3321 FD->getIdentifier()->isStr("move")) { 3322 HandleValue(E->getArg(0), false /*AddressOf*/); 3323 return; 3324 } 3325 } 3326 } 3327 3328 Inherited::VisitCallExpr(E); 3329 } 3330 3331 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3332 Expr *Callee = E->getCallee(); 3333 3334 if (isa<UnresolvedLookupExpr>(Callee)) 3335 return Inherited::VisitCXXOperatorCallExpr(E); 3336 3337 Visit(Callee); 3338 for (auto Arg : E->arguments()) 3339 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3340 } 3341 3342 void VisitBinaryOperator(BinaryOperator *E) { 3343 // If a field assignment is detected, remove the field from the 3344 // uninitiailized field set. 3345 if (E->getOpcode() == BO_Assign) 3346 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3347 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3348 if (!FD->getType()->isReferenceType()) 3349 DeclsToRemove.push_back(FD); 3350 3351 if (E->isCompoundAssignmentOp()) { 3352 HandleValue(E->getLHS(), false /*AddressOf*/); 3353 Visit(E->getRHS()); 3354 return; 3355 } 3356 3357 Inherited::VisitBinaryOperator(E); 3358 } 3359 3360 void VisitUnaryOperator(UnaryOperator *E) { 3361 if (E->isIncrementDecrementOp()) { 3362 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3363 return; 3364 } 3365 if (E->getOpcode() == UO_AddrOf) { 3366 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3367 HandleValue(ME->getBase(), true /*AddressOf*/); 3368 return; 3369 } 3370 } 3371 3372 Inherited::VisitUnaryOperator(E); 3373 } 3374 }; 3375 3376 // Diagnose value-uses of fields to initialize themselves, e.g. 3377 // foo(foo) 3378 // where foo is not also a parameter to the constructor. 3379 // Also diagnose across field uninitialized use such as 3380 // x(y), y(x) 3381 // TODO: implement -Wuninitialized and fold this into that framework. 3382 static void DiagnoseUninitializedFields( 3383 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3384 3385 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3386 Constructor->getLocation())) { 3387 return; 3388 } 3389 3390 if (Constructor->isInvalidDecl()) 3391 return; 3392 3393 const CXXRecordDecl *RD = Constructor->getParent(); 3394 3395 if (RD->getDescribedClassTemplate()) 3396 return; 3397 3398 // Holds fields that are uninitialized. 3399 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3400 3401 // At the beginning, all fields are uninitialized. 3402 for (auto *I : RD->decls()) { 3403 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3404 UninitializedFields.insert(FD); 3405 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3406 UninitializedFields.insert(IFD->getAnonField()); 3407 } 3408 } 3409 3410 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3411 for (auto I : RD->bases()) 3412 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3413 3414 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3415 return; 3416 3417 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3418 UninitializedFields, 3419 UninitializedBaseClasses); 3420 3421 for (const auto *FieldInit : Constructor->inits()) { 3422 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3423 break; 3424 3425 Expr *InitExpr = FieldInit->getInit(); 3426 if (!InitExpr) 3427 continue; 3428 3429 if (CXXDefaultInitExpr *Default = 3430 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3431 InitExpr = Default->getExpr(); 3432 if (!InitExpr) 3433 continue; 3434 // In class initializers will point to the constructor. 3435 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3436 FieldInit->getAnyMember(), 3437 FieldInit->getBaseClass()); 3438 } else { 3439 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3440 FieldInit->getAnyMember(), 3441 FieldInit->getBaseClass()); 3442 } 3443 } 3444 } 3445 } // namespace 3446 3447 /// \brief Enter a new C++ default initializer scope. After calling this, the 3448 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3449 /// parsing or instantiating the initializer failed. 3450 void Sema::ActOnStartCXXInClassMemberInitializer() { 3451 // Create a synthetic function scope to represent the call to the constructor 3452 // that notionally surrounds a use of this initializer. 3453 PushFunctionScope(); 3454 } 3455 3456 /// \brief This is invoked after parsing an in-class initializer for a 3457 /// non-static C++ class member, and after instantiating an in-class initializer 3458 /// in a class template. Such actions are deferred until the class is complete. 3459 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3460 SourceLocation InitLoc, 3461 Expr *InitExpr) { 3462 // Pop the notional constructor scope we created earlier. 3463 PopFunctionScopeInfo(nullptr, D); 3464 3465 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3466 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3467 "must set init style when field is created"); 3468 3469 if (!InitExpr) { 3470 D->setInvalidDecl(); 3471 if (FD) 3472 FD->removeInClassInitializer(); 3473 return; 3474 } 3475 3476 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3477 FD->setInvalidDecl(); 3478 FD->removeInClassInitializer(); 3479 return; 3480 } 3481 3482 ExprResult Init = InitExpr; 3483 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3484 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3485 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 3486 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 3487 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3488 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3489 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3490 if (Init.isInvalid()) { 3491 FD->setInvalidDecl(); 3492 return; 3493 } 3494 } 3495 3496 // C++11 [class.base.init]p7: 3497 // The initialization of each base and member constitutes a 3498 // full-expression. 3499 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3500 if (Init.isInvalid()) { 3501 FD->setInvalidDecl(); 3502 return; 3503 } 3504 3505 InitExpr = Init.get(); 3506 3507 FD->setInClassInitializer(InitExpr); 3508 } 3509 3510 /// \brief Find the direct and/or virtual base specifiers that 3511 /// correspond to the given base type, for use in base initialization 3512 /// within a constructor. 3513 static bool FindBaseInitializer(Sema &SemaRef, 3514 CXXRecordDecl *ClassDecl, 3515 QualType BaseType, 3516 const CXXBaseSpecifier *&DirectBaseSpec, 3517 const CXXBaseSpecifier *&VirtualBaseSpec) { 3518 // First, check for a direct base class. 3519 DirectBaseSpec = nullptr; 3520 for (const auto &Base : ClassDecl->bases()) { 3521 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3522 // We found a direct base of this type. That's what we're 3523 // initializing. 3524 DirectBaseSpec = &Base; 3525 break; 3526 } 3527 } 3528 3529 // Check for a virtual base class. 3530 // FIXME: We might be able to short-circuit this if we know in advance that 3531 // there are no virtual bases. 3532 VirtualBaseSpec = nullptr; 3533 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3534 // We haven't found a base yet; search the class hierarchy for a 3535 // virtual base class. 3536 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3537 /*DetectVirtual=*/false); 3538 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3539 SemaRef.Context.getTypeDeclType(ClassDecl), 3540 BaseType, Paths)) { 3541 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3542 Path != Paths.end(); ++Path) { 3543 if (Path->back().Base->isVirtual()) { 3544 VirtualBaseSpec = Path->back().Base; 3545 break; 3546 } 3547 } 3548 } 3549 } 3550 3551 return DirectBaseSpec || VirtualBaseSpec; 3552 } 3553 3554 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3555 MemInitResult 3556 Sema::ActOnMemInitializer(Decl *ConstructorD, 3557 Scope *S, 3558 CXXScopeSpec &SS, 3559 IdentifierInfo *MemberOrBase, 3560 ParsedType TemplateTypeTy, 3561 const DeclSpec &DS, 3562 SourceLocation IdLoc, 3563 Expr *InitList, 3564 SourceLocation EllipsisLoc) { 3565 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3566 DS, IdLoc, InitList, 3567 EllipsisLoc); 3568 } 3569 3570 /// \brief Handle a C++ member initializer using parentheses syntax. 3571 MemInitResult 3572 Sema::ActOnMemInitializer(Decl *ConstructorD, 3573 Scope *S, 3574 CXXScopeSpec &SS, 3575 IdentifierInfo *MemberOrBase, 3576 ParsedType TemplateTypeTy, 3577 const DeclSpec &DS, 3578 SourceLocation IdLoc, 3579 SourceLocation LParenLoc, 3580 ArrayRef<Expr *> Args, 3581 SourceLocation RParenLoc, 3582 SourceLocation EllipsisLoc) { 3583 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3584 Args, RParenLoc); 3585 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3586 DS, IdLoc, List, EllipsisLoc); 3587 } 3588 3589 namespace { 3590 3591 // Callback to only accept typo corrections that can be a valid C++ member 3592 // intializer: either a non-static field member or a base class. 3593 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3594 public: 3595 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3596 : ClassDecl(ClassDecl) {} 3597 3598 bool ValidateCandidate(const TypoCorrection &candidate) override { 3599 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3600 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3601 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3602 return isa<TypeDecl>(ND); 3603 } 3604 return false; 3605 } 3606 3607 private: 3608 CXXRecordDecl *ClassDecl; 3609 }; 3610 3611 } 3612 3613 /// \brief Handle a C++ member initializer. 3614 MemInitResult 3615 Sema::BuildMemInitializer(Decl *ConstructorD, 3616 Scope *S, 3617 CXXScopeSpec &SS, 3618 IdentifierInfo *MemberOrBase, 3619 ParsedType TemplateTypeTy, 3620 const DeclSpec &DS, 3621 SourceLocation IdLoc, 3622 Expr *Init, 3623 SourceLocation EllipsisLoc) { 3624 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3625 if (!Res.isUsable()) 3626 return true; 3627 Init = Res.get(); 3628 3629 if (!ConstructorD) 3630 return true; 3631 3632 AdjustDeclIfTemplate(ConstructorD); 3633 3634 CXXConstructorDecl *Constructor 3635 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3636 if (!Constructor) { 3637 // The user wrote a constructor initializer on a function that is 3638 // not a C++ constructor. Ignore the error for now, because we may 3639 // have more member initializers coming; we'll diagnose it just 3640 // once in ActOnMemInitializers. 3641 return true; 3642 } 3643 3644 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3645 3646 // C++ [class.base.init]p2: 3647 // Names in a mem-initializer-id are looked up in the scope of the 3648 // constructor's class and, if not found in that scope, are looked 3649 // up in the scope containing the constructor's definition. 3650 // [Note: if the constructor's class contains a member with the 3651 // same name as a direct or virtual base class of the class, a 3652 // mem-initializer-id naming the member or base class and composed 3653 // of a single identifier refers to the class member. A 3654 // mem-initializer-id for the hidden base class may be specified 3655 // using a qualified name. ] 3656 if (!SS.getScopeRep() && !TemplateTypeTy) { 3657 // Look for a member, first. 3658 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3659 if (!Result.empty()) { 3660 ValueDecl *Member; 3661 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3662 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3663 if (EllipsisLoc.isValid()) 3664 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3665 << MemberOrBase 3666 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3667 3668 return BuildMemberInitializer(Member, Init, IdLoc); 3669 } 3670 } 3671 } 3672 // It didn't name a member, so see if it names a class. 3673 QualType BaseType; 3674 TypeSourceInfo *TInfo = nullptr; 3675 3676 if (TemplateTypeTy) { 3677 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3678 } else if (DS.getTypeSpecType() == TST_decltype) { 3679 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3680 } else { 3681 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3682 LookupParsedName(R, S, &SS); 3683 3684 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3685 if (!TyD) { 3686 if (R.isAmbiguous()) return true; 3687 3688 // We don't want access-control diagnostics here. 3689 R.suppressDiagnostics(); 3690 3691 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3692 bool NotUnknownSpecialization = false; 3693 DeclContext *DC = computeDeclContext(SS, false); 3694 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3695 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3696 3697 if (!NotUnknownSpecialization) { 3698 // When the scope specifier can refer to a member of an unknown 3699 // specialization, we take it as a type name. 3700 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3701 SS.getWithLocInContext(Context), 3702 *MemberOrBase, IdLoc); 3703 if (BaseType.isNull()) 3704 return true; 3705 3706 R.clear(); 3707 R.setLookupName(MemberOrBase); 3708 } 3709 } 3710 3711 // If no results were found, try to correct typos. 3712 TypoCorrection Corr; 3713 if (R.empty() && BaseType.isNull() && 3714 (Corr = CorrectTypo( 3715 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3716 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3717 CTK_ErrorRecovery, ClassDecl))) { 3718 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3719 // We have found a non-static data member with a similar 3720 // name to what was typed; complain and initialize that 3721 // member. 3722 diagnoseTypo(Corr, 3723 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3724 << MemberOrBase << true); 3725 return BuildMemberInitializer(Member, Init, IdLoc); 3726 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3727 const CXXBaseSpecifier *DirectBaseSpec; 3728 const CXXBaseSpecifier *VirtualBaseSpec; 3729 if (FindBaseInitializer(*this, ClassDecl, 3730 Context.getTypeDeclType(Type), 3731 DirectBaseSpec, VirtualBaseSpec)) { 3732 // We have found a direct or virtual base class with a 3733 // similar name to what was typed; complain and initialize 3734 // that base class. 3735 diagnoseTypo(Corr, 3736 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3737 << MemberOrBase << false, 3738 PDiag() /*Suppress note, we provide our own.*/); 3739 3740 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3741 : VirtualBaseSpec; 3742 Diag(BaseSpec->getLocStart(), 3743 diag::note_base_class_specified_here) 3744 << BaseSpec->getType() 3745 << BaseSpec->getSourceRange(); 3746 3747 TyD = Type; 3748 } 3749 } 3750 } 3751 3752 if (!TyD && BaseType.isNull()) { 3753 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3754 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3755 return true; 3756 } 3757 } 3758 3759 if (BaseType.isNull()) { 3760 BaseType = Context.getTypeDeclType(TyD); 3761 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3762 if (SS.isSet()) { 3763 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3764 BaseType); 3765 TInfo = Context.CreateTypeSourceInfo(BaseType); 3766 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3767 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3768 TL.setElaboratedKeywordLoc(SourceLocation()); 3769 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3770 } 3771 } 3772 } 3773 3774 if (!TInfo) 3775 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3776 3777 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3778 } 3779 3780 /// Checks a member initializer expression for cases where reference (or 3781 /// pointer) members are bound to by-value parameters (or their addresses). 3782 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3783 Expr *Init, 3784 SourceLocation IdLoc) { 3785 QualType MemberTy = Member->getType(); 3786 3787 // We only handle pointers and references currently. 3788 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3789 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3790 return; 3791 3792 const bool IsPointer = MemberTy->isPointerType(); 3793 if (IsPointer) { 3794 if (const UnaryOperator *Op 3795 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3796 // The only case we're worried about with pointers requires taking the 3797 // address. 3798 if (Op->getOpcode() != UO_AddrOf) 3799 return; 3800 3801 Init = Op->getSubExpr(); 3802 } else { 3803 // We only handle address-of expression initializers for pointers. 3804 return; 3805 } 3806 } 3807 3808 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3809 // We only warn when referring to a non-reference parameter declaration. 3810 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3811 if (!Parameter || Parameter->getType()->isReferenceType()) 3812 return; 3813 3814 S.Diag(Init->getExprLoc(), 3815 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3816 : diag::warn_bind_ref_member_to_parameter) 3817 << Member << Parameter << Init->getSourceRange(); 3818 } else { 3819 // Other initializers are fine. 3820 return; 3821 } 3822 3823 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3824 << (unsigned)IsPointer; 3825 } 3826 3827 MemInitResult 3828 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3829 SourceLocation IdLoc) { 3830 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3831 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3832 assert((DirectMember || IndirectMember) && 3833 "Member must be a FieldDecl or IndirectFieldDecl"); 3834 3835 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3836 return true; 3837 3838 if (Member->isInvalidDecl()) 3839 return true; 3840 3841 MultiExprArg Args; 3842 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3843 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3844 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3845 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3846 } else { 3847 // Template instantiation doesn't reconstruct ParenListExprs for us. 3848 Args = Init; 3849 } 3850 3851 SourceRange InitRange = Init->getSourceRange(); 3852 3853 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3854 // Can't check initialization for a member of dependent type or when 3855 // any of the arguments are type-dependent expressions. 3856 DiscardCleanupsInEvaluationContext(); 3857 } else { 3858 bool InitList = false; 3859 if (isa<InitListExpr>(Init)) { 3860 InitList = true; 3861 Args = Init; 3862 } 3863 3864 // Initialize the member. 3865 InitializedEntity MemberEntity = 3866 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3867 : InitializedEntity::InitializeMember(IndirectMember, 3868 nullptr); 3869 InitializationKind Kind = 3870 InitList ? InitializationKind::CreateDirectList(IdLoc) 3871 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3872 InitRange.getEnd()); 3873 3874 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3875 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3876 nullptr); 3877 if (MemberInit.isInvalid()) 3878 return true; 3879 3880 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3881 3882 // C++11 [class.base.init]p7: 3883 // The initialization of each base and member constitutes a 3884 // full-expression. 3885 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3886 if (MemberInit.isInvalid()) 3887 return true; 3888 3889 Init = MemberInit.get(); 3890 } 3891 3892 if (DirectMember) { 3893 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3894 InitRange.getBegin(), Init, 3895 InitRange.getEnd()); 3896 } else { 3897 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3898 InitRange.getBegin(), Init, 3899 InitRange.getEnd()); 3900 } 3901 } 3902 3903 MemInitResult 3904 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3905 CXXRecordDecl *ClassDecl) { 3906 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3907 if (!LangOpts.CPlusPlus11) 3908 return Diag(NameLoc, diag::err_delegating_ctor) 3909 << TInfo->getTypeLoc().getLocalSourceRange(); 3910 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3911 3912 bool InitList = true; 3913 MultiExprArg Args = Init; 3914 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3915 InitList = false; 3916 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3917 } 3918 3919 SourceRange InitRange = Init->getSourceRange(); 3920 // Initialize the object. 3921 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3922 QualType(ClassDecl->getTypeForDecl(), 0)); 3923 InitializationKind Kind = 3924 InitList ? InitializationKind::CreateDirectList(NameLoc) 3925 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3926 InitRange.getEnd()); 3927 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3928 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3929 Args, nullptr); 3930 if (DelegationInit.isInvalid()) 3931 return true; 3932 3933 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3934 "Delegating constructor with no target?"); 3935 3936 // C++11 [class.base.init]p7: 3937 // The initialization of each base and member constitutes a 3938 // full-expression. 3939 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3940 InitRange.getBegin()); 3941 if (DelegationInit.isInvalid()) 3942 return true; 3943 3944 // If we are in a dependent context, template instantiation will 3945 // perform this type-checking again. Just save the arguments that we 3946 // received in a ParenListExpr. 3947 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3948 // of the information that we have about the base 3949 // initializer. However, deconstructing the ASTs is a dicey process, 3950 // and this approach is far more likely to get the corner cases right. 3951 if (CurContext->isDependentContext()) 3952 DelegationInit = Init; 3953 3954 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3955 DelegationInit.getAs<Expr>(), 3956 InitRange.getEnd()); 3957 } 3958 3959 MemInitResult 3960 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3961 Expr *Init, CXXRecordDecl *ClassDecl, 3962 SourceLocation EllipsisLoc) { 3963 SourceLocation BaseLoc 3964 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3965 3966 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3967 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3968 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3969 3970 // C++ [class.base.init]p2: 3971 // [...] Unless the mem-initializer-id names a nonstatic data 3972 // member of the constructor's class or a direct or virtual base 3973 // of that class, the mem-initializer is ill-formed. A 3974 // mem-initializer-list can initialize a base class using any 3975 // name that denotes that base class type. 3976 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3977 3978 SourceRange InitRange = Init->getSourceRange(); 3979 if (EllipsisLoc.isValid()) { 3980 // This is a pack expansion. 3981 if (!BaseType->containsUnexpandedParameterPack()) { 3982 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3983 << SourceRange(BaseLoc, InitRange.getEnd()); 3984 3985 EllipsisLoc = SourceLocation(); 3986 } 3987 } else { 3988 // Check for any unexpanded parameter packs. 3989 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3990 return true; 3991 3992 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3993 return true; 3994 } 3995 3996 // Check for direct and virtual base classes. 3997 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3998 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3999 if (!Dependent) { 4000 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4001 BaseType)) 4002 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4003 4004 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4005 VirtualBaseSpec); 4006 4007 // C++ [base.class.init]p2: 4008 // Unless the mem-initializer-id names a nonstatic data member of the 4009 // constructor's class or a direct or virtual base of that class, the 4010 // mem-initializer is ill-formed. 4011 if (!DirectBaseSpec && !VirtualBaseSpec) { 4012 // If the class has any dependent bases, then it's possible that 4013 // one of those types will resolve to the same type as 4014 // BaseType. Therefore, just treat this as a dependent base 4015 // class initialization. FIXME: Should we try to check the 4016 // initialization anyway? It seems odd. 4017 if (ClassDecl->hasAnyDependentBases()) 4018 Dependent = true; 4019 else 4020 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4021 << BaseType << Context.getTypeDeclType(ClassDecl) 4022 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4023 } 4024 } 4025 4026 if (Dependent) { 4027 DiscardCleanupsInEvaluationContext(); 4028 4029 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4030 /*IsVirtual=*/false, 4031 InitRange.getBegin(), Init, 4032 InitRange.getEnd(), EllipsisLoc); 4033 } 4034 4035 // C++ [base.class.init]p2: 4036 // If a mem-initializer-id is ambiguous because it designates both 4037 // a direct non-virtual base class and an inherited virtual base 4038 // class, the mem-initializer is ill-formed. 4039 if (DirectBaseSpec && VirtualBaseSpec) 4040 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4041 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4042 4043 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4044 if (!BaseSpec) 4045 BaseSpec = VirtualBaseSpec; 4046 4047 // Initialize the base. 4048 bool InitList = true; 4049 MultiExprArg Args = Init; 4050 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4051 InitList = false; 4052 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4053 } 4054 4055 InitializedEntity BaseEntity = 4056 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4057 InitializationKind Kind = 4058 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4059 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4060 InitRange.getEnd()); 4061 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4062 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4063 if (BaseInit.isInvalid()) 4064 return true; 4065 4066 // C++11 [class.base.init]p7: 4067 // The initialization of each base and member constitutes a 4068 // full-expression. 4069 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4070 if (BaseInit.isInvalid()) 4071 return true; 4072 4073 // If we are in a dependent context, template instantiation will 4074 // perform this type-checking again. Just save the arguments that we 4075 // received in a ParenListExpr. 4076 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4077 // of the information that we have about the base 4078 // initializer. However, deconstructing the ASTs is a dicey process, 4079 // and this approach is far more likely to get the corner cases right. 4080 if (CurContext->isDependentContext()) 4081 BaseInit = Init; 4082 4083 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4084 BaseSpec->isVirtual(), 4085 InitRange.getBegin(), 4086 BaseInit.getAs<Expr>(), 4087 InitRange.getEnd(), EllipsisLoc); 4088 } 4089 4090 // Create a static_cast\<T&&>(expr). 4091 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4092 if (T.isNull()) T = E->getType(); 4093 QualType TargetType = SemaRef.BuildReferenceType( 4094 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4095 SourceLocation ExprLoc = E->getLocStart(); 4096 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4097 TargetType, ExprLoc); 4098 4099 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4100 SourceRange(ExprLoc, ExprLoc), 4101 E->getSourceRange()).get(); 4102 } 4103 4104 /// ImplicitInitializerKind - How an implicit base or member initializer should 4105 /// initialize its base or member. 4106 enum ImplicitInitializerKind { 4107 IIK_Default, 4108 IIK_Copy, 4109 IIK_Move, 4110 IIK_Inherit 4111 }; 4112 4113 static bool 4114 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4115 ImplicitInitializerKind ImplicitInitKind, 4116 CXXBaseSpecifier *BaseSpec, 4117 bool IsInheritedVirtualBase, 4118 CXXCtorInitializer *&CXXBaseInit) { 4119 InitializedEntity InitEntity 4120 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4121 IsInheritedVirtualBase); 4122 4123 ExprResult BaseInit; 4124 4125 switch (ImplicitInitKind) { 4126 case IIK_Inherit: 4127 case IIK_Default: { 4128 InitializationKind InitKind 4129 = InitializationKind::CreateDefault(Constructor->getLocation()); 4130 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4131 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4132 break; 4133 } 4134 4135 case IIK_Move: 4136 case IIK_Copy: { 4137 bool Moving = ImplicitInitKind == IIK_Move; 4138 ParmVarDecl *Param = Constructor->getParamDecl(0); 4139 QualType ParamType = Param->getType().getNonReferenceType(); 4140 4141 Expr *CopyCtorArg = 4142 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4143 SourceLocation(), Param, false, 4144 Constructor->getLocation(), ParamType, 4145 VK_LValue, nullptr); 4146 4147 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4148 4149 // Cast to the base class to avoid ambiguities. 4150 QualType ArgTy = 4151 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4152 ParamType.getQualifiers()); 4153 4154 if (Moving) { 4155 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4156 } 4157 4158 CXXCastPath BasePath; 4159 BasePath.push_back(BaseSpec); 4160 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4161 CK_UncheckedDerivedToBase, 4162 Moving ? VK_XValue : VK_LValue, 4163 &BasePath).get(); 4164 4165 InitializationKind InitKind 4166 = InitializationKind::CreateDirect(Constructor->getLocation(), 4167 SourceLocation(), SourceLocation()); 4168 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4169 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4170 break; 4171 } 4172 } 4173 4174 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4175 if (BaseInit.isInvalid()) 4176 return true; 4177 4178 CXXBaseInit = 4179 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4180 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4181 SourceLocation()), 4182 BaseSpec->isVirtual(), 4183 SourceLocation(), 4184 BaseInit.getAs<Expr>(), 4185 SourceLocation(), 4186 SourceLocation()); 4187 4188 return false; 4189 } 4190 4191 static bool RefersToRValueRef(Expr *MemRef) { 4192 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4193 return Referenced->getType()->isRValueReferenceType(); 4194 } 4195 4196 static bool 4197 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4198 ImplicitInitializerKind ImplicitInitKind, 4199 FieldDecl *Field, IndirectFieldDecl *Indirect, 4200 CXXCtorInitializer *&CXXMemberInit) { 4201 if (Field->isInvalidDecl()) 4202 return true; 4203 4204 SourceLocation Loc = Constructor->getLocation(); 4205 4206 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4207 bool Moving = ImplicitInitKind == IIK_Move; 4208 ParmVarDecl *Param = Constructor->getParamDecl(0); 4209 QualType ParamType = Param->getType().getNonReferenceType(); 4210 4211 // Suppress copying zero-width bitfields. 4212 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4213 return false; 4214 4215 Expr *MemberExprBase = 4216 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4217 SourceLocation(), Param, false, 4218 Loc, ParamType, VK_LValue, nullptr); 4219 4220 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4221 4222 if (Moving) { 4223 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4224 } 4225 4226 // Build a reference to this field within the parameter. 4227 CXXScopeSpec SS; 4228 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4229 Sema::LookupMemberName); 4230 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4231 : cast<ValueDecl>(Field), AS_public); 4232 MemberLookup.resolveKind(); 4233 ExprResult CtorArg 4234 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4235 ParamType, Loc, 4236 /*IsArrow=*/false, 4237 SS, 4238 /*TemplateKWLoc=*/SourceLocation(), 4239 /*FirstQualifierInScope=*/nullptr, 4240 MemberLookup, 4241 /*TemplateArgs=*/nullptr, 4242 /*S*/nullptr); 4243 if (CtorArg.isInvalid()) 4244 return true; 4245 4246 // C++11 [class.copy]p15: 4247 // - if a member m has rvalue reference type T&&, it is direct-initialized 4248 // with static_cast<T&&>(x.m); 4249 if (RefersToRValueRef(CtorArg.get())) { 4250 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4251 } 4252 4253 // When the field we are copying is an array, create index variables for 4254 // each dimension of the array. We use these index variables to subscript 4255 // the source array, and other clients (e.g., CodeGen) will perform the 4256 // necessary iteration with these index variables. 4257 SmallVector<VarDecl *, 4> IndexVariables; 4258 QualType BaseType = Field->getType(); 4259 QualType SizeType = SemaRef.Context.getSizeType(); 4260 bool InitializingArray = false; 4261 while (const ConstantArrayType *Array 4262 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 4263 InitializingArray = true; 4264 // Create the iteration variable for this array index. 4265 IdentifierInfo *IterationVarName = nullptr; 4266 { 4267 SmallString<8> Str; 4268 llvm::raw_svector_ostream OS(Str); 4269 OS << "__i" << IndexVariables.size(); 4270 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 4271 } 4272 VarDecl *IterationVar 4273 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 4274 IterationVarName, SizeType, 4275 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 4276 SC_None); 4277 IndexVariables.push_back(IterationVar); 4278 4279 // Create a reference to the iteration variable. 4280 ExprResult IterationVarRef 4281 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 4282 assert(!IterationVarRef.isInvalid() && 4283 "Reference to invented variable cannot fail!"); 4284 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 4285 assert(!IterationVarRef.isInvalid() && 4286 "Conversion of invented variable cannot fail!"); 4287 4288 // Subscript the array with this iteration variable. 4289 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 4290 IterationVarRef.get(), 4291 Loc); 4292 if (CtorArg.isInvalid()) 4293 return true; 4294 4295 BaseType = Array->getElementType(); 4296 } 4297 4298 // The array subscript expression is an lvalue, which is wrong for moving. 4299 if (Moving && InitializingArray) 4300 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4301 4302 // Construct the entity that we will be initializing. For an array, this 4303 // will be first element in the array, which may require several levels 4304 // of array-subscript entities. 4305 SmallVector<InitializedEntity, 4> Entities; 4306 Entities.reserve(1 + IndexVariables.size()); 4307 if (Indirect) 4308 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 4309 else 4310 Entities.push_back(InitializedEntity::InitializeMember(Field)); 4311 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 4312 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 4313 0, 4314 Entities.back())); 4315 4316 // Direct-initialize to use the copy constructor. 4317 InitializationKind InitKind = 4318 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4319 4320 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4321 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 4322 CtorArgE); 4323 4324 ExprResult MemberInit 4325 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 4326 MultiExprArg(&CtorArgE, 1)); 4327 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4328 if (MemberInit.isInvalid()) 4329 return true; 4330 4331 if (Indirect) { 4332 assert(IndexVariables.size() == 0 && 4333 "Indirect field improperly initialized"); 4334 CXXMemberInit 4335 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 4336 Loc, Loc, 4337 MemberInit.getAs<Expr>(), 4338 Loc); 4339 } else 4340 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 4341 Loc, MemberInit.getAs<Expr>(), 4342 Loc, 4343 IndexVariables.data(), 4344 IndexVariables.size()); 4345 return false; 4346 } 4347 4348 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4349 "Unhandled implicit init kind!"); 4350 4351 QualType FieldBaseElementType = 4352 SemaRef.Context.getBaseElementType(Field->getType()); 4353 4354 if (FieldBaseElementType->isRecordType()) { 4355 InitializedEntity InitEntity 4356 = Indirect? InitializedEntity::InitializeMember(Indirect) 4357 : InitializedEntity::InitializeMember(Field); 4358 InitializationKind InitKind = 4359 InitializationKind::CreateDefault(Loc); 4360 4361 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4362 ExprResult MemberInit = 4363 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4364 4365 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4366 if (MemberInit.isInvalid()) 4367 return true; 4368 4369 if (Indirect) 4370 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4371 Indirect, Loc, 4372 Loc, 4373 MemberInit.get(), 4374 Loc); 4375 else 4376 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4377 Field, Loc, Loc, 4378 MemberInit.get(), 4379 Loc); 4380 return false; 4381 } 4382 4383 if (!Field->getParent()->isUnion()) { 4384 if (FieldBaseElementType->isReferenceType()) { 4385 SemaRef.Diag(Constructor->getLocation(), 4386 diag::err_uninitialized_member_in_ctor) 4387 << (int)Constructor->isImplicit() 4388 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4389 << 0 << Field->getDeclName(); 4390 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4391 return true; 4392 } 4393 4394 if (FieldBaseElementType.isConstQualified()) { 4395 SemaRef.Diag(Constructor->getLocation(), 4396 diag::err_uninitialized_member_in_ctor) 4397 << (int)Constructor->isImplicit() 4398 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4399 << 1 << Field->getDeclName(); 4400 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4401 return true; 4402 } 4403 } 4404 4405 if (SemaRef.getLangOpts().ObjCAutoRefCount && 4406 FieldBaseElementType->isObjCRetainableType() && 4407 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 4408 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 4409 // ARC: 4410 // Default-initialize Objective-C pointers to NULL. 4411 CXXMemberInit 4412 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4413 Loc, Loc, 4414 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4415 Loc); 4416 return false; 4417 } 4418 4419 // Nothing to initialize. 4420 CXXMemberInit = nullptr; 4421 return false; 4422 } 4423 4424 namespace { 4425 struct BaseAndFieldInfo { 4426 Sema &S; 4427 CXXConstructorDecl *Ctor; 4428 bool AnyErrorsInInits; 4429 ImplicitInitializerKind IIK; 4430 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4431 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4432 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4433 4434 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4435 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4436 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4437 if (Ctor->getInheritedConstructor()) 4438 IIK = IIK_Inherit; 4439 else if (Generated && Ctor->isCopyConstructor()) 4440 IIK = IIK_Copy; 4441 else if (Generated && Ctor->isMoveConstructor()) 4442 IIK = IIK_Move; 4443 else 4444 IIK = IIK_Default; 4445 } 4446 4447 bool isImplicitCopyOrMove() const { 4448 switch (IIK) { 4449 case IIK_Copy: 4450 case IIK_Move: 4451 return true; 4452 4453 case IIK_Default: 4454 case IIK_Inherit: 4455 return false; 4456 } 4457 4458 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4459 } 4460 4461 bool addFieldInitializer(CXXCtorInitializer *Init) { 4462 AllToInit.push_back(Init); 4463 4464 // Check whether this initializer makes the field "used". 4465 if (Init->getInit()->HasSideEffects(S.Context)) 4466 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4467 4468 return false; 4469 } 4470 4471 bool isInactiveUnionMember(FieldDecl *Field) { 4472 RecordDecl *Record = Field->getParent(); 4473 if (!Record->isUnion()) 4474 return false; 4475 4476 if (FieldDecl *Active = 4477 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4478 return Active != Field->getCanonicalDecl(); 4479 4480 // In an implicit copy or move constructor, ignore any in-class initializer. 4481 if (isImplicitCopyOrMove()) 4482 return true; 4483 4484 // If there's no explicit initialization, the field is active only if it 4485 // has an in-class initializer... 4486 if (Field->hasInClassInitializer()) 4487 return false; 4488 // ... or it's an anonymous struct or union whose class has an in-class 4489 // initializer. 4490 if (!Field->isAnonymousStructOrUnion()) 4491 return true; 4492 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4493 return !FieldRD->hasInClassInitializer(); 4494 } 4495 4496 /// \brief Determine whether the given field is, or is within, a union member 4497 /// that is inactive (because there was an initializer given for a different 4498 /// member of the union, or because the union was not initialized at all). 4499 bool isWithinInactiveUnionMember(FieldDecl *Field, 4500 IndirectFieldDecl *Indirect) { 4501 if (!Indirect) 4502 return isInactiveUnionMember(Field); 4503 4504 for (auto *C : Indirect->chain()) { 4505 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4506 if (Field && isInactiveUnionMember(Field)) 4507 return true; 4508 } 4509 return false; 4510 } 4511 }; 4512 } 4513 4514 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4515 /// array type. 4516 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4517 if (T->isIncompleteArrayType()) 4518 return true; 4519 4520 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4521 if (!ArrayT->getSize()) 4522 return true; 4523 4524 T = ArrayT->getElementType(); 4525 } 4526 4527 return false; 4528 } 4529 4530 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4531 FieldDecl *Field, 4532 IndirectFieldDecl *Indirect = nullptr) { 4533 if (Field->isInvalidDecl()) 4534 return false; 4535 4536 // Overwhelmingly common case: we have a direct initializer for this field. 4537 if (CXXCtorInitializer *Init = 4538 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4539 return Info.addFieldInitializer(Init); 4540 4541 // C++11 [class.base.init]p8: 4542 // if the entity is a non-static data member that has a 4543 // brace-or-equal-initializer and either 4544 // -- the constructor's class is a union and no other variant member of that 4545 // union is designated by a mem-initializer-id or 4546 // -- the constructor's class is not a union, and, if the entity is a member 4547 // of an anonymous union, no other member of that union is designated by 4548 // a mem-initializer-id, 4549 // the entity is initialized as specified in [dcl.init]. 4550 // 4551 // We also apply the same rules to handle anonymous structs within anonymous 4552 // unions. 4553 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4554 return false; 4555 4556 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4557 ExprResult DIE = 4558 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4559 if (DIE.isInvalid()) 4560 return true; 4561 CXXCtorInitializer *Init; 4562 if (Indirect) 4563 Init = new (SemaRef.Context) 4564 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4565 SourceLocation(), DIE.get(), SourceLocation()); 4566 else 4567 Init = new (SemaRef.Context) 4568 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4569 SourceLocation(), DIE.get(), SourceLocation()); 4570 return Info.addFieldInitializer(Init); 4571 } 4572 4573 // Don't initialize incomplete or zero-length arrays. 4574 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4575 return false; 4576 4577 // Don't try to build an implicit initializer if there were semantic 4578 // errors in any of the initializers (and therefore we might be 4579 // missing some that the user actually wrote). 4580 if (Info.AnyErrorsInInits) 4581 return false; 4582 4583 CXXCtorInitializer *Init = nullptr; 4584 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4585 Indirect, Init)) 4586 return true; 4587 4588 if (!Init) 4589 return false; 4590 4591 return Info.addFieldInitializer(Init); 4592 } 4593 4594 bool 4595 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4596 CXXCtorInitializer *Initializer) { 4597 assert(Initializer->isDelegatingInitializer()); 4598 Constructor->setNumCtorInitializers(1); 4599 CXXCtorInitializer **initializer = 4600 new (Context) CXXCtorInitializer*[1]; 4601 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4602 Constructor->setCtorInitializers(initializer); 4603 4604 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4605 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4606 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4607 } 4608 4609 DelegatingCtorDecls.push_back(Constructor); 4610 4611 DiagnoseUninitializedFields(*this, Constructor); 4612 4613 return false; 4614 } 4615 4616 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4617 ArrayRef<CXXCtorInitializer *> Initializers) { 4618 if (Constructor->isDependentContext()) { 4619 // Just store the initializers as written, they will be checked during 4620 // instantiation. 4621 if (!Initializers.empty()) { 4622 Constructor->setNumCtorInitializers(Initializers.size()); 4623 CXXCtorInitializer **baseOrMemberInitializers = 4624 new (Context) CXXCtorInitializer*[Initializers.size()]; 4625 memcpy(baseOrMemberInitializers, Initializers.data(), 4626 Initializers.size() * sizeof(CXXCtorInitializer*)); 4627 Constructor->setCtorInitializers(baseOrMemberInitializers); 4628 } 4629 4630 // Let template instantiation know whether we had errors. 4631 if (AnyErrors) 4632 Constructor->setInvalidDecl(); 4633 4634 return false; 4635 } 4636 4637 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4638 4639 // We need to build the initializer AST according to order of construction 4640 // and not what user specified in the Initializers list. 4641 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4642 if (!ClassDecl) 4643 return true; 4644 4645 bool HadError = false; 4646 4647 for (unsigned i = 0; i < Initializers.size(); i++) { 4648 CXXCtorInitializer *Member = Initializers[i]; 4649 4650 if (Member->isBaseInitializer()) 4651 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4652 else { 4653 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4654 4655 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4656 for (auto *C : F->chain()) { 4657 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4658 if (FD && FD->getParent()->isUnion()) 4659 Info.ActiveUnionMember.insert(std::make_pair( 4660 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4661 } 4662 } else if (FieldDecl *FD = Member->getMember()) { 4663 if (FD->getParent()->isUnion()) 4664 Info.ActiveUnionMember.insert(std::make_pair( 4665 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4666 } 4667 } 4668 } 4669 4670 // Keep track of the direct virtual bases. 4671 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4672 for (auto &I : ClassDecl->bases()) { 4673 if (I.isVirtual()) 4674 DirectVBases.insert(&I); 4675 } 4676 4677 // Push virtual bases before others. 4678 for (auto &VBase : ClassDecl->vbases()) { 4679 if (CXXCtorInitializer *Value 4680 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4681 // [class.base.init]p7, per DR257: 4682 // A mem-initializer where the mem-initializer-id names a virtual base 4683 // class is ignored during execution of a constructor of any class that 4684 // is not the most derived class. 4685 if (ClassDecl->isAbstract()) { 4686 // FIXME: Provide a fixit to remove the base specifier. This requires 4687 // tracking the location of the associated comma for a base specifier. 4688 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4689 << VBase.getType() << ClassDecl; 4690 DiagnoseAbstractType(ClassDecl); 4691 } 4692 4693 Info.AllToInit.push_back(Value); 4694 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4695 // [class.base.init]p8, per DR257: 4696 // If a given [...] base class is not named by a mem-initializer-id 4697 // [...] and the entity is not a virtual base class of an abstract 4698 // class, then [...] the entity is default-initialized. 4699 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4700 CXXCtorInitializer *CXXBaseInit; 4701 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4702 &VBase, IsInheritedVirtualBase, 4703 CXXBaseInit)) { 4704 HadError = true; 4705 continue; 4706 } 4707 4708 Info.AllToInit.push_back(CXXBaseInit); 4709 } 4710 } 4711 4712 // Non-virtual bases. 4713 for (auto &Base : ClassDecl->bases()) { 4714 // Virtuals are in the virtual base list and already constructed. 4715 if (Base.isVirtual()) 4716 continue; 4717 4718 if (CXXCtorInitializer *Value 4719 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4720 Info.AllToInit.push_back(Value); 4721 } else if (!AnyErrors) { 4722 CXXCtorInitializer *CXXBaseInit; 4723 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4724 &Base, /*IsInheritedVirtualBase=*/false, 4725 CXXBaseInit)) { 4726 HadError = true; 4727 continue; 4728 } 4729 4730 Info.AllToInit.push_back(CXXBaseInit); 4731 } 4732 } 4733 4734 // Fields. 4735 for (auto *Mem : ClassDecl->decls()) { 4736 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4737 // C++ [class.bit]p2: 4738 // A declaration for a bit-field that omits the identifier declares an 4739 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4740 // initialized. 4741 if (F->isUnnamedBitfield()) 4742 continue; 4743 4744 // If we're not generating the implicit copy/move constructor, then we'll 4745 // handle anonymous struct/union fields based on their individual 4746 // indirect fields. 4747 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4748 continue; 4749 4750 if (CollectFieldInitializer(*this, Info, F)) 4751 HadError = true; 4752 continue; 4753 } 4754 4755 // Beyond this point, we only consider default initialization. 4756 if (Info.isImplicitCopyOrMove()) 4757 continue; 4758 4759 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4760 if (F->getType()->isIncompleteArrayType()) { 4761 assert(ClassDecl->hasFlexibleArrayMember() && 4762 "Incomplete array type is not valid"); 4763 continue; 4764 } 4765 4766 // Initialize each field of an anonymous struct individually. 4767 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4768 HadError = true; 4769 4770 continue; 4771 } 4772 } 4773 4774 unsigned NumInitializers = Info.AllToInit.size(); 4775 if (NumInitializers > 0) { 4776 Constructor->setNumCtorInitializers(NumInitializers); 4777 CXXCtorInitializer **baseOrMemberInitializers = 4778 new (Context) CXXCtorInitializer*[NumInitializers]; 4779 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4780 NumInitializers * sizeof(CXXCtorInitializer*)); 4781 Constructor->setCtorInitializers(baseOrMemberInitializers); 4782 4783 // Constructors implicitly reference the base and member 4784 // destructors. 4785 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4786 Constructor->getParent()); 4787 } 4788 4789 return HadError; 4790 } 4791 4792 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4793 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4794 const RecordDecl *RD = RT->getDecl(); 4795 if (RD->isAnonymousStructOrUnion()) { 4796 for (auto *Field : RD->fields()) 4797 PopulateKeysForFields(Field, IdealInits); 4798 return; 4799 } 4800 } 4801 IdealInits.push_back(Field->getCanonicalDecl()); 4802 } 4803 4804 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4805 return Context.getCanonicalType(BaseType).getTypePtr(); 4806 } 4807 4808 static const void *GetKeyForMember(ASTContext &Context, 4809 CXXCtorInitializer *Member) { 4810 if (!Member->isAnyMemberInitializer()) 4811 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4812 4813 return Member->getAnyMember()->getCanonicalDecl(); 4814 } 4815 4816 static void DiagnoseBaseOrMemInitializerOrder( 4817 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4818 ArrayRef<CXXCtorInitializer *> Inits) { 4819 if (Constructor->getDeclContext()->isDependentContext()) 4820 return; 4821 4822 // Don't check initializers order unless the warning is enabled at the 4823 // location of at least one initializer. 4824 bool ShouldCheckOrder = false; 4825 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4826 CXXCtorInitializer *Init = Inits[InitIndex]; 4827 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4828 Init->getSourceLocation())) { 4829 ShouldCheckOrder = true; 4830 break; 4831 } 4832 } 4833 if (!ShouldCheckOrder) 4834 return; 4835 4836 // Build the list of bases and members in the order that they'll 4837 // actually be initialized. The explicit initializers should be in 4838 // this same order but may be missing things. 4839 SmallVector<const void*, 32> IdealInitKeys; 4840 4841 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4842 4843 // 1. Virtual bases. 4844 for (const auto &VBase : ClassDecl->vbases()) 4845 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4846 4847 // 2. Non-virtual bases. 4848 for (const auto &Base : ClassDecl->bases()) { 4849 if (Base.isVirtual()) 4850 continue; 4851 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4852 } 4853 4854 // 3. Direct fields. 4855 for (auto *Field : ClassDecl->fields()) { 4856 if (Field->isUnnamedBitfield()) 4857 continue; 4858 4859 PopulateKeysForFields(Field, IdealInitKeys); 4860 } 4861 4862 unsigned NumIdealInits = IdealInitKeys.size(); 4863 unsigned IdealIndex = 0; 4864 4865 CXXCtorInitializer *PrevInit = nullptr; 4866 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4867 CXXCtorInitializer *Init = Inits[InitIndex]; 4868 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4869 4870 // Scan forward to try to find this initializer in the idealized 4871 // initializers list. 4872 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4873 if (InitKey == IdealInitKeys[IdealIndex]) 4874 break; 4875 4876 // If we didn't find this initializer, it must be because we 4877 // scanned past it on a previous iteration. That can only 4878 // happen if we're out of order; emit a warning. 4879 if (IdealIndex == NumIdealInits && PrevInit) { 4880 Sema::SemaDiagnosticBuilder D = 4881 SemaRef.Diag(PrevInit->getSourceLocation(), 4882 diag::warn_initializer_out_of_order); 4883 4884 if (PrevInit->isAnyMemberInitializer()) 4885 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4886 else 4887 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4888 4889 if (Init->isAnyMemberInitializer()) 4890 D << 0 << Init->getAnyMember()->getDeclName(); 4891 else 4892 D << 1 << Init->getTypeSourceInfo()->getType(); 4893 4894 // Move back to the initializer's location in the ideal list. 4895 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4896 if (InitKey == IdealInitKeys[IdealIndex]) 4897 break; 4898 4899 assert(IdealIndex < NumIdealInits && 4900 "initializer not found in initializer list"); 4901 } 4902 4903 PrevInit = Init; 4904 } 4905 } 4906 4907 namespace { 4908 bool CheckRedundantInit(Sema &S, 4909 CXXCtorInitializer *Init, 4910 CXXCtorInitializer *&PrevInit) { 4911 if (!PrevInit) { 4912 PrevInit = Init; 4913 return false; 4914 } 4915 4916 if (FieldDecl *Field = Init->getAnyMember()) 4917 S.Diag(Init->getSourceLocation(), 4918 diag::err_multiple_mem_initialization) 4919 << Field->getDeclName() 4920 << Init->getSourceRange(); 4921 else { 4922 const Type *BaseClass = Init->getBaseClass(); 4923 assert(BaseClass && "neither field nor base"); 4924 S.Diag(Init->getSourceLocation(), 4925 diag::err_multiple_base_initialization) 4926 << QualType(BaseClass, 0) 4927 << Init->getSourceRange(); 4928 } 4929 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4930 << 0 << PrevInit->getSourceRange(); 4931 4932 return true; 4933 } 4934 4935 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4936 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4937 4938 bool CheckRedundantUnionInit(Sema &S, 4939 CXXCtorInitializer *Init, 4940 RedundantUnionMap &Unions) { 4941 FieldDecl *Field = Init->getAnyMember(); 4942 RecordDecl *Parent = Field->getParent(); 4943 NamedDecl *Child = Field; 4944 4945 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4946 if (Parent->isUnion()) { 4947 UnionEntry &En = Unions[Parent]; 4948 if (En.first && En.first != Child) { 4949 S.Diag(Init->getSourceLocation(), 4950 diag::err_multiple_mem_union_initialization) 4951 << Field->getDeclName() 4952 << Init->getSourceRange(); 4953 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4954 << 0 << En.second->getSourceRange(); 4955 return true; 4956 } 4957 if (!En.first) { 4958 En.first = Child; 4959 En.second = Init; 4960 } 4961 if (!Parent->isAnonymousStructOrUnion()) 4962 return false; 4963 } 4964 4965 Child = Parent; 4966 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4967 } 4968 4969 return false; 4970 } 4971 } 4972 4973 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4974 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4975 SourceLocation ColonLoc, 4976 ArrayRef<CXXCtorInitializer*> MemInits, 4977 bool AnyErrors) { 4978 if (!ConstructorDecl) 4979 return; 4980 4981 AdjustDeclIfTemplate(ConstructorDecl); 4982 4983 CXXConstructorDecl *Constructor 4984 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4985 4986 if (!Constructor) { 4987 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4988 return; 4989 } 4990 4991 // Mapping for the duplicate initializers check. 4992 // For member initializers, this is keyed with a FieldDecl*. 4993 // For base initializers, this is keyed with a Type*. 4994 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4995 4996 // Mapping for the inconsistent anonymous-union initializers check. 4997 RedundantUnionMap MemberUnions; 4998 4999 bool HadError = false; 5000 for (unsigned i = 0; i < MemInits.size(); i++) { 5001 CXXCtorInitializer *Init = MemInits[i]; 5002 5003 // Set the source order index. 5004 Init->setSourceOrder(i); 5005 5006 if (Init->isAnyMemberInitializer()) { 5007 const void *Key = GetKeyForMember(Context, Init); 5008 if (CheckRedundantInit(*this, Init, Members[Key]) || 5009 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5010 HadError = true; 5011 } else if (Init->isBaseInitializer()) { 5012 const void *Key = GetKeyForMember(Context, Init); 5013 if (CheckRedundantInit(*this, Init, Members[Key])) 5014 HadError = true; 5015 } else { 5016 assert(Init->isDelegatingInitializer()); 5017 // This must be the only initializer 5018 if (MemInits.size() != 1) { 5019 Diag(Init->getSourceLocation(), 5020 diag::err_delegating_initializer_alone) 5021 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5022 // We will treat this as being the only initializer. 5023 } 5024 SetDelegatingInitializer(Constructor, MemInits[i]); 5025 // Return immediately as the initializer is set. 5026 return; 5027 } 5028 } 5029 5030 if (HadError) 5031 return; 5032 5033 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5034 5035 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5036 5037 DiagnoseUninitializedFields(*this, Constructor); 5038 } 5039 5040 void 5041 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5042 CXXRecordDecl *ClassDecl) { 5043 // Ignore dependent contexts. Also ignore unions, since their members never 5044 // have destructors implicitly called. 5045 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5046 return; 5047 5048 // FIXME: all the access-control diagnostics are positioned on the 5049 // field/base declaration. That's probably good; that said, the 5050 // user might reasonably want to know why the destructor is being 5051 // emitted, and we currently don't say. 5052 5053 // Non-static data members. 5054 for (auto *Field : ClassDecl->fields()) { 5055 if (Field->isInvalidDecl()) 5056 continue; 5057 5058 // Don't destroy incomplete or zero-length arrays. 5059 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5060 continue; 5061 5062 QualType FieldType = Context.getBaseElementType(Field->getType()); 5063 5064 const RecordType* RT = FieldType->getAs<RecordType>(); 5065 if (!RT) 5066 continue; 5067 5068 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5069 if (FieldClassDecl->isInvalidDecl()) 5070 continue; 5071 if (FieldClassDecl->hasIrrelevantDestructor()) 5072 continue; 5073 // The destructor for an implicit anonymous union member is never invoked. 5074 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5075 continue; 5076 5077 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5078 assert(Dtor && "No dtor found for FieldClassDecl!"); 5079 CheckDestructorAccess(Field->getLocation(), Dtor, 5080 PDiag(diag::err_access_dtor_field) 5081 << Field->getDeclName() 5082 << FieldType); 5083 5084 MarkFunctionReferenced(Location, Dtor); 5085 DiagnoseUseOfDecl(Dtor, Location); 5086 } 5087 5088 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5089 5090 // Bases. 5091 for (const auto &Base : ClassDecl->bases()) { 5092 // Bases are always records in a well-formed non-dependent class. 5093 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5094 5095 // Remember direct virtual bases. 5096 if (Base.isVirtual()) 5097 DirectVirtualBases.insert(RT); 5098 5099 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5100 // If our base class is invalid, we probably can't get its dtor anyway. 5101 if (BaseClassDecl->isInvalidDecl()) 5102 continue; 5103 if (BaseClassDecl->hasIrrelevantDestructor()) 5104 continue; 5105 5106 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5107 assert(Dtor && "No dtor found for BaseClassDecl!"); 5108 5109 // FIXME: caret should be on the start of the class name 5110 CheckDestructorAccess(Base.getLocStart(), Dtor, 5111 PDiag(diag::err_access_dtor_base) 5112 << Base.getType() 5113 << Base.getSourceRange(), 5114 Context.getTypeDeclType(ClassDecl)); 5115 5116 MarkFunctionReferenced(Location, Dtor); 5117 DiagnoseUseOfDecl(Dtor, Location); 5118 } 5119 5120 // Virtual bases. 5121 for (const auto &VBase : ClassDecl->vbases()) { 5122 // Bases are always records in a well-formed non-dependent class. 5123 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5124 5125 // Ignore direct virtual bases. 5126 if (DirectVirtualBases.count(RT)) 5127 continue; 5128 5129 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5130 // If our base class is invalid, we probably can't get its dtor anyway. 5131 if (BaseClassDecl->isInvalidDecl()) 5132 continue; 5133 if (BaseClassDecl->hasIrrelevantDestructor()) 5134 continue; 5135 5136 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5137 assert(Dtor && "No dtor found for BaseClassDecl!"); 5138 if (CheckDestructorAccess( 5139 ClassDecl->getLocation(), Dtor, 5140 PDiag(diag::err_access_dtor_vbase) 5141 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5142 Context.getTypeDeclType(ClassDecl)) == 5143 AR_accessible) { 5144 CheckDerivedToBaseConversion( 5145 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5146 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5147 SourceRange(), DeclarationName(), nullptr); 5148 } 5149 5150 MarkFunctionReferenced(Location, Dtor); 5151 DiagnoseUseOfDecl(Dtor, Location); 5152 } 5153 } 5154 5155 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5156 if (!CDtorDecl) 5157 return; 5158 5159 if (CXXConstructorDecl *Constructor 5160 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5161 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5162 DiagnoseUninitializedFields(*this, Constructor); 5163 } 5164 } 5165 5166 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5167 if (!getLangOpts().CPlusPlus) 5168 return false; 5169 5170 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5171 if (!RD) 5172 return false; 5173 5174 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5175 // class template specialization here, but doing so breaks a lot of code. 5176 5177 // We can't answer whether something is abstract until it has a 5178 // definition. If it's currently being defined, we'll walk back 5179 // over all the declarations when we have a full definition. 5180 const CXXRecordDecl *Def = RD->getDefinition(); 5181 if (!Def || Def->isBeingDefined()) 5182 return false; 5183 5184 return RD->isAbstract(); 5185 } 5186 5187 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5188 TypeDiagnoser &Diagnoser) { 5189 if (!isAbstractType(Loc, T)) 5190 return false; 5191 5192 T = Context.getBaseElementType(T); 5193 Diagnoser.diagnose(*this, Loc, T); 5194 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5195 return true; 5196 } 5197 5198 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5199 // Check if we've already emitted the list of pure virtual functions 5200 // for this class. 5201 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5202 return; 5203 5204 // If the diagnostic is suppressed, don't emit the notes. We're only 5205 // going to emit them once, so try to attach them to a diagnostic we're 5206 // actually going to show. 5207 if (Diags.isLastDiagnosticIgnored()) 5208 return; 5209 5210 CXXFinalOverriderMap FinalOverriders; 5211 RD->getFinalOverriders(FinalOverriders); 5212 5213 // Keep a set of seen pure methods so we won't diagnose the same method 5214 // more than once. 5215 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5216 5217 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5218 MEnd = FinalOverriders.end(); 5219 M != MEnd; 5220 ++M) { 5221 for (OverridingMethods::iterator SO = M->second.begin(), 5222 SOEnd = M->second.end(); 5223 SO != SOEnd; ++SO) { 5224 // C++ [class.abstract]p4: 5225 // A class is abstract if it contains or inherits at least one 5226 // pure virtual function for which the final overrider is pure 5227 // virtual. 5228 5229 // 5230 if (SO->second.size() != 1) 5231 continue; 5232 5233 if (!SO->second.front().Method->isPure()) 5234 continue; 5235 5236 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5237 continue; 5238 5239 Diag(SO->second.front().Method->getLocation(), 5240 diag::note_pure_virtual_function) 5241 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5242 } 5243 } 5244 5245 if (!PureVirtualClassDiagSet) 5246 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5247 PureVirtualClassDiagSet->insert(RD); 5248 } 5249 5250 namespace { 5251 struct AbstractUsageInfo { 5252 Sema &S; 5253 CXXRecordDecl *Record; 5254 CanQualType AbstractType; 5255 bool Invalid; 5256 5257 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5258 : S(S), Record(Record), 5259 AbstractType(S.Context.getCanonicalType( 5260 S.Context.getTypeDeclType(Record))), 5261 Invalid(false) {} 5262 5263 void DiagnoseAbstractType() { 5264 if (Invalid) return; 5265 S.DiagnoseAbstractType(Record); 5266 Invalid = true; 5267 } 5268 5269 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5270 }; 5271 5272 struct CheckAbstractUsage { 5273 AbstractUsageInfo &Info; 5274 const NamedDecl *Ctx; 5275 5276 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5277 : Info(Info), Ctx(Ctx) {} 5278 5279 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5280 switch (TL.getTypeLocClass()) { 5281 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5282 #define TYPELOC(CLASS, PARENT) \ 5283 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5284 #include "clang/AST/TypeLocNodes.def" 5285 } 5286 } 5287 5288 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5289 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5290 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5291 if (!TL.getParam(I)) 5292 continue; 5293 5294 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5295 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5296 } 5297 } 5298 5299 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5300 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5301 } 5302 5303 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5304 // Visit the type parameters from a permissive context. 5305 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5306 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5307 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5308 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5309 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5310 // TODO: other template argument types? 5311 } 5312 } 5313 5314 // Visit pointee types from a permissive context. 5315 #define CheckPolymorphic(Type) \ 5316 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5317 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5318 } 5319 CheckPolymorphic(PointerTypeLoc) 5320 CheckPolymorphic(ReferenceTypeLoc) 5321 CheckPolymorphic(MemberPointerTypeLoc) 5322 CheckPolymorphic(BlockPointerTypeLoc) 5323 CheckPolymorphic(AtomicTypeLoc) 5324 5325 /// Handle all the types we haven't given a more specific 5326 /// implementation for above. 5327 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5328 // Every other kind of type that we haven't called out already 5329 // that has an inner type is either (1) sugar or (2) contains that 5330 // inner type in some way as a subobject. 5331 if (TypeLoc Next = TL.getNextTypeLoc()) 5332 return Visit(Next, Sel); 5333 5334 // If there's no inner type and we're in a permissive context, 5335 // don't diagnose. 5336 if (Sel == Sema::AbstractNone) return; 5337 5338 // Check whether the type matches the abstract type. 5339 QualType T = TL.getType(); 5340 if (T->isArrayType()) { 5341 Sel = Sema::AbstractArrayType; 5342 T = Info.S.Context.getBaseElementType(T); 5343 } 5344 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5345 if (CT != Info.AbstractType) return; 5346 5347 // It matched; do some magic. 5348 if (Sel == Sema::AbstractArrayType) { 5349 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5350 << T << TL.getSourceRange(); 5351 } else { 5352 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5353 << Sel << T << TL.getSourceRange(); 5354 } 5355 Info.DiagnoseAbstractType(); 5356 } 5357 }; 5358 5359 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5360 Sema::AbstractDiagSelID Sel) { 5361 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5362 } 5363 5364 } 5365 5366 /// Check for invalid uses of an abstract type in a method declaration. 5367 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5368 CXXMethodDecl *MD) { 5369 // No need to do the check on definitions, which require that 5370 // the return/param types be complete. 5371 if (MD->doesThisDeclarationHaveABody()) 5372 return; 5373 5374 // For safety's sake, just ignore it if we don't have type source 5375 // information. This should never happen for non-implicit methods, 5376 // but... 5377 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5378 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5379 } 5380 5381 /// Check for invalid uses of an abstract type within a class definition. 5382 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5383 CXXRecordDecl *RD) { 5384 for (auto *D : RD->decls()) { 5385 if (D->isImplicit()) continue; 5386 5387 // Methods and method templates. 5388 if (isa<CXXMethodDecl>(D)) { 5389 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5390 } else if (isa<FunctionTemplateDecl>(D)) { 5391 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5392 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5393 5394 // Fields and static variables. 5395 } else if (isa<FieldDecl>(D)) { 5396 FieldDecl *FD = cast<FieldDecl>(D); 5397 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5398 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5399 } else if (isa<VarDecl>(D)) { 5400 VarDecl *VD = cast<VarDecl>(D); 5401 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5402 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5403 5404 // Nested classes and class templates. 5405 } else if (isa<CXXRecordDecl>(D)) { 5406 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5407 } else if (isa<ClassTemplateDecl>(D)) { 5408 CheckAbstractClassUsage(Info, 5409 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5410 } 5411 } 5412 } 5413 5414 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 5415 Attr *ClassAttr = getDLLAttr(Class); 5416 if (!ClassAttr) 5417 return; 5418 5419 assert(ClassAttr->getKind() == attr::DLLExport); 5420 5421 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5422 5423 if (TSK == TSK_ExplicitInstantiationDeclaration) 5424 // Don't go any further if this is just an explicit instantiation 5425 // declaration. 5426 return; 5427 5428 for (Decl *Member : Class->decls()) { 5429 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5430 if (!MD) 5431 continue; 5432 5433 if (Member->getAttr<DLLExportAttr>()) { 5434 if (MD->isUserProvided()) { 5435 // Instantiate non-default class member functions ... 5436 5437 // .. except for certain kinds of template specializations. 5438 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5439 continue; 5440 5441 S.MarkFunctionReferenced(Class->getLocation(), MD); 5442 5443 // The function will be passed to the consumer when its definition is 5444 // encountered. 5445 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5446 MD->isCopyAssignmentOperator() || 5447 MD->isMoveAssignmentOperator()) { 5448 // Synthesize and instantiate non-trivial implicit methods, explicitly 5449 // defaulted methods, and the copy and move assignment operators. The 5450 // latter are exported even if they are trivial, because the address of 5451 // an operator can be taken and should compare equal accross libraries. 5452 DiagnosticErrorTrap Trap(S.Diags); 5453 S.MarkFunctionReferenced(Class->getLocation(), MD); 5454 if (Trap.hasErrorOccurred()) { 5455 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5456 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5457 break; 5458 } 5459 5460 // There is no later point when we will see the definition of this 5461 // function, so pass it to the consumer now. 5462 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5463 } 5464 } 5465 } 5466 } 5467 5468 /// \brief Check class-level dllimport/dllexport attribute. 5469 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5470 Attr *ClassAttr = getDLLAttr(Class); 5471 5472 // MSVC inherits DLL attributes to partial class template specializations. 5473 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5474 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5475 if (Attr *TemplateAttr = 5476 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5477 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5478 A->setInherited(true); 5479 ClassAttr = A; 5480 } 5481 } 5482 } 5483 5484 if (!ClassAttr) 5485 return; 5486 5487 if (!Class->isExternallyVisible()) { 5488 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5489 << Class << ClassAttr; 5490 return; 5491 } 5492 5493 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5494 !ClassAttr->isInherited()) { 5495 // Diagnose dll attributes on members of class with dll attribute. 5496 for (Decl *Member : Class->decls()) { 5497 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5498 continue; 5499 InheritableAttr *MemberAttr = getDLLAttr(Member); 5500 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5501 continue; 5502 5503 Diag(MemberAttr->getLocation(), 5504 diag::err_attribute_dll_member_of_dll_class) 5505 << MemberAttr << ClassAttr; 5506 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5507 Member->setInvalidDecl(); 5508 } 5509 } 5510 5511 if (Class->getDescribedClassTemplate()) 5512 // Don't inherit dll attribute until the template is instantiated. 5513 return; 5514 5515 // The class is either imported or exported. 5516 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5517 5518 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5519 5520 // Ignore explicit dllexport on explicit class template instantiation declarations. 5521 if (ClassExported && !ClassAttr->isInherited() && 5522 TSK == TSK_ExplicitInstantiationDeclaration) { 5523 Class->dropAttr<DLLExportAttr>(); 5524 return; 5525 } 5526 5527 // Force declaration of implicit members so they can inherit the attribute. 5528 ForceDeclarationOfImplicitMembers(Class); 5529 5530 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5531 // seem to be true in practice? 5532 5533 for (Decl *Member : Class->decls()) { 5534 VarDecl *VD = dyn_cast<VarDecl>(Member); 5535 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5536 5537 // Only methods and static fields inherit the attributes. 5538 if (!VD && !MD) 5539 continue; 5540 5541 if (MD) { 5542 // Don't process deleted methods. 5543 if (MD->isDeleted()) 5544 continue; 5545 5546 if (MD->isInlined()) { 5547 // MinGW does not import or export inline methods. 5548 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5549 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5550 continue; 5551 5552 // MSVC versions before 2015 don't export the move assignment operators 5553 // and move constructor, so don't attempt to import/export them if 5554 // we have a definition. 5555 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5556 if ((MD->isMoveAssignmentOperator() || 5557 (Ctor && Ctor->isMoveConstructor())) && 5558 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5559 continue; 5560 5561 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5562 // operator is exported anyway. 5563 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5564 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5565 continue; 5566 } 5567 } 5568 5569 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5570 continue; 5571 5572 if (!getDLLAttr(Member)) { 5573 auto *NewAttr = 5574 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5575 NewAttr->setInherited(true); 5576 Member->addAttr(NewAttr); 5577 } 5578 } 5579 5580 if (ClassExported) 5581 DelayedDllExportClasses.push_back(Class); 5582 } 5583 5584 /// \brief Perform propagation of DLL attributes from a derived class to a 5585 /// templated base class for MS compatibility. 5586 void Sema::propagateDLLAttrToBaseClassTemplate( 5587 CXXRecordDecl *Class, Attr *ClassAttr, 5588 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5589 if (getDLLAttr( 5590 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5591 // If the base class template has a DLL attribute, don't try to change it. 5592 return; 5593 } 5594 5595 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5596 if (!getDLLAttr(BaseTemplateSpec) && 5597 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5598 TSK == TSK_ImplicitInstantiation)) { 5599 // The template hasn't been instantiated yet (or it has, but only as an 5600 // explicit instantiation declaration or implicit instantiation, which means 5601 // we haven't codegenned any members yet), so propagate the attribute. 5602 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5603 NewAttr->setInherited(true); 5604 BaseTemplateSpec->addAttr(NewAttr); 5605 5606 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5607 // needs to be run again to work see the new attribute. Otherwise this will 5608 // get run whenever the template is instantiated. 5609 if (TSK != TSK_Undeclared) 5610 checkClassLevelDLLAttribute(BaseTemplateSpec); 5611 5612 return; 5613 } 5614 5615 if (getDLLAttr(BaseTemplateSpec)) { 5616 // The template has already been specialized or instantiated with an 5617 // attribute, explicitly or through propagation. We should not try to change 5618 // it. 5619 return; 5620 } 5621 5622 // The template was previously instantiated or explicitly specialized without 5623 // a dll attribute, It's too late for us to add an attribute, so warn that 5624 // this is unsupported. 5625 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5626 << BaseTemplateSpec->isExplicitSpecialization(); 5627 Diag(ClassAttr->getLocation(), diag::note_attribute); 5628 if (BaseTemplateSpec->isExplicitSpecialization()) { 5629 Diag(BaseTemplateSpec->getLocation(), 5630 diag::note_template_class_explicit_specialization_was_here) 5631 << BaseTemplateSpec; 5632 } else { 5633 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5634 diag::note_template_class_instantiation_was_here) 5635 << BaseTemplateSpec; 5636 } 5637 } 5638 5639 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5640 SourceLocation DefaultLoc) { 5641 switch (S.getSpecialMember(MD)) { 5642 case Sema::CXXDefaultConstructor: 5643 S.DefineImplicitDefaultConstructor(DefaultLoc, 5644 cast<CXXConstructorDecl>(MD)); 5645 break; 5646 case Sema::CXXCopyConstructor: 5647 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5648 break; 5649 case Sema::CXXCopyAssignment: 5650 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5651 break; 5652 case Sema::CXXDestructor: 5653 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5654 break; 5655 case Sema::CXXMoveConstructor: 5656 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5657 break; 5658 case Sema::CXXMoveAssignment: 5659 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5660 break; 5661 case Sema::CXXInvalid: 5662 llvm_unreachable("Invalid special member."); 5663 } 5664 } 5665 5666 /// \brief Perform semantic checks on a class definition that has been 5667 /// completing, introducing implicitly-declared members, checking for 5668 /// abstract types, etc. 5669 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5670 if (!Record) 5671 return; 5672 5673 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5674 AbstractUsageInfo Info(*this, Record); 5675 CheckAbstractClassUsage(Info, Record); 5676 } 5677 5678 // If this is not an aggregate type and has no user-declared constructor, 5679 // complain about any non-static data members of reference or const scalar 5680 // type, since they will never get initializers. 5681 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5682 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5683 !Record->isLambda()) { 5684 bool Complained = false; 5685 for (const auto *F : Record->fields()) { 5686 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5687 continue; 5688 5689 if (F->getType()->isReferenceType() || 5690 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5691 if (!Complained) { 5692 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5693 << Record->getTagKind() << Record; 5694 Complained = true; 5695 } 5696 5697 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5698 << F->getType()->isReferenceType() 5699 << F->getDeclName(); 5700 } 5701 } 5702 } 5703 5704 if (Record->getIdentifier()) { 5705 // C++ [class.mem]p13: 5706 // If T is the name of a class, then each of the following shall have a 5707 // name different from T: 5708 // - every member of every anonymous union that is a member of class T. 5709 // 5710 // C++ [class.mem]p14: 5711 // In addition, if class T has a user-declared constructor (12.1), every 5712 // non-static data member of class T shall have a name different from T. 5713 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5714 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5715 ++I) { 5716 NamedDecl *D = *I; 5717 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5718 isa<IndirectFieldDecl>(D)) { 5719 Diag(D->getLocation(), diag::err_member_name_of_class) 5720 << D->getDeclName(); 5721 break; 5722 } 5723 } 5724 } 5725 5726 // Warn if the class has virtual methods but non-virtual public destructor. 5727 if (Record->isPolymorphic() && !Record->isDependentType()) { 5728 CXXDestructorDecl *dtor = Record->getDestructor(); 5729 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5730 !Record->hasAttr<FinalAttr>()) 5731 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5732 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5733 } 5734 5735 if (Record->isAbstract()) { 5736 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5737 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5738 << FA->isSpelledAsSealed(); 5739 DiagnoseAbstractType(Record); 5740 } 5741 } 5742 5743 bool HasMethodWithOverrideControl = false, 5744 HasOverridingMethodWithoutOverrideControl = false; 5745 if (!Record->isDependentType()) { 5746 for (auto *M : Record->methods()) { 5747 // See if a method overloads virtual methods in a base 5748 // class without overriding any. 5749 if (!M->isStatic()) 5750 DiagnoseHiddenVirtualMethods(M); 5751 if (M->hasAttr<OverrideAttr>()) 5752 HasMethodWithOverrideControl = true; 5753 else if (M->size_overridden_methods() > 0) 5754 HasOverridingMethodWithoutOverrideControl = true; 5755 // Check whether the explicitly-defaulted special members are valid. 5756 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5757 CheckExplicitlyDefaultedSpecialMember(M); 5758 5759 // For an explicitly defaulted or deleted special member, we defer 5760 // determining triviality until the class is complete. That time is now! 5761 CXXSpecialMember CSM = getSpecialMember(M); 5762 if (!M->isImplicit() && !M->isUserProvided()) { 5763 if (CSM != CXXInvalid) { 5764 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5765 5766 // Inform the class that we've finished declaring this member. 5767 Record->finishedDefaultedOrDeletedMember(M); 5768 } 5769 } 5770 5771 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5772 M->hasAttr<DLLExportAttr>()) { 5773 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5774 M->isTrivial() && 5775 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5776 CSM == CXXDestructor)) 5777 M->dropAttr<DLLExportAttr>(); 5778 5779 if (M->hasAttr<DLLExportAttr>()) { 5780 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5781 ActOnFinishInlineFunctionDef(M); 5782 } 5783 } 5784 } 5785 } 5786 5787 if (HasMethodWithOverrideControl && 5788 HasOverridingMethodWithoutOverrideControl) { 5789 // At least one method has the 'override' control declared. 5790 // Diagnose all other overridden methods which do not have 'override' specified on them. 5791 for (auto *M : Record->methods()) 5792 DiagnoseAbsenceOfOverrideControl(M); 5793 } 5794 5795 // ms_struct is a request to use the same ABI rules as MSVC. Check 5796 // whether this class uses any C++ features that are implemented 5797 // completely differently in MSVC, and if so, emit a diagnostic. 5798 // That diagnostic defaults to an error, but we allow projects to 5799 // map it down to a warning (or ignore it). It's a fairly common 5800 // practice among users of the ms_struct pragma to mass-annotate 5801 // headers, sweeping up a bunch of types that the project doesn't 5802 // really rely on MSVC-compatible layout for. We must therefore 5803 // support "ms_struct except for C++ stuff" as a secondary ABI. 5804 if (Record->isMsStruct(Context) && 5805 (Record->isPolymorphic() || Record->getNumBases())) { 5806 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5807 } 5808 5809 checkClassLevelDLLAttribute(Record); 5810 } 5811 5812 /// Look up the special member function that would be called by a special 5813 /// member function for a subobject of class type. 5814 /// 5815 /// \param Class The class type of the subobject. 5816 /// \param CSM The kind of special member function. 5817 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5818 /// \param ConstRHS True if this is a copy operation with a const object 5819 /// on its RHS, that is, if the argument to the outer special member 5820 /// function is 'const' and this is not a field marked 'mutable'. 5821 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 5822 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5823 unsigned FieldQuals, bool ConstRHS) { 5824 unsigned LHSQuals = 0; 5825 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5826 LHSQuals = FieldQuals; 5827 5828 unsigned RHSQuals = FieldQuals; 5829 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5830 RHSQuals = 0; 5831 else if (ConstRHS) 5832 RHSQuals |= Qualifiers::Const; 5833 5834 return S.LookupSpecialMember(Class, CSM, 5835 RHSQuals & Qualifiers::Const, 5836 RHSQuals & Qualifiers::Volatile, 5837 false, 5838 LHSQuals & Qualifiers::Const, 5839 LHSQuals & Qualifiers::Volatile); 5840 } 5841 5842 class Sema::InheritedConstructorInfo { 5843 Sema &S; 5844 SourceLocation UseLoc; 5845 5846 /// A mapping from the base classes through which the constructor was 5847 /// inherited to the using shadow declaration in that base class (or a null 5848 /// pointer if the constructor was declared in that base class). 5849 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 5850 InheritedFromBases; 5851 5852 public: 5853 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 5854 ConstructorUsingShadowDecl *Shadow) 5855 : S(S), UseLoc(UseLoc) { 5856 bool DiagnosedMultipleConstructedBases = false; 5857 CXXRecordDecl *ConstructedBase = nullptr; 5858 UsingDecl *ConstructedBaseUsing = nullptr; 5859 5860 // Find the set of such base class subobjects and check that there's a 5861 // unique constructed subobject. 5862 for (auto *D : Shadow->redecls()) { 5863 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 5864 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 5865 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 5866 5867 InheritedFromBases.insert( 5868 std::make_pair(DNominatedBase->getCanonicalDecl(), 5869 DShadow->getNominatedBaseClassShadowDecl())); 5870 if (DShadow->constructsVirtualBase()) 5871 InheritedFromBases.insert( 5872 std::make_pair(DConstructedBase->getCanonicalDecl(), 5873 DShadow->getConstructedBaseClassShadowDecl())); 5874 else 5875 assert(DNominatedBase == DConstructedBase); 5876 5877 // [class.inhctor.init]p2: 5878 // If the constructor was inherited from multiple base class subobjects 5879 // of type B, the program is ill-formed. 5880 if (!ConstructedBase) { 5881 ConstructedBase = DConstructedBase; 5882 ConstructedBaseUsing = D->getUsingDecl(); 5883 } else if (ConstructedBase != DConstructedBase && 5884 !Shadow->isInvalidDecl()) { 5885 if (!DiagnosedMultipleConstructedBases) { 5886 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 5887 << Shadow->getTargetDecl(); 5888 S.Diag(ConstructedBaseUsing->getLocation(), 5889 diag::note_ambiguous_inherited_constructor_using) 5890 << ConstructedBase; 5891 DiagnosedMultipleConstructedBases = true; 5892 } 5893 S.Diag(D->getUsingDecl()->getLocation(), 5894 diag::note_ambiguous_inherited_constructor_using) 5895 << DConstructedBase; 5896 } 5897 } 5898 5899 if (DiagnosedMultipleConstructedBases) 5900 Shadow->setInvalidDecl(); 5901 } 5902 5903 /// Find the constructor to use for inherited construction of a base class, 5904 /// and whether that base class constructor inherits the constructor from a 5905 /// virtual base class (in which case it won't actually invoke it). 5906 std::pair<CXXConstructorDecl *, bool> 5907 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 5908 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 5909 if (It == InheritedFromBases.end()) 5910 return std::make_pair(nullptr, false); 5911 5912 // This is an intermediary class. 5913 if (It->second) 5914 return std::make_pair( 5915 S.findInheritingConstructor(UseLoc, Ctor, It->second), 5916 It->second->constructsVirtualBase()); 5917 5918 // This is the base class from which the constructor was inherited. 5919 return std::make_pair(Ctor, false); 5920 } 5921 }; 5922 5923 /// Is the special member function which would be selected to perform the 5924 /// specified operation on the specified class type a constexpr constructor? 5925 static bool 5926 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5927 Sema::CXXSpecialMember CSM, unsigned Quals, 5928 bool ConstRHS, 5929 CXXConstructorDecl *InheritedCtor = nullptr, 5930 Sema::InheritedConstructorInfo *Inherited = nullptr) { 5931 // If we're inheriting a constructor, see if we need to call it for this base 5932 // class. 5933 if (InheritedCtor) { 5934 assert(CSM == Sema::CXXDefaultConstructor); 5935 auto BaseCtor = 5936 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 5937 if (BaseCtor) 5938 return BaseCtor->isConstexpr(); 5939 } 5940 5941 if (CSM == Sema::CXXDefaultConstructor) 5942 return ClassDecl->hasConstexprDefaultConstructor(); 5943 5944 Sema::SpecialMemberOverloadResult *SMOR = 5945 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5946 if (!SMOR || !SMOR->getMethod()) 5947 // A constructor we wouldn't select can't be "involved in initializing" 5948 // anything. 5949 return true; 5950 return SMOR->getMethod()->isConstexpr(); 5951 } 5952 5953 /// Determine whether the specified special member function would be constexpr 5954 /// if it were implicitly defined. 5955 static bool defaultedSpecialMemberIsConstexpr( 5956 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 5957 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 5958 Sema::InheritedConstructorInfo *Inherited = nullptr) { 5959 if (!S.getLangOpts().CPlusPlus11) 5960 return false; 5961 5962 // C++11 [dcl.constexpr]p4: 5963 // In the definition of a constexpr constructor [...] 5964 bool Ctor = true; 5965 switch (CSM) { 5966 case Sema::CXXDefaultConstructor: 5967 if (Inherited) 5968 break; 5969 // Since default constructor lookup is essentially trivial (and cannot 5970 // involve, for instance, template instantiation), we compute whether a 5971 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5972 // 5973 // This is important for performance; we need to know whether the default 5974 // constructor is constexpr to determine whether the type is a literal type. 5975 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5976 5977 case Sema::CXXCopyConstructor: 5978 case Sema::CXXMoveConstructor: 5979 // For copy or move constructors, we need to perform overload resolution. 5980 break; 5981 5982 case Sema::CXXCopyAssignment: 5983 case Sema::CXXMoveAssignment: 5984 if (!S.getLangOpts().CPlusPlus14) 5985 return false; 5986 // In C++1y, we need to perform overload resolution. 5987 Ctor = false; 5988 break; 5989 5990 case Sema::CXXDestructor: 5991 case Sema::CXXInvalid: 5992 return false; 5993 } 5994 5995 // -- if the class is a non-empty union, or for each non-empty anonymous 5996 // union member of a non-union class, exactly one non-static data member 5997 // shall be initialized; [DR1359] 5998 // 5999 // If we squint, this is guaranteed, since exactly one non-static data member 6000 // will be initialized (if the constructor isn't deleted), we just don't know 6001 // which one. 6002 if (Ctor && ClassDecl->isUnion()) 6003 return CSM == Sema::CXXDefaultConstructor 6004 ? ClassDecl->hasInClassInitializer() || 6005 !ClassDecl->hasVariantMembers() 6006 : true; 6007 6008 // -- the class shall not have any virtual base classes; 6009 if (Ctor && ClassDecl->getNumVBases()) 6010 return false; 6011 6012 // C++1y [class.copy]p26: 6013 // -- [the class] is a literal type, and 6014 if (!Ctor && !ClassDecl->isLiteral()) 6015 return false; 6016 6017 // -- every constructor involved in initializing [...] base class 6018 // sub-objects shall be a constexpr constructor; 6019 // -- the assignment operator selected to copy/move each direct base 6020 // class is a constexpr function, and 6021 for (const auto &B : ClassDecl->bases()) { 6022 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6023 if (!BaseType) continue; 6024 6025 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6026 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6027 InheritedCtor, Inherited)) 6028 return false; 6029 } 6030 6031 // -- every constructor involved in initializing non-static data members 6032 // [...] shall be a constexpr constructor; 6033 // -- every non-static data member and base class sub-object shall be 6034 // initialized 6035 // -- for each non-static data member of X that is of class type (or array 6036 // thereof), the assignment operator selected to copy/move that member is 6037 // a constexpr function 6038 for (const auto *F : ClassDecl->fields()) { 6039 if (F->isInvalidDecl()) 6040 continue; 6041 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6042 continue; 6043 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6044 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6045 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6046 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6047 BaseType.getCVRQualifiers(), 6048 ConstArg && !F->isMutable())) 6049 return false; 6050 } else if (CSM == Sema::CXXDefaultConstructor) { 6051 return false; 6052 } 6053 } 6054 6055 // All OK, it's constexpr! 6056 return true; 6057 } 6058 6059 static Sema::ImplicitExceptionSpecification 6060 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6061 switch (S.getSpecialMember(MD)) { 6062 case Sema::CXXDefaultConstructor: 6063 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 6064 case Sema::CXXCopyConstructor: 6065 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 6066 case Sema::CXXCopyAssignment: 6067 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 6068 case Sema::CXXMoveConstructor: 6069 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 6070 case Sema::CXXMoveAssignment: 6071 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 6072 case Sema::CXXDestructor: 6073 return S.ComputeDefaultedDtorExceptionSpec(MD); 6074 case Sema::CXXInvalid: 6075 break; 6076 } 6077 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 6078 "only special members have implicit exception specs"); 6079 return S.ComputeInheritingCtorExceptionSpec(Loc, 6080 cast<CXXConstructorDecl>(MD)); 6081 } 6082 6083 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6084 CXXMethodDecl *MD) { 6085 FunctionProtoType::ExtProtoInfo EPI; 6086 6087 // Build an exception specification pointing back at this member. 6088 EPI.ExceptionSpec.Type = EST_Unevaluated; 6089 EPI.ExceptionSpec.SourceDecl = MD; 6090 6091 // Set the calling convention to the default for C++ instance methods. 6092 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6093 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6094 /*IsCXXMethod=*/true)); 6095 return EPI; 6096 } 6097 6098 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6099 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6100 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6101 return; 6102 6103 // Evaluate the exception specification. 6104 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 6105 6106 // Update the type of the special member to use it. 6107 UpdateExceptionSpec(MD, ESI); 6108 6109 // A user-provided destructor can be defined outside the class. When that 6110 // happens, be sure to update the exception specification on both 6111 // declarations. 6112 const FunctionProtoType *CanonicalFPT = 6113 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6114 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6115 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6116 } 6117 6118 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6119 CXXRecordDecl *RD = MD->getParent(); 6120 CXXSpecialMember CSM = getSpecialMember(MD); 6121 6122 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6123 "not an explicitly-defaulted special member"); 6124 6125 // Whether this was the first-declared instance of the constructor. 6126 // This affects whether we implicitly add an exception spec and constexpr. 6127 bool First = MD == MD->getCanonicalDecl(); 6128 6129 bool HadError = false; 6130 6131 // C++11 [dcl.fct.def.default]p1: 6132 // A function that is explicitly defaulted shall 6133 // -- be a special member function (checked elsewhere), 6134 // -- have the same type (except for ref-qualifiers, and except that a 6135 // copy operation can take a non-const reference) as an implicit 6136 // declaration, and 6137 // -- not have default arguments. 6138 unsigned ExpectedParams = 1; 6139 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6140 ExpectedParams = 0; 6141 if (MD->getNumParams() != ExpectedParams) { 6142 // This also checks for default arguments: a copy or move constructor with a 6143 // default argument is classified as a default constructor, and assignment 6144 // operations and destructors can't have default arguments. 6145 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6146 << CSM << MD->getSourceRange(); 6147 HadError = true; 6148 } else if (MD->isVariadic()) { 6149 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6150 << CSM << MD->getSourceRange(); 6151 HadError = true; 6152 } 6153 6154 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6155 6156 bool CanHaveConstParam = false; 6157 if (CSM == CXXCopyConstructor) 6158 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6159 else if (CSM == CXXCopyAssignment) 6160 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6161 6162 QualType ReturnType = Context.VoidTy; 6163 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6164 // Check for return type matching. 6165 ReturnType = Type->getReturnType(); 6166 QualType ExpectedReturnType = 6167 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6168 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6169 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6170 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6171 HadError = true; 6172 } 6173 6174 // A defaulted special member cannot have cv-qualifiers. 6175 if (Type->getTypeQuals()) { 6176 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6177 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6178 HadError = true; 6179 } 6180 } 6181 6182 // Check for parameter type matching. 6183 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6184 bool HasConstParam = false; 6185 if (ExpectedParams && ArgType->isReferenceType()) { 6186 // Argument must be reference to possibly-const T. 6187 QualType ReferentType = ArgType->getPointeeType(); 6188 HasConstParam = ReferentType.isConstQualified(); 6189 6190 if (ReferentType.isVolatileQualified()) { 6191 Diag(MD->getLocation(), 6192 diag::err_defaulted_special_member_volatile_param) << CSM; 6193 HadError = true; 6194 } 6195 6196 if (HasConstParam && !CanHaveConstParam) { 6197 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6198 Diag(MD->getLocation(), 6199 diag::err_defaulted_special_member_copy_const_param) 6200 << (CSM == CXXCopyAssignment); 6201 // FIXME: Explain why this special member can't be const. 6202 } else { 6203 Diag(MD->getLocation(), 6204 diag::err_defaulted_special_member_move_const_param) 6205 << (CSM == CXXMoveAssignment); 6206 } 6207 HadError = true; 6208 } 6209 } else if (ExpectedParams) { 6210 // A copy assignment operator can take its argument by value, but a 6211 // defaulted one cannot. 6212 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6213 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6214 HadError = true; 6215 } 6216 6217 // C++11 [dcl.fct.def.default]p2: 6218 // An explicitly-defaulted function may be declared constexpr only if it 6219 // would have been implicitly declared as constexpr, 6220 // Do not apply this rule to members of class templates, since core issue 1358 6221 // makes such functions always instantiate to constexpr functions. For 6222 // functions which cannot be constexpr (for non-constructors in C++11 and for 6223 // destructors in C++1y), this is checked elsewhere. 6224 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6225 HasConstParam); 6226 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6227 : isa<CXXConstructorDecl>(MD)) && 6228 MD->isConstexpr() && !Constexpr && 6229 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6230 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6231 // FIXME: Explain why the special member can't be constexpr. 6232 HadError = true; 6233 } 6234 6235 // and may have an explicit exception-specification only if it is compatible 6236 // with the exception-specification on the implicit declaration. 6237 if (Type->hasExceptionSpec()) { 6238 // Delay the check if this is the first declaration of the special member, 6239 // since we may not have parsed some necessary in-class initializers yet. 6240 if (First) { 6241 // If the exception specification needs to be instantiated, do so now, 6242 // before we clobber it with an EST_Unevaluated specification below. 6243 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6244 InstantiateExceptionSpec(MD->getLocStart(), MD); 6245 Type = MD->getType()->getAs<FunctionProtoType>(); 6246 } 6247 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6248 } else 6249 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6250 } 6251 6252 // If a function is explicitly defaulted on its first declaration, 6253 if (First) { 6254 // -- it is implicitly considered to be constexpr if the implicit 6255 // definition would be, 6256 MD->setConstexpr(Constexpr); 6257 6258 // -- it is implicitly considered to have the same exception-specification 6259 // as if it had been implicitly declared, 6260 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6261 EPI.ExceptionSpec.Type = EST_Unevaluated; 6262 EPI.ExceptionSpec.SourceDecl = MD; 6263 MD->setType(Context.getFunctionType(ReturnType, 6264 llvm::makeArrayRef(&ArgType, 6265 ExpectedParams), 6266 EPI)); 6267 } 6268 6269 if (ShouldDeleteSpecialMember(MD, CSM)) { 6270 if (First) { 6271 SetDeclDeleted(MD, MD->getLocation()); 6272 } else { 6273 // C++11 [dcl.fct.def.default]p4: 6274 // [For a] user-provided explicitly-defaulted function [...] if such a 6275 // function is implicitly defined as deleted, the program is ill-formed. 6276 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6277 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6278 HadError = true; 6279 } 6280 } 6281 6282 if (HadError) 6283 MD->setInvalidDecl(); 6284 } 6285 6286 /// Check whether the exception specification provided for an 6287 /// explicitly-defaulted special member matches the exception specification 6288 /// that would have been generated for an implicit special member, per 6289 /// C++11 [dcl.fct.def.default]p2. 6290 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6291 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6292 // If the exception specification was explicitly specified but hadn't been 6293 // parsed when the method was defaulted, grab it now. 6294 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6295 SpecifiedType = 6296 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6297 6298 // Compute the implicit exception specification. 6299 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6300 /*IsCXXMethod=*/true); 6301 FunctionProtoType::ExtProtoInfo EPI(CC); 6302 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 6303 .getExceptionSpec(); 6304 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6305 Context.getFunctionType(Context.VoidTy, None, EPI)); 6306 6307 // Ensure that it matches. 6308 CheckEquivalentExceptionSpec( 6309 PDiag(diag::err_incorrect_defaulted_exception_spec) 6310 << getSpecialMember(MD), PDiag(), 6311 ImplicitType, SourceLocation(), 6312 SpecifiedType, MD->getLocation()); 6313 } 6314 6315 void Sema::CheckDelayedMemberExceptionSpecs() { 6316 decltype(DelayedExceptionSpecChecks) Checks; 6317 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6318 6319 std::swap(Checks, DelayedExceptionSpecChecks); 6320 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6321 6322 // Perform any deferred checking of exception specifications for virtual 6323 // destructors. 6324 for (auto &Check : Checks) 6325 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6326 6327 // Check that any explicitly-defaulted methods have exception specifications 6328 // compatible with their implicit exception specifications. 6329 for (auto &Spec : Specs) 6330 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6331 } 6332 6333 namespace { 6334 struct SpecialMemberDeletionInfo { 6335 Sema &S; 6336 CXXMethodDecl *MD; 6337 Sema::CXXSpecialMember CSM; 6338 Sema::InheritedConstructorInfo *ICI; 6339 bool Diagnose; 6340 6341 // Properties of the special member, computed for convenience. 6342 bool IsConstructor, IsAssignment, IsMove, ConstArg; 6343 SourceLocation Loc; 6344 6345 bool AllFieldsAreConst; 6346 6347 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6348 Sema::CXXSpecialMember CSM, 6349 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6350 : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose), 6351 IsConstructor(false), IsAssignment(false), IsMove(false), 6352 ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) { 6353 switch (CSM) { 6354 case Sema::CXXDefaultConstructor: 6355 case Sema::CXXCopyConstructor: 6356 IsConstructor = true; 6357 break; 6358 case Sema::CXXMoveConstructor: 6359 IsConstructor = true; 6360 IsMove = true; 6361 break; 6362 case Sema::CXXCopyAssignment: 6363 IsAssignment = true; 6364 break; 6365 case Sema::CXXMoveAssignment: 6366 IsAssignment = true; 6367 IsMove = true; 6368 break; 6369 case Sema::CXXDestructor: 6370 break; 6371 case Sema::CXXInvalid: 6372 llvm_unreachable("invalid special member kind"); 6373 } 6374 6375 if (MD->getNumParams()) { 6376 if (const ReferenceType *RT = 6377 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6378 ConstArg = RT->getPointeeType().isConstQualified(); 6379 } 6380 } 6381 6382 bool inUnion() const { return MD->getParent()->isUnion(); } 6383 6384 Sema::CXXSpecialMember getEffectiveCSM() { 6385 return ICI ? Sema::CXXInvalid : CSM; 6386 } 6387 6388 /// Look up the corresponding special member in the given class. 6389 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 6390 unsigned Quals, bool IsMutable) { 6391 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6392 ConstArg && !IsMutable); 6393 } 6394 6395 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6396 6397 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6398 bool shouldDeleteForField(FieldDecl *FD); 6399 bool shouldDeleteForAllConstMembers(); 6400 6401 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6402 unsigned Quals); 6403 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6404 Sema::SpecialMemberOverloadResult *SMOR, 6405 bool IsDtorCallInCtor); 6406 6407 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6408 }; 6409 } 6410 6411 /// Is the given special member inaccessible when used on the given 6412 /// sub-object. 6413 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6414 CXXMethodDecl *target) { 6415 /// If we're operating on a base class, the object type is the 6416 /// type of this special member. 6417 QualType objectTy; 6418 AccessSpecifier access = target->getAccess(); 6419 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6420 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6421 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6422 6423 // If we're operating on a field, the object type is the type of the field. 6424 } else { 6425 objectTy = S.Context.getTypeDeclType(target->getParent()); 6426 } 6427 6428 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6429 } 6430 6431 /// Check whether we should delete a special member due to the implicit 6432 /// definition containing a call to a special member of a subobject. 6433 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6434 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 6435 bool IsDtorCallInCtor) { 6436 CXXMethodDecl *Decl = SMOR->getMethod(); 6437 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6438 6439 int DiagKind = -1; 6440 6441 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6442 DiagKind = !Decl ? 0 : 1; 6443 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6444 DiagKind = 2; 6445 else if (!isAccessible(Subobj, Decl)) 6446 DiagKind = 3; 6447 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6448 !Decl->isTrivial()) { 6449 // A member of a union must have a trivial corresponding special member. 6450 // As a weird special case, a destructor call from a union's constructor 6451 // must be accessible and non-deleted, but need not be trivial. Such a 6452 // destructor is never actually called, but is semantically checked as 6453 // if it were. 6454 DiagKind = 4; 6455 } 6456 6457 if (DiagKind == -1) 6458 return false; 6459 6460 if (Diagnose) { 6461 if (Field) { 6462 S.Diag(Field->getLocation(), 6463 diag::note_deleted_special_member_class_subobject) 6464 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6465 << Field << DiagKind << IsDtorCallInCtor; 6466 } else { 6467 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6468 S.Diag(Base->getLocStart(), 6469 diag::note_deleted_special_member_class_subobject) 6470 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6471 << Base->getType() << DiagKind << IsDtorCallInCtor; 6472 } 6473 6474 if (DiagKind == 1) 6475 S.NoteDeletedFunction(Decl); 6476 // FIXME: Explain inaccessibility if DiagKind == 3. 6477 } 6478 6479 return true; 6480 } 6481 6482 /// Check whether we should delete a special member function due to having a 6483 /// direct or virtual base class or non-static data member of class type M. 6484 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6485 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6486 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6487 bool IsMutable = Field && Field->isMutable(); 6488 6489 // C++11 [class.ctor]p5: 6490 // -- any direct or virtual base class, or non-static data member with no 6491 // brace-or-equal-initializer, has class type M (or array thereof) and 6492 // either M has no default constructor or overload resolution as applied 6493 // to M's default constructor results in an ambiguity or in a function 6494 // that is deleted or inaccessible 6495 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6496 // -- a direct or virtual base class B that cannot be copied/moved because 6497 // overload resolution, as applied to B's corresponding special member, 6498 // results in an ambiguity or a function that is deleted or inaccessible 6499 // from the defaulted special member 6500 // C++11 [class.dtor]p5: 6501 // -- any direct or virtual base class [...] has a type with a destructor 6502 // that is deleted or inaccessible 6503 if (!(CSM == Sema::CXXDefaultConstructor && 6504 Field && Field->hasInClassInitializer()) && 6505 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6506 false)) 6507 return true; 6508 6509 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6510 // -- any direct or virtual base class or non-static data member has a 6511 // type with a destructor that is deleted or inaccessible 6512 if (IsConstructor) { 6513 Sema::SpecialMemberOverloadResult *SMOR = 6514 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6515 false, false, false, false, false); 6516 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6517 return true; 6518 } 6519 6520 return false; 6521 } 6522 6523 /// Check whether we should delete a special member function due to the class 6524 /// having a particular direct or virtual base class. 6525 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6526 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6527 // If program is correct, BaseClass cannot be null, but if it is, the error 6528 // must be reported elsewhere. 6529 if (!BaseClass) 6530 return false; 6531 // If we have an inheriting constructor, check whether we're calling an 6532 // inherited constructor instead of a default constructor. 6533 if (ICI) { 6534 assert(CSM == Sema::CXXDefaultConstructor); 6535 auto *BaseCtor = 6536 ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD) 6537 ->getInheritedConstructor() 6538 .getConstructor()) 6539 .first; 6540 if (BaseCtor) { 6541 if (BaseCtor->isDeleted() && Diagnose) { 6542 S.Diag(Base->getLocStart(), 6543 diag::note_deleted_special_member_class_subobject) 6544 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6545 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6546 S.NoteDeletedFunction(BaseCtor); 6547 } 6548 return BaseCtor->isDeleted(); 6549 } 6550 } 6551 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6552 } 6553 6554 /// Check whether we should delete a special member function due to the class 6555 /// having a particular non-static data member. 6556 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6557 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6558 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6559 6560 if (CSM == Sema::CXXDefaultConstructor) { 6561 // For a default constructor, all references must be initialized in-class 6562 // and, if a union, it must have a non-const member. 6563 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6564 if (Diagnose) 6565 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6566 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6567 return true; 6568 } 6569 // C++11 [class.ctor]p5: any non-variant non-static data member of 6570 // const-qualified type (or array thereof) with no 6571 // brace-or-equal-initializer does not have a user-provided default 6572 // constructor. 6573 if (!inUnion() && FieldType.isConstQualified() && 6574 !FD->hasInClassInitializer() && 6575 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6576 if (Diagnose) 6577 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6578 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6579 return true; 6580 } 6581 6582 if (inUnion() && !FieldType.isConstQualified()) 6583 AllFieldsAreConst = false; 6584 } else if (CSM == Sema::CXXCopyConstructor) { 6585 // For a copy constructor, data members must not be of rvalue reference 6586 // type. 6587 if (FieldType->isRValueReferenceType()) { 6588 if (Diagnose) 6589 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6590 << MD->getParent() << FD << FieldType; 6591 return true; 6592 } 6593 } else if (IsAssignment) { 6594 // For an assignment operator, data members must not be of reference type. 6595 if (FieldType->isReferenceType()) { 6596 if (Diagnose) 6597 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6598 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 6599 return true; 6600 } 6601 if (!FieldRecord && FieldType.isConstQualified()) { 6602 // C++11 [class.copy]p23: 6603 // -- a non-static data member of const non-class type (or array thereof) 6604 if (Diagnose) 6605 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6606 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 6607 return true; 6608 } 6609 } 6610 6611 if (FieldRecord) { 6612 // Some additional restrictions exist on the variant members. 6613 if (!inUnion() && FieldRecord->isUnion() && 6614 FieldRecord->isAnonymousStructOrUnion()) { 6615 bool AllVariantFieldsAreConst = true; 6616 6617 // FIXME: Handle anonymous unions declared within anonymous unions. 6618 for (auto *UI : FieldRecord->fields()) { 6619 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6620 6621 if (!UnionFieldType.isConstQualified()) 6622 AllVariantFieldsAreConst = false; 6623 6624 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6625 if (UnionFieldRecord && 6626 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6627 UnionFieldType.getCVRQualifiers())) 6628 return true; 6629 } 6630 6631 // At least one member in each anonymous union must be non-const 6632 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6633 !FieldRecord->field_empty()) { 6634 if (Diagnose) 6635 S.Diag(FieldRecord->getLocation(), 6636 diag::note_deleted_default_ctor_all_const) 6637 << !!ICI << MD->getParent() << /*anonymous union*/1; 6638 return true; 6639 } 6640 6641 // Don't check the implicit member of the anonymous union type. 6642 // This is technically non-conformant, but sanity demands it. 6643 return false; 6644 } 6645 6646 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6647 FieldType.getCVRQualifiers())) 6648 return true; 6649 } 6650 6651 return false; 6652 } 6653 6654 /// C++11 [class.ctor] p5: 6655 /// A defaulted default constructor for a class X is defined as deleted if 6656 /// X is a union and all of its variant members are of const-qualified type. 6657 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6658 // This is a silly definition, because it gives an empty union a deleted 6659 // default constructor. Don't do that. 6660 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 6661 !MD->getParent()->field_empty()) { 6662 if (Diagnose) 6663 S.Diag(MD->getParent()->getLocation(), 6664 diag::note_deleted_default_ctor_all_const) 6665 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6666 return true; 6667 } 6668 return false; 6669 } 6670 6671 /// Determine whether a defaulted special member function should be defined as 6672 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6673 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6674 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6675 InheritedConstructorInfo *ICI, 6676 bool Diagnose) { 6677 if (MD->isInvalidDecl()) 6678 return false; 6679 CXXRecordDecl *RD = MD->getParent(); 6680 assert(!RD->isDependentType() && "do deletion after instantiation"); 6681 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6682 return false; 6683 6684 // C++11 [expr.lambda.prim]p19: 6685 // The closure type associated with a lambda-expression has a 6686 // deleted (8.4.3) default constructor and a deleted copy 6687 // assignment operator. 6688 if (RD->isLambda() && 6689 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6690 if (Diagnose) 6691 Diag(RD->getLocation(), diag::note_lambda_decl); 6692 return true; 6693 } 6694 6695 // For an anonymous struct or union, the copy and assignment special members 6696 // will never be used, so skip the check. For an anonymous union declared at 6697 // namespace scope, the constructor and destructor are used. 6698 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6699 RD->isAnonymousStructOrUnion()) 6700 return false; 6701 6702 // C++11 [class.copy]p7, p18: 6703 // If the class definition declares a move constructor or move assignment 6704 // operator, an implicitly declared copy constructor or copy assignment 6705 // operator is defined as deleted. 6706 if (MD->isImplicit() && 6707 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6708 CXXMethodDecl *UserDeclaredMove = nullptr; 6709 6710 // In Microsoft mode, a user-declared move only causes the deletion of the 6711 // corresponding copy operation, not both copy operations. 6712 if (RD->hasUserDeclaredMoveConstructor() && 6713 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 6714 if (!Diagnose) return true; 6715 6716 // Find any user-declared move constructor. 6717 for (auto *I : RD->ctors()) { 6718 if (I->isMoveConstructor()) { 6719 UserDeclaredMove = I; 6720 break; 6721 } 6722 } 6723 assert(UserDeclaredMove); 6724 } else if (RD->hasUserDeclaredMoveAssignment() && 6725 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 6726 if (!Diagnose) return true; 6727 6728 // Find any user-declared move assignment operator. 6729 for (auto *I : RD->methods()) { 6730 if (I->isMoveAssignmentOperator()) { 6731 UserDeclaredMove = I; 6732 break; 6733 } 6734 } 6735 assert(UserDeclaredMove); 6736 } 6737 6738 if (UserDeclaredMove) { 6739 Diag(UserDeclaredMove->getLocation(), 6740 diag::note_deleted_copy_user_declared_move) 6741 << (CSM == CXXCopyAssignment) << RD 6742 << UserDeclaredMove->isMoveAssignmentOperator(); 6743 return true; 6744 } 6745 } 6746 6747 // Do access control from the special member function 6748 ContextRAII MethodContext(*this, MD); 6749 6750 // C++11 [class.dtor]p5: 6751 // -- for a virtual destructor, lookup of the non-array deallocation function 6752 // results in an ambiguity or in a function that is deleted or inaccessible 6753 if (CSM == CXXDestructor && MD->isVirtual()) { 6754 FunctionDecl *OperatorDelete = nullptr; 6755 DeclarationName Name = 6756 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6757 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 6758 OperatorDelete, /*Diagnose*/false)) { 6759 if (Diagnose) 6760 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 6761 return true; 6762 } 6763 } 6764 6765 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 6766 6767 for (auto &BI : RD->bases()) 6768 if ((SMI.IsAssignment || !BI.isVirtual()) && 6769 SMI.shouldDeleteForBase(&BI)) 6770 return true; 6771 6772 // Per DR1611, do not consider virtual bases of constructors of abstract 6773 // classes, since we are not going to construct them. For assignment 6774 // operators, we only assign (and thus only consider) direct bases. 6775 if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) { 6776 for (auto &BI : RD->vbases()) 6777 if (SMI.shouldDeleteForBase(&BI)) 6778 return true; 6779 } 6780 6781 for (auto *FI : RD->fields()) 6782 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 6783 SMI.shouldDeleteForField(FI)) 6784 return true; 6785 6786 if (SMI.shouldDeleteForAllConstMembers()) 6787 return true; 6788 6789 if (getLangOpts().CUDA) { 6790 // We should delete the special member in CUDA mode if target inference 6791 // failed. 6792 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 6793 Diagnose); 6794 } 6795 6796 return false; 6797 } 6798 6799 /// Perform lookup for a special member of the specified kind, and determine 6800 /// whether it is trivial. If the triviality can be determined without the 6801 /// lookup, skip it. This is intended for use when determining whether a 6802 /// special member of a containing object is trivial, and thus does not ever 6803 /// perform overload resolution for default constructors. 6804 /// 6805 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 6806 /// member that was most likely to be intended to be trivial, if any. 6807 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 6808 Sema::CXXSpecialMember CSM, unsigned Quals, 6809 bool ConstRHS, CXXMethodDecl **Selected) { 6810 if (Selected) 6811 *Selected = nullptr; 6812 6813 switch (CSM) { 6814 case Sema::CXXInvalid: 6815 llvm_unreachable("not a special member"); 6816 6817 case Sema::CXXDefaultConstructor: 6818 // C++11 [class.ctor]p5: 6819 // A default constructor is trivial if: 6820 // - all the [direct subobjects] have trivial default constructors 6821 // 6822 // Note, no overload resolution is performed in this case. 6823 if (RD->hasTrivialDefaultConstructor()) 6824 return true; 6825 6826 if (Selected) { 6827 // If there's a default constructor which could have been trivial, dig it 6828 // out. Otherwise, if there's any user-provided default constructor, point 6829 // to that as an example of why there's not a trivial one. 6830 CXXConstructorDecl *DefCtor = nullptr; 6831 if (RD->needsImplicitDefaultConstructor()) 6832 S.DeclareImplicitDefaultConstructor(RD); 6833 for (auto *CI : RD->ctors()) { 6834 if (!CI->isDefaultConstructor()) 6835 continue; 6836 DefCtor = CI; 6837 if (!DefCtor->isUserProvided()) 6838 break; 6839 } 6840 6841 *Selected = DefCtor; 6842 } 6843 6844 return false; 6845 6846 case Sema::CXXDestructor: 6847 // C++11 [class.dtor]p5: 6848 // A destructor is trivial if: 6849 // - all the direct [subobjects] have trivial destructors 6850 if (RD->hasTrivialDestructor()) 6851 return true; 6852 6853 if (Selected) { 6854 if (RD->needsImplicitDestructor()) 6855 S.DeclareImplicitDestructor(RD); 6856 *Selected = RD->getDestructor(); 6857 } 6858 6859 return false; 6860 6861 case Sema::CXXCopyConstructor: 6862 // C++11 [class.copy]p12: 6863 // A copy constructor is trivial if: 6864 // - the constructor selected to copy each direct [subobject] is trivial 6865 if (RD->hasTrivialCopyConstructor()) { 6866 if (Quals == Qualifiers::Const) 6867 // We must either select the trivial copy constructor or reach an 6868 // ambiguity; no need to actually perform overload resolution. 6869 return true; 6870 } else if (!Selected) { 6871 return false; 6872 } 6873 // In C++98, we are not supposed to perform overload resolution here, but we 6874 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 6875 // cases like B as having a non-trivial copy constructor: 6876 // struct A { template<typename T> A(T&); }; 6877 // struct B { mutable A a; }; 6878 goto NeedOverloadResolution; 6879 6880 case Sema::CXXCopyAssignment: 6881 // C++11 [class.copy]p25: 6882 // A copy assignment operator is trivial if: 6883 // - the assignment operator selected to copy each direct [subobject] is 6884 // trivial 6885 if (RD->hasTrivialCopyAssignment()) { 6886 if (Quals == Qualifiers::Const) 6887 return true; 6888 } else if (!Selected) { 6889 return false; 6890 } 6891 // In C++98, we are not supposed to perform overload resolution here, but we 6892 // treat that as a language defect. 6893 goto NeedOverloadResolution; 6894 6895 case Sema::CXXMoveConstructor: 6896 case Sema::CXXMoveAssignment: 6897 NeedOverloadResolution: 6898 Sema::SpecialMemberOverloadResult *SMOR = 6899 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 6900 6901 // The standard doesn't describe how to behave if the lookup is ambiguous. 6902 // We treat it as not making the member non-trivial, just like the standard 6903 // mandates for the default constructor. This should rarely matter, because 6904 // the member will also be deleted. 6905 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6906 return true; 6907 6908 if (!SMOR->getMethod()) { 6909 assert(SMOR->getKind() == 6910 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 6911 return false; 6912 } 6913 6914 // We deliberately don't check if we found a deleted special member. We're 6915 // not supposed to! 6916 if (Selected) 6917 *Selected = SMOR->getMethod(); 6918 return SMOR->getMethod()->isTrivial(); 6919 } 6920 6921 llvm_unreachable("unknown special method kind"); 6922 } 6923 6924 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 6925 for (auto *CI : RD->ctors()) 6926 if (!CI->isImplicit()) 6927 return CI; 6928 6929 // Look for constructor templates. 6930 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 6931 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 6932 if (CXXConstructorDecl *CD = 6933 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 6934 return CD; 6935 } 6936 6937 return nullptr; 6938 } 6939 6940 /// The kind of subobject we are checking for triviality. The values of this 6941 /// enumeration are used in diagnostics. 6942 enum TrivialSubobjectKind { 6943 /// The subobject is a base class. 6944 TSK_BaseClass, 6945 /// The subobject is a non-static data member. 6946 TSK_Field, 6947 /// The object is actually the complete object. 6948 TSK_CompleteObject 6949 }; 6950 6951 /// Check whether the special member selected for a given type would be trivial. 6952 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 6953 QualType SubType, bool ConstRHS, 6954 Sema::CXXSpecialMember CSM, 6955 TrivialSubobjectKind Kind, 6956 bool Diagnose) { 6957 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 6958 if (!SubRD) 6959 return true; 6960 6961 CXXMethodDecl *Selected; 6962 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 6963 ConstRHS, Diagnose ? &Selected : nullptr)) 6964 return true; 6965 6966 if (Diagnose) { 6967 if (ConstRHS) 6968 SubType.addConst(); 6969 6970 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6971 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6972 << Kind << SubType.getUnqualifiedType(); 6973 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6974 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6975 } else if (!Selected) 6976 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6977 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6978 else if (Selected->isUserProvided()) { 6979 if (Kind == TSK_CompleteObject) 6980 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6981 << Kind << SubType.getUnqualifiedType() << CSM; 6982 else { 6983 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6984 << Kind << SubType.getUnqualifiedType() << CSM; 6985 S.Diag(Selected->getLocation(), diag::note_declared_at); 6986 } 6987 } else { 6988 if (Kind != TSK_CompleteObject) 6989 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6990 << Kind << SubType.getUnqualifiedType() << CSM; 6991 6992 // Explain why the defaulted or deleted special member isn't trivial. 6993 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6994 } 6995 } 6996 6997 return false; 6998 } 6999 7000 /// Check whether the members of a class type allow a special member to be 7001 /// trivial. 7002 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7003 Sema::CXXSpecialMember CSM, 7004 bool ConstArg, bool Diagnose) { 7005 for (const auto *FI : RD->fields()) { 7006 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7007 continue; 7008 7009 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7010 7011 // Pretend anonymous struct or union members are members of this class. 7012 if (FI->isAnonymousStructOrUnion()) { 7013 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7014 CSM, ConstArg, Diagnose)) 7015 return false; 7016 continue; 7017 } 7018 7019 // C++11 [class.ctor]p5: 7020 // A default constructor is trivial if [...] 7021 // -- no non-static data member of its class has a 7022 // brace-or-equal-initializer 7023 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7024 if (Diagnose) 7025 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7026 return false; 7027 } 7028 7029 // Objective C ARC 4.3.5: 7030 // [...] nontrivally ownership-qualified types are [...] not trivially 7031 // default constructible, copy constructible, move constructible, copy 7032 // assignable, move assignable, or destructible [...] 7033 if (S.getLangOpts().ObjCAutoRefCount && 7034 FieldType.hasNonTrivialObjCLifetime()) { 7035 if (Diagnose) 7036 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7037 << RD << FieldType.getObjCLifetime(); 7038 return false; 7039 } 7040 7041 bool ConstRHS = ConstArg && !FI->isMutable(); 7042 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7043 CSM, TSK_Field, Diagnose)) 7044 return false; 7045 } 7046 7047 return true; 7048 } 7049 7050 /// Diagnose why the specified class does not have a trivial special member of 7051 /// the given kind. 7052 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7053 QualType Ty = Context.getRecordType(RD); 7054 7055 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7056 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7057 TSK_CompleteObject, /*Diagnose*/true); 7058 } 7059 7060 /// Determine whether a defaulted or deleted special member function is trivial, 7061 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7062 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7063 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7064 bool Diagnose) { 7065 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7066 7067 CXXRecordDecl *RD = MD->getParent(); 7068 7069 bool ConstArg = false; 7070 7071 // C++11 [class.copy]p12, p25: [DR1593] 7072 // A [special member] is trivial if [...] its parameter-type-list is 7073 // equivalent to the parameter-type-list of an implicit declaration [...] 7074 switch (CSM) { 7075 case CXXDefaultConstructor: 7076 case CXXDestructor: 7077 // Trivial default constructors and destructors cannot have parameters. 7078 break; 7079 7080 case CXXCopyConstructor: 7081 case CXXCopyAssignment: { 7082 // Trivial copy operations always have const, non-volatile parameter types. 7083 ConstArg = true; 7084 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7085 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7086 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7087 if (Diagnose) 7088 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7089 << Param0->getSourceRange() << Param0->getType() 7090 << Context.getLValueReferenceType( 7091 Context.getRecordType(RD).withConst()); 7092 return false; 7093 } 7094 break; 7095 } 7096 7097 case CXXMoveConstructor: 7098 case CXXMoveAssignment: { 7099 // Trivial move operations always have non-cv-qualified parameters. 7100 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7101 const RValueReferenceType *RT = 7102 Param0->getType()->getAs<RValueReferenceType>(); 7103 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7104 if (Diagnose) 7105 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7106 << Param0->getSourceRange() << Param0->getType() 7107 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7108 return false; 7109 } 7110 break; 7111 } 7112 7113 case CXXInvalid: 7114 llvm_unreachable("not a special member"); 7115 } 7116 7117 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7118 if (Diagnose) 7119 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7120 diag::note_nontrivial_default_arg) 7121 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7122 return false; 7123 } 7124 if (MD->isVariadic()) { 7125 if (Diagnose) 7126 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7127 return false; 7128 } 7129 7130 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7131 // A copy/move [constructor or assignment operator] is trivial if 7132 // -- the [member] selected to copy/move each direct base class subobject 7133 // is trivial 7134 // 7135 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7136 // A [default constructor or destructor] is trivial if 7137 // -- all the direct base classes have trivial [default constructors or 7138 // destructors] 7139 for (const auto &BI : RD->bases()) 7140 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7141 ConstArg, CSM, TSK_BaseClass, Diagnose)) 7142 return false; 7143 7144 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7145 // A copy/move [constructor or assignment operator] for a class X is 7146 // trivial if 7147 // -- for each non-static data member of X that is of class type (or array 7148 // thereof), the constructor selected to copy/move that member is 7149 // trivial 7150 // 7151 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7152 // A [default constructor or destructor] is trivial if 7153 // -- for all of the non-static data members of its class that are of class 7154 // type (or array thereof), each such class has a trivial [default 7155 // constructor or destructor] 7156 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 7157 return false; 7158 7159 // C++11 [class.dtor]p5: 7160 // A destructor is trivial if [...] 7161 // -- the destructor is not virtual 7162 if (CSM == CXXDestructor && MD->isVirtual()) { 7163 if (Diagnose) 7164 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7165 return false; 7166 } 7167 7168 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7169 // A [special member] for class X is trivial if [...] 7170 // -- class X has no virtual functions and no virtual base classes 7171 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7172 if (!Diagnose) 7173 return false; 7174 7175 if (RD->getNumVBases()) { 7176 // Check for virtual bases. We already know that the corresponding 7177 // member in all bases is trivial, so vbases must all be direct. 7178 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7179 assert(BS.isVirtual()); 7180 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7181 return false; 7182 } 7183 7184 // Must have a virtual method. 7185 for (const auto *MI : RD->methods()) { 7186 if (MI->isVirtual()) { 7187 SourceLocation MLoc = MI->getLocStart(); 7188 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7189 return false; 7190 } 7191 } 7192 7193 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7194 } 7195 7196 // Looks like it's trivial! 7197 return true; 7198 } 7199 7200 namespace { 7201 struct FindHiddenVirtualMethod { 7202 Sema *S; 7203 CXXMethodDecl *Method; 7204 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7205 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7206 7207 private: 7208 /// Check whether any most overriden method from MD in Methods 7209 static bool CheckMostOverridenMethods( 7210 const CXXMethodDecl *MD, 7211 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7212 if (MD->size_overridden_methods() == 0) 7213 return Methods.count(MD->getCanonicalDecl()); 7214 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7215 E = MD->end_overridden_methods(); 7216 I != E; ++I) 7217 if (CheckMostOverridenMethods(*I, Methods)) 7218 return true; 7219 return false; 7220 } 7221 7222 public: 7223 /// Member lookup function that determines whether a given C++ 7224 /// method overloads virtual methods in a base class without overriding any, 7225 /// to be used with CXXRecordDecl::lookupInBases(). 7226 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7227 RecordDecl *BaseRecord = 7228 Specifier->getType()->getAs<RecordType>()->getDecl(); 7229 7230 DeclarationName Name = Method->getDeclName(); 7231 assert(Name.getNameKind() == DeclarationName::Identifier); 7232 7233 bool foundSameNameMethod = false; 7234 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7235 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7236 Path.Decls = Path.Decls.slice(1)) { 7237 NamedDecl *D = Path.Decls.front(); 7238 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7239 MD = MD->getCanonicalDecl(); 7240 foundSameNameMethod = true; 7241 // Interested only in hidden virtual methods. 7242 if (!MD->isVirtual()) 7243 continue; 7244 // If the method we are checking overrides a method from its base 7245 // don't warn about the other overloaded methods. Clang deviates from 7246 // GCC by only diagnosing overloads of inherited virtual functions that 7247 // do not override any other virtual functions in the base. GCC's 7248 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7249 // function from a base class. These cases may be better served by a 7250 // warning (not specific to virtual functions) on call sites when the 7251 // call would select a different function from the base class, were it 7252 // visible. 7253 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7254 if (!S->IsOverload(Method, MD, false)) 7255 return true; 7256 // Collect the overload only if its hidden. 7257 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7258 overloadedMethods.push_back(MD); 7259 } 7260 } 7261 7262 if (foundSameNameMethod) 7263 OverloadedMethods.append(overloadedMethods.begin(), 7264 overloadedMethods.end()); 7265 return foundSameNameMethod; 7266 } 7267 }; 7268 } // end anonymous namespace 7269 7270 /// \brief Add the most overriden methods from MD to Methods 7271 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7272 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7273 if (MD->size_overridden_methods() == 0) 7274 Methods.insert(MD->getCanonicalDecl()); 7275 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7276 E = MD->end_overridden_methods(); 7277 I != E; ++I) 7278 AddMostOverridenMethods(*I, Methods); 7279 } 7280 7281 /// \brief Check if a method overloads virtual methods in a base class without 7282 /// overriding any. 7283 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7284 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7285 if (!MD->getDeclName().isIdentifier()) 7286 return; 7287 7288 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7289 /*bool RecordPaths=*/false, 7290 /*bool DetectVirtual=*/false); 7291 FindHiddenVirtualMethod FHVM; 7292 FHVM.Method = MD; 7293 FHVM.S = this; 7294 7295 // Keep the base methods that were overriden or introduced in the subclass 7296 // by 'using' in a set. A base method not in this set is hidden. 7297 CXXRecordDecl *DC = MD->getParent(); 7298 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7299 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7300 NamedDecl *ND = *I; 7301 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7302 ND = shad->getTargetDecl(); 7303 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7304 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7305 } 7306 7307 if (DC->lookupInBases(FHVM, Paths)) 7308 OverloadedMethods = FHVM.OverloadedMethods; 7309 } 7310 7311 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7312 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7313 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7314 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7315 PartialDiagnostic PD = PDiag( 7316 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7317 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7318 Diag(overloadedMD->getLocation(), PD); 7319 } 7320 } 7321 7322 /// \brief Diagnose methods which overload virtual methods in a base class 7323 /// without overriding any. 7324 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7325 if (MD->isInvalidDecl()) 7326 return; 7327 7328 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7329 return; 7330 7331 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7332 FindHiddenVirtualMethods(MD, OverloadedMethods); 7333 if (!OverloadedMethods.empty()) { 7334 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7335 << MD << (OverloadedMethods.size() > 1); 7336 7337 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7338 } 7339 } 7340 7341 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7342 Decl *TagDecl, 7343 SourceLocation LBrac, 7344 SourceLocation RBrac, 7345 AttributeList *AttrList) { 7346 if (!TagDecl) 7347 return; 7348 7349 AdjustDeclIfTemplate(TagDecl); 7350 7351 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7352 if (l->getKind() != AttributeList::AT_Visibility) 7353 continue; 7354 l->setInvalid(); 7355 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7356 l->getName(); 7357 } 7358 7359 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7360 // strict aliasing violation! 7361 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7362 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7363 7364 CheckCompletedCXXClass( 7365 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7366 } 7367 7368 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7369 /// special functions, such as the default constructor, copy 7370 /// constructor, or destructor, to the given C++ class (C++ 7371 /// [special]p1). This routine can only be executed just before the 7372 /// definition of the class is complete. 7373 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7374 if (ClassDecl->needsImplicitDefaultConstructor()) { 7375 ++ASTContext::NumImplicitDefaultConstructors; 7376 7377 if (ClassDecl->hasInheritedConstructor()) 7378 DeclareImplicitDefaultConstructor(ClassDecl); 7379 } 7380 7381 if (ClassDecl->needsImplicitCopyConstructor()) { 7382 ++ASTContext::NumImplicitCopyConstructors; 7383 7384 // If the properties or semantics of the copy constructor couldn't be 7385 // determined while the class was being declared, force a declaration 7386 // of it now. 7387 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7388 ClassDecl->hasInheritedConstructor()) 7389 DeclareImplicitCopyConstructor(ClassDecl); 7390 } 7391 7392 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7393 ++ASTContext::NumImplicitMoveConstructors; 7394 7395 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7396 ClassDecl->hasInheritedConstructor()) 7397 DeclareImplicitMoveConstructor(ClassDecl); 7398 } 7399 7400 if (ClassDecl->needsImplicitCopyAssignment()) { 7401 ++ASTContext::NumImplicitCopyAssignmentOperators; 7402 7403 // If we have a dynamic class, then the copy assignment operator may be 7404 // virtual, so we have to declare it immediately. This ensures that, e.g., 7405 // it shows up in the right place in the vtable and that we diagnose 7406 // problems with the implicit exception specification. 7407 if (ClassDecl->isDynamicClass() || 7408 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7409 ClassDecl->hasInheritedAssignment()) 7410 DeclareImplicitCopyAssignment(ClassDecl); 7411 } 7412 7413 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7414 ++ASTContext::NumImplicitMoveAssignmentOperators; 7415 7416 // Likewise for the move assignment operator. 7417 if (ClassDecl->isDynamicClass() || 7418 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7419 ClassDecl->hasInheritedAssignment()) 7420 DeclareImplicitMoveAssignment(ClassDecl); 7421 } 7422 7423 if (ClassDecl->needsImplicitDestructor()) { 7424 ++ASTContext::NumImplicitDestructors; 7425 7426 // If we have a dynamic class, then the destructor may be virtual, so we 7427 // have to declare the destructor immediately. This ensures that, e.g., it 7428 // shows up in the right place in the vtable and that we diagnose problems 7429 // with the implicit exception specification. 7430 if (ClassDecl->isDynamicClass() || 7431 ClassDecl->needsOverloadResolutionForDestructor()) 7432 DeclareImplicitDestructor(ClassDecl); 7433 } 7434 } 7435 7436 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7437 if (!D) 7438 return 0; 7439 7440 // The order of template parameters is not important here. All names 7441 // get added to the same scope. 7442 SmallVector<TemplateParameterList *, 4> ParameterLists; 7443 7444 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7445 D = TD->getTemplatedDecl(); 7446 7447 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7448 ParameterLists.push_back(PSD->getTemplateParameters()); 7449 7450 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7451 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7452 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7453 7454 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7455 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7456 ParameterLists.push_back(FTD->getTemplateParameters()); 7457 } 7458 } 7459 7460 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7461 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7462 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7463 7464 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7465 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7466 ParameterLists.push_back(CTD->getTemplateParameters()); 7467 } 7468 } 7469 7470 unsigned Count = 0; 7471 for (TemplateParameterList *Params : ParameterLists) { 7472 if (Params->size() > 0) 7473 // Ignore explicit specializations; they don't contribute to the template 7474 // depth. 7475 ++Count; 7476 for (NamedDecl *Param : *Params) { 7477 if (Param->getDeclName()) { 7478 S->AddDecl(Param); 7479 IdResolver.AddDecl(Param); 7480 } 7481 } 7482 } 7483 7484 return Count; 7485 } 7486 7487 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7488 if (!RecordD) return; 7489 AdjustDeclIfTemplate(RecordD); 7490 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7491 PushDeclContext(S, Record); 7492 } 7493 7494 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7495 if (!RecordD) return; 7496 PopDeclContext(); 7497 } 7498 7499 /// This is used to implement the constant expression evaluation part of the 7500 /// attribute enable_if extension. There is nothing in standard C++ which would 7501 /// require reentering parameters. 7502 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7503 if (!Param) 7504 return; 7505 7506 S->AddDecl(Param); 7507 if (Param->getDeclName()) 7508 IdResolver.AddDecl(Param); 7509 } 7510 7511 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7512 /// parsing a top-level (non-nested) C++ class, and we are now 7513 /// parsing those parts of the given Method declaration that could 7514 /// not be parsed earlier (C++ [class.mem]p2), such as default 7515 /// arguments. This action should enter the scope of the given 7516 /// Method declaration as if we had just parsed the qualified method 7517 /// name. However, it should not bring the parameters into scope; 7518 /// that will be performed by ActOnDelayedCXXMethodParameter. 7519 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7520 } 7521 7522 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7523 /// C++ method declaration. We're (re-)introducing the given 7524 /// function parameter into scope for use in parsing later parts of 7525 /// the method declaration. For example, we could see an 7526 /// ActOnParamDefaultArgument event for this parameter. 7527 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7528 if (!ParamD) 7529 return; 7530 7531 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7532 7533 // If this parameter has an unparsed default argument, clear it out 7534 // to make way for the parsed default argument. 7535 if (Param->hasUnparsedDefaultArg()) 7536 Param->setDefaultArg(nullptr); 7537 7538 S->AddDecl(Param); 7539 if (Param->getDeclName()) 7540 IdResolver.AddDecl(Param); 7541 } 7542 7543 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7544 /// processing the delayed method declaration for Method. The method 7545 /// declaration is now considered finished. There may be a separate 7546 /// ActOnStartOfFunctionDef action later (not necessarily 7547 /// immediately!) for this method, if it was also defined inside the 7548 /// class body. 7549 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7550 if (!MethodD) 7551 return; 7552 7553 AdjustDeclIfTemplate(MethodD); 7554 7555 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7556 7557 // Now that we have our default arguments, check the constructor 7558 // again. It could produce additional diagnostics or affect whether 7559 // the class has implicitly-declared destructors, among other 7560 // things. 7561 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7562 CheckConstructor(Constructor); 7563 7564 // Check the default arguments, which we may have added. 7565 if (!Method->isInvalidDecl()) 7566 CheckCXXDefaultArguments(Method); 7567 } 7568 7569 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7570 /// the well-formedness of the constructor declarator @p D with type @p 7571 /// R. If there are any errors in the declarator, this routine will 7572 /// emit diagnostics and set the invalid bit to true. In any case, the type 7573 /// will be updated to reflect a well-formed type for the constructor and 7574 /// returned. 7575 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7576 StorageClass &SC) { 7577 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7578 7579 // C++ [class.ctor]p3: 7580 // A constructor shall not be virtual (10.3) or static (9.4). A 7581 // constructor can be invoked for a const, volatile or const 7582 // volatile object. A constructor shall not be declared const, 7583 // volatile, or const volatile (9.3.2). 7584 if (isVirtual) { 7585 if (!D.isInvalidType()) 7586 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7587 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7588 << SourceRange(D.getIdentifierLoc()); 7589 D.setInvalidType(); 7590 } 7591 if (SC == SC_Static) { 7592 if (!D.isInvalidType()) 7593 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7594 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7595 << SourceRange(D.getIdentifierLoc()); 7596 D.setInvalidType(); 7597 SC = SC_None; 7598 } 7599 7600 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7601 diagnoseIgnoredQualifiers( 7602 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7603 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7604 D.getDeclSpec().getRestrictSpecLoc(), 7605 D.getDeclSpec().getAtomicSpecLoc()); 7606 D.setInvalidType(); 7607 } 7608 7609 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7610 if (FTI.TypeQuals != 0) { 7611 if (FTI.TypeQuals & Qualifiers::Const) 7612 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7613 << "const" << SourceRange(D.getIdentifierLoc()); 7614 if (FTI.TypeQuals & Qualifiers::Volatile) 7615 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7616 << "volatile" << SourceRange(D.getIdentifierLoc()); 7617 if (FTI.TypeQuals & Qualifiers::Restrict) 7618 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7619 << "restrict" << SourceRange(D.getIdentifierLoc()); 7620 D.setInvalidType(); 7621 } 7622 7623 // C++0x [class.ctor]p4: 7624 // A constructor shall not be declared with a ref-qualifier. 7625 if (FTI.hasRefQualifier()) { 7626 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7627 << FTI.RefQualifierIsLValueRef 7628 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7629 D.setInvalidType(); 7630 } 7631 7632 // Rebuild the function type "R" without any type qualifiers (in 7633 // case any of the errors above fired) and with "void" as the 7634 // return type, since constructors don't have return types. 7635 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7636 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7637 return R; 7638 7639 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7640 EPI.TypeQuals = 0; 7641 EPI.RefQualifier = RQ_None; 7642 7643 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7644 } 7645 7646 /// CheckConstructor - Checks a fully-formed constructor for 7647 /// well-formedness, issuing any diagnostics required. Returns true if 7648 /// the constructor declarator is invalid. 7649 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7650 CXXRecordDecl *ClassDecl 7651 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7652 if (!ClassDecl) 7653 return Constructor->setInvalidDecl(); 7654 7655 // C++ [class.copy]p3: 7656 // A declaration of a constructor for a class X is ill-formed if 7657 // its first parameter is of type (optionally cv-qualified) X and 7658 // either there are no other parameters or else all other 7659 // parameters have default arguments. 7660 if (!Constructor->isInvalidDecl() && 7661 ((Constructor->getNumParams() == 1) || 7662 (Constructor->getNumParams() > 1 && 7663 Constructor->getParamDecl(1)->hasDefaultArg())) && 7664 Constructor->getTemplateSpecializationKind() 7665 != TSK_ImplicitInstantiation) { 7666 QualType ParamType = Constructor->getParamDecl(0)->getType(); 7667 QualType ClassTy = Context.getTagDeclType(ClassDecl); 7668 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 7669 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 7670 const char *ConstRef 7671 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 7672 : " const &"; 7673 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 7674 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 7675 7676 // FIXME: Rather that making the constructor invalid, we should endeavor 7677 // to fix the type. 7678 Constructor->setInvalidDecl(); 7679 } 7680 } 7681 } 7682 7683 /// CheckDestructor - Checks a fully-formed destructor definition for 7684 /// well-formedness, issuing any diagnostics required. Returns true 7685 /// on error. 7686 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 7687 CXXRecordDecl *RD = Destructor->getParent(); 7688 7689 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 7690 SourceLocation Loc; 7691 7692 if (!Destructor->isImplicit()) 7693 Loc = Destructor->getLocation(); 7694 else 7695 Loc = RD->getLocation(); 7696 7697 // If we have a virtual destructor, look up the deallocation function 7698 if (FunctionDecl *OperatorDelete = 7699 FindDeallocationFunctionForDestructor(Loc, RD)) { 7700 MarkFunctionReferenced(Loc, OperatorDelete); 7701 Destructor->setOperatorDelete(OperatorDelete); 7702 } 7703 } 7704 7705 return false; 7706 } 7707 7708 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 7709 /// the well-formednes of the destructor declarator @p D with type @p 7710 /// R. If there are any errors in the declarator, this routine will 7711 /// emit diagnostics and set the declarator to invalid. Even if this happens, 7712 /// will be updated to reflect a well-formed type for the destructor and 7713 /// returned. 7714 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 7715 StorageClass& SC) { 7716 // C++ [class.dtor]p1: 7717 // [...] A typedef-name that names a class is a class-name 7718 // (7.1.3); however, a typedef-name that names a class shall not 7719 // be used as the identifier in the declarator for a destructor 7720 // declaration. 7721 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 7722 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 7723 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7724 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 7725 else if (const TemplateSpecializationType *TST = 7726 DeclaratorType->getAs<TemplateSpecializationType>()) 7727 if (TST->isTypeAlias()) 7728 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7729 << DeclaratorType << 1; 7730 7731 // C++ [class.dtor]p2: 7732 // A destructor is used to destroy objects of its class type. A 7733 // destructor takes no parameters, and no return type can be 7734 // specified for it (not even void). The address of a destructor 7735 // shall not be taken. A destructor shall not be static. A 7736 // destructor can be invoked for a const, volatile or const 7737 // volatile object. A destructor shall not be declared const, 7738 // volatile or const volatile (9.3.2). 7739 if (SC == SC_Static) { 7740 if (!D.isInvalidType()) 7741 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 7742 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7743 << SourceRange(D.getIdentifierLoc()) 7744 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7745 7746 SC = SC_None; 7747 } 7748 if (!D.isInvalidType()) { 7749 // Destructors don't have return types, but the parser will 7750 // happily parse something like: 7751 // 7752 // class X { 7753 // float ~X(); 7754 // }; 7755 // 7756 // The return type will be eliminated later. 7757 if (D.getDeclSpec().hasTypeSpecifier()) 7758 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 7759 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7760 << SourceRange(D.getIdentifierLoc()); 7761 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7762 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 7763 SourceLocation(), 7764 D.getDeclSpec().getConstSpecLoc(), 7765 D.getDeclSpec().getVolatileSpecLoc(), 7766 D.getDeclSpec().getRestrictSpecLoc(), 7767 D.getDeclSpec().getAtomicSpecLoc()); 7768 D.setInvalidType(); 7769 } 7770 } 7771 7772 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7773 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 7774 if (FTI.TypeQuals & Qualifiers::Const) 7775 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7776 << "const" << SourceRange(D.getIdentifierLoc()); 7777 if (FTI.TypeQuals & Qualifiers::Volatile) 7778 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7779 << "volatile" << SourceRange(D.getIdentifierLoc()); 7780 if (FTI.TypeQuals & Qualifiers::Restrict) 7781 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7782 << "restrict" << SourceRange(D.getIdentifierLoc()); 7783 D.setInvalidType(); 7784 } 7785 7786 // C++0x [class.dtor]p2: 7787 // A destructor shall not be declared with a ref-qualifier. 7788 if (FTI.hasRefQualifier()) { 7789 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 7790 << FTI.RefQualifierIsLValueRef 7791 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7792 D.setInvalidType(); 7793 } 7794 7795 // Make sure we don't have any parameters. 7796 if (FTIHasNonVoidParameters(FTI)) { 7797 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 7798 7799 // Delete the parameters. 7800 FTI.freeParams(); 7801 D.setInvalidType(); 7802 } 7803 7804 // Make sure the destructor isn't variadic. 7805 if (FTI.isVariadic) { 7806 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 7807 D.setInvalidType(); 7808 } 7809 7810 // Rebuild the function type "R" without any type qualifiers or 7811 // parameters (in case any of the errors above fired) and with 7812 // "void" as the return type, since destructors don't have return 7813 // types. 7814 if (!D.isInvalidType()) 7815 return R; 7816 7817 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7818 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7819 EPI.Variadic = false; 7820 EPI.TypeQuals = 0; 7821 EPI.RefQualifier = RQ_None; 7822 return Context.getFunctionType(Context.VoidTy, None, EPI); 7823 } 7824 7825 static void extendLeft(SourceRange &R, SourceRange Before) { 7826 if (Before.isInvalid()) 7827 return; 7828 R.setBegin(Before.getBegin()); 7829 if (R.getEnd().isInvalid()) 7830 R.setEnd(Before.getEnd()); 7831 } 7832 7833 static void extendRight(SourceRange &R, SourceRange After) { 7834 if (After.isInvalid()) 7835 return; 7836 if (R.getBegin().isInvalid()) 7837 R.setBegin(After.getBegin()); 7838 R.setEnd(After.getEnd()); 7839 } 7840 7841 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 7842 /// well-formednes of the conversion function declarator @p D with 7843 /// type @p R. If there are any errors in the declarator, this routine 7844 /// will emit diagnostics and return true. Otherwise, it will return 7845 /// false. Either way, the type @p R will be updated to reflect a 7846 /// well-formed type for the conversion operator. 7847 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 7848 StorageClass& SC) { 7849 // C++ [class.conv.fct]p1: 7850 // Neither parameter types nor return type can be specified. The 7851 // type of a conversion function (8.3.5) is "function taking no 7852 // parameter returning conversion-type-id." 7853 if (SC == SC_Static) { 7854 if (!D.isInvalidType()) 7855 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 7856 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7857 << D.getName().getSourceRange(); 7858 D.setInvalidType(); 7859 SC = SC_None; 7860 } 7861 7862 TypeSourceInfo *ConvTSI = nullptr; 7863 QualType ConvType = 7864 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 7865 7866 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 7867 // Conversion functions don't have return types, but the parser will 7868 // happily parse something like: 7869 // 7870 // class X { 7871 // float operator bool(); 7872 // }; 7873 // 7874 // The return type will be changed later anyway. 7875 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 7876 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7877 << SourceRange(D.getIdentifierLoc()); 7878 D.setInvalidType(); 7879 } 7880 7881 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7882 7883 // Make sure we don't have any parameters. 7884 if (Proto->getNumParams() > 0) { 7885 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 7886 7887 // Delete the parameters. 7888 D.getFunctionTypeInfo().freeParams(); 7889 D.setInvalidType(); 7890 } else if (Proto->isVariadic()) { 7891 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 7892 D.setInvalidType(); 7893 } 7894 7895 // Diagnose "&operator bool()" and other such nonsense. This 7896 // is actually a gcc extension which we don't support. 7897 if (Proto->getReturnType() != ConvType) { 7898 bool NeedsTypedef = false; 7899 SourceRange Before, After; 7900 7901 // Walk the chunks and extract information on them for our diagnostic. 7902 bool PastFunctionChunk = false; 7903 for (auto &Chunk : D.type_objects()) { 7904 switch (Chunk.Kind) { 7905 case DeclaratorChunk::Function: 7906 if (!PastFunctionChunk) { 7907 if (Chunk.Fun.HasTrailingReturnType) { 7908 TypeSourceInfo *TRT = nullptr; 7909 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 7910 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 7911 } 7912 PastFunctionChunk = true; 7913 break; 7914 } 7915 // Fall through. 7916 case DeclaratorChunk::Array: 7917 NeedsTypedef = true; 7918 extendRight(After, Chunk.getSourceRange()); 7919 break; 7920 7921 case DeclaratorChunk::Pointer: 7922 case DeclaratorChunk::BlockPointer: 7923 case DeclaratorChunk::Reference: 7924 case DeclaratorChunk::MemberPointer: 7925 case DeclaratorChunk::Pipe: 7926 extendLeft(Before, Chunk.getSourceRange()); 7927 break; 7928 7929 case DeclaratorChunk::Paren: 7930 extendLeft(Before, Chunk.Loc); 7931 extendRight(After, Chunk.EndLoc); 7932 break; 7933 } 7934 } 7935 7936 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 7937 After.isValid() ? After.getBegin() : 7938 D.getIdentifierLoc(); 7939 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 7940 DB << Before << After; 7941 7942 if (!NeedsTypedef) { 7943 DB << /*don't need a typedef*/0; 7944 7945 // If we can provide a correct fix-it hint, do so. 7946 if (After.isInvalid() && ConvTSI) { 7947 SourceLocation InsertLoc = 7948 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 7949 DB << FixItHint::CreateInsertion(InsertLoc, " ") 7950 << FixItHint::CreateInsertionFromRange( 7951 InsertLoc, CharSourceRange::getTokenRange(Before)) 7952 << FixItHint::CreateRemoval(Before); 7953 } 7954 } else if (!Proto->getReturnType()->isDependentType()) { 7955 DB << /*typedef*/1 << Proto->getReturnType(); 7956 } else if (getLangOpts().CPlusPlus11) { 7957 DB << /*alias template*/2 << Proto->getReturnType(); 7958 } else { 7959 DB << /*might not be fixable*/3; 7960 } 7961 7962 // Recover by incorporating the other type chunks into the result type. 7963 // Note, this does *not* change the name of the function. This is compatible 7964 // with the GCC extension: 7965 // struct S { &operator int(); } s; 7966 // int &r = s.operator int(); // ok in GCC 7967 // S::operator int&() {} // error in GCC, function name is 'operator int'. 7968 ConvType = Proto->getReturnType(); 7969 } 7970 7971 // C++ [class.conv.fct]p4: 7972 // The conversion-type-id shall not represent a function type nor 7973 // an array type. 7974 if (ConvType->isArrayType()) { 7975 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7976 ConvType = Context.getPointerType(ConvType); 7977 D.setInvalidType(); 7978 } else if (ConvType->isFunctionType()) { 7979 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7980 ConvType = Context.getPointerType(ConvType); 7981 D.setInvalidType(); 7982 } 7983 7984 // Rebuild the function type "R" without any parameters (in case any 7985 // of the errors above fired) and with the conversion type as the 7986 // return type. 7987 if (D.isInvalidType()) 7988 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7989 7990 // C++0x explicit conversion operators. 7991 if (D.getDeclSpec().isExplicitSpecified()) 7992 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7993 getLangOpts().CPlusPlus11 ? 7994 diag::warn_cxx98_compat_explicit_conversion_functions : 7995 diag::ext_explicit_conversion_functions) 7996 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7997 } 7998 7999 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8000 /// the declaration of the given C++ conversion function. This routine 8001 /// is responsible for recording the conversion function in the C++ 8002 /// class, if possible. 8003 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8004 assert(Conversion && "Expected to receive a conversion function declaration"); 8005 8006 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8007 8008 // Make sure we aren't redeclaring the conversion function. 8009 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8010 8011 // C++ [class.conv.fct]p1: 8012 // [...] A conversion function is never used to convert a 8013 // (possibly cv-qualified) object to the (possibly cv-qualified) 8014 // same object type (or a reference to it), to a (possibly 8015 // cv-qualified) base class of that type (or a reference to it), 8016 // or to (possibly cv-qualified) void. 8017 // FIXME: Suppress this warning if the conversion function ends up being a 8018 // virtual function that overrides a virtual function in a base class. 8019 QualType ClassType 8020 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8021 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8022 ConvType = ConvTypeRef->getPointeeType(); 8023 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8024 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8025 /* Suppress diagnostics for instantiations. */; 8026 else if (ConvType->isRecordType()) { 8027 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8028 if (ConvType == ClassType) 8029 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8030 << ClassType; 8031 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8032 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8033 << ClassType << ConvType; 8034 } else if (ConvType->isVoidType()) { 8035 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8036 << ClassType << ConvType; 8037 } 8038 8039 if (FunctionTemplateDecl *ConversionTemplate 8040 = Conversion->getDescribedFunctionTemplate()) 8041 return ConversionTemplate; 8042 8043 return Conversion; 8044 } 8045 8046 //===----------------------------------------------------------------------===// 8047 // Namespace Handling 8048 //===----------------------------------------------------------------------===// 8049 8050 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8051 /// reopened. 8052 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8053 SourceLocation Loc, 8054 IdentifierInfo *II, bool *IsInline, 8055 NamespaceDecl *PrevNS) { 8056 assert(*IsInline != PrevNS->isInline()); 8057 8058 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8059 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8060 // inline namespaces, with the intention of bringing names into namespace std. 8061 // 8062 // We support this just well enough to get that case working; this is not 8063 // sufficient to support reopening namespaces as inline in general. 8064 if (*IsInline && II && II->getName().startswith("__atomic") && 8065 S.getSourceManager().isInSystemHeader(Loc)) { 8066 // Mark all prior declarations of the namespace as inline. 8067 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8068 NS = NS->getPreviousDecl()) 8069 NS->setInline(*IsInline); 8070 // Patch up the lookup table for the containing namespace. This isn't really 8071 // correct, but it's good enough for this particular case. 8072 for (auto *I : PrevNS->decls()) 8073 if (auto *ND = dyn_cast<NamedDecl>(I)) 8074 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8075 return; 8076 } 8077 8078 if (PrevNS->isInline()) 8079 // The user probably just forgot the 'inline', so suggest that it 8080 // be added back. 8081 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8082 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8083 else 8084 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8085 8086 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8087 *IsInline = PrevNS->isInline(); 8088 } 8089 8090 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8091 /// definition. 8092 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8093 SourceLocation InlineLoc, 8094 SourceLocation NamespaceLoc, 8095 SourceLocation IdentLoc, 8096 IdentifierInfo *II, 8097 SourceLocation LBrace, 8098 AttributeList *AttrList, 8099 UsingDirectiveDecl *&UD) { 8100 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8101 // For anonymous namespace, take the location of the left brace. 8102 SourceLocation Loc = II ? IdentLoc : LBrace; 8103 bool IsInline = InlineLoc.isValid(); 8104 bool IsInvalid = false; 8105 bool IsStd = false; 8106 bool AddToKnown = false; 8107 Scope *DeclRegionScope = NamespcScope->getParent(); 8108 8109 NamespaceDecl *PrevNS = nullptr; 8110 if (II) { 8111 // C++ [namespace.def]p2: 8112 // The identifier in an original-namespace-definition shall not 8113 // have been previously defined in the declarative region in 8114 // which the original-namespace-definition appears. The 8115 // identifier in an original-namespace-definition is the name of 8116 // the namespace. Subsequently in that declarative region, it is 8117 // treated as an original-namespace-name. 8118 // 8119 // Since namespace names are unique in their scope, and we don't 8120 // look through using directives, just look for any ordinary names 8121 // as if by qualified name lookup. 8122 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration); 8123 LookupQualifiedName(R, CurContext->getRedeclContext()); 8124 NamedDecl *PrevDecl = 8125 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8126 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8127 8128 if (PrevNS) { 8129 // This is an extended namespace definition. 8130 if (IsInline != PrevNS->isInline()) 8131 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8132 &IsInline, PrevNS); 8133 } else if (PrevDecl) { 8134 // This is an invalid name redefinition. 8135 Diag(Loc, diag::err_redefinition_different_kind) 8136 << II; 8137 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8138 IsInvalid = true; 8139 // Continue on to push Namespc as current DeclContext and return it. 8140 } else if (II->isStr("std") && 8141 CurContext->getRedeclContext()->isTranslationUnit()) { 8142 // This is the first "real" definition of the namespace "std", so update 8143 // our cache of the "std" namespace to point at this definition. 8144 PrevNS = getStdNamespace(); 8145 IsStd = true; 8146 AddToKnown = !IsInline; 8147 } else { 8148 // We've seen this namespace for the first time. 8149 AddToKnown = !IsInline; 8150 } 8151 } else { 8152 // Anonymous namespaces. 8153 8154 // Determine whether the parent already has an anonymous namespace. 8155 DeclContext *Parent = CurContext->getRedeclContext(); 8156 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8157 PrevNS = TU->getAnonymousNamespace(); 8158 } else { 8159 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8160 PrevNS = ND->getAnonymousNamespace(); 8161 } 8162 8163 if (PrevNS && IsInline != PrevNS->isInline()) 8164 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8165 &IsInline, PrevNS); 8166 } 8167 8168 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8169 StartLoc, Loc, II, PrevNS); 8170 if (IsInvalid) 8171 Namespc->setInvalidDecl(); 8172 8173 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8174 8175 // FIXME: Should we be merging attributes? 8176 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8177 PushNamespaceVisibilityAttr(Attr, Loc); 8178 8179 if (IsStd) 8180 StdNamespace = Namespc; 8181 if (AddToKnown) 8182 KnownNamespaces[Namespc] = false; 8183 8184 if (II) { 8185 PushOnScopeChains(Namespc, DeclRegionScope); 8186 } else { 8187 // Link the anonymous namespace into its parent. 8188 DeclContext *Parent = CurContext->getRedeclContext(); 8189 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8190 TU->setAnonymousNamespace(Namespc); 8191 } else { 8192 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8193 } 8194 8195 CurContext->addDecl(Namespc); 8196 8197 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8198 // behaves as if it were replaced by 8199 // namespace unique { /* empty body */ } 8200 // using namespace unique; 8201 // namespace unique { namespace-body } 8202 // where all occurrences of 'unique' in a translation unit are 8203 // replaced by the same identifier and this identifier differs 8204 // from all other identifiers in the entire program. 8205 8206 // We just create the namespace with an empty name and then add an 8207 // implicit using declaration, just like the standard suggests. 8208 // 8209 // CodeGen enforces the "universally unique" aspect by giving all 8210 // declarations semantically contained within an anonymous 8211 // namespace internal linkage. 8212 8213 if (!PrevNS) { 8214 UD = UsingDirectiveDecl::Create(Context, Parent, 8215 /* 'using' */ LBrace, 8216 /* 'namespace' */ SourceLocation(), 8217 /* qualifier */ NestedNameSpecifierLoc(), 8218 /* identifier */ SourceLocation(), 8219 Namespc, 8220 /* Ancestor */ Parent); 8221 UD->setImplicit(); 8222 Parent->addDecl(UD); 8223 } 8224 } 8225 8226 ActOnDocumentableDecl(Namespc); 8227 8228 // Although we could have an invalid decl (i.e. the namespace name is a 8229 // redefinition), push it as current DeclContext and try to continue parsing. 8230 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8231 // for the namespace has the declarations that showed up in that particular 8232 // namespace definition. 8233 PushDeclContext(NamespcScope, Namespc); 8234 return Namespc; 8235 } 8236 8237 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8238 /// is a namespace alias, returns the namespace it points to. 8239 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8240 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8241 return AD->getNamespace(); 8242 return dyn_cast_or_null<NamespaceDecl>(D); 8243 } 8244 8245 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8246 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8247 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8248 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8249 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8250 Namespc->setRBraceLoc(RBrace); 8251 PopDeclContext(); 8252 if (Namespc->hasAttr<VisibilityAttr>()) 8253 PopPragmaVisibility(true, RBrace); 8254 } 8255 8256 CXXRecordDecl *Sema::getStdBadAlloc() const { 8257 return cast_or_null<CXXRecordDecl>( 8258 StdBadAlloc.get(Context.getExternalSource())); 8259 } 8260 8261 EnumDecl *Sema::getStdAlignValT() const { 8262 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8263 } 8264 8265 NamespaceDecl *Sema::getStdNamespace() const { 8266 return cast_or_null<NamespaceDecl>( 8267 StdNamespace.get(Context.getExternalSource())); 8268 } 8269 8270 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8271 if (!StdExperimentalNamespaceCache) { 8272 if (auto Std = getStdNamespace()) { 8273 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8274 SourceLocation(), LookupNamespaceName); 8275 if (!LookupQualifiedName(Result, Std) || 8276 !(StdExperimentalNamespaceCache = 8277 Result.getAsSingle<NamespaceDecl>())) 8278 Result.suppressDiagnostics(); 8279 } 8280 } 8281 return StdExperimentalNamespaceCache; 8282 } 8283 8284 /// \brief Retrieve the special "std" namespace, which may require us to 8285 /// implicitly define the namespace. 8286 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8287 if (!StdNamespace) { 8288 // The "std" namespace has not yet been defined, so build one implicitly. 8289 StdNamespace = NamespaceDecl::Create(Context, 8290 Context.getTranslationUnitDecl(), 8291 /*Inline=*/false, 8292 SourceLocation(), SourceLocation(), 8293 &PP.getIdentifierTable().get("std"), 8294 /*PrevDecl=*/nullptr); 8295 getStdNamespace()->setImplicit(true); 8296 } 8297 8298 return getStdNamespace(); 8299 } 8300 8301 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8302 assert(getLangOpts().CPlusPlus && 8303 "Looking for std::initializer_list outside of C++."); 8304 8305 // We're looking for implicit instantiations of 8306 // template <typename E> class std::initializer_list. 8307 8308 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8309 return false; 8310 8311 ClassTemplateDecl *Template = nullptr; 8312 const TemplateArgument *Arguments = nullptr; 8313 8314 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8315 8316 ClassTemplateSpecializationDecl *Specialization = 8317 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8318 if (!Specialization) 8319 return false; 8320 8321 Template = Specialization->getSpecializedTemplate(); 8322 Arguments = Specialization->getTemplateArgs().data(); 8323 } else if (const TemplateSpecializationType *TST = 8324 Ty->getAs<TemplateSpecializationType>()) { 8325 Template = dyn_cast_or_null<ClassTemplateDecl>( 8326 TST->getTemplateName().getAsTemplateDecl()); 8327 Arguments = TST->getArgs(); 8328 } 8329 if (!Template) 8330 return false; 8331 8332 if (!StdInitializerList) { 8333 // Haven't recognized std::initializer_list yet, maybe this is it. 8334 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8335 if (TemplateClass->getIdentifier() != 8336 &PP.getIdentifierTable().get("initializer_list") || 8337 !getStdNamespace()->InEnclosingNamespaceSetOf( 8338 TemplateClass->getDeclContext())) 8339 return false; 8340 // This is a template called std::initializer_list, but is it the right 8341 // template? 8342 TemplateParameterList *Params = Template->getTemplateParameters(); 8343 if (Params->getMinRequiredArguments() != 1) 8344 return false; 8345 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8346 return false; 8347 8348 // It's the right template. 8349 StdInitializerList = Template; 8350 } 8351 8352 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8353 return false; 8354 8355 // This is an instance of std::initializer_list. Find the argument type. 8356 if (Element) 8357 *Element = Arguments[0].getAsType(); 8358 return true; 8359 } 8360 8361 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8362 NamespaceDecl *Std = S.getStdNamespace(); 8363 if (!Std) { 8364 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8365 return nullptr; 8366 } 8367 8368 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8369 Loc, Sema::LookupOrdinaryName); 8370 if (!S.LookupQualifiedName(Result, Std)) { 8371 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8372 return nullptr; 8373 } 8374 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8375 if (!Template) { 8376 Result.suppressDiagnostics(); 8377 // We found something weird. Complain about the first thing we found. 8378 NamedDecl *Found = *Result.begin(); 8379 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8380 return nullptr; 8381 } 8382 8383 // We found some template called std::initializer_list. Now verify that it's 8384 // correct. 8385 TemplateParameterList *Params = Template->getTemplateParameters(); 8386 if (Params->getMinRequiredArguments() != 1 || 8387 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8388 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8389 return nullptr; 8390 } 8391 8392 return Template; 8393 } 8394 8395 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8396 if (!StdInitializerList) { 8397 StdInitializerList = LookupStdInitializerList(*this, Loc); 8398 if (!StdInitializerList) 8399 return QualType(); 8400 } 8401 8402 TemplateArgumentListInfo Args(Loc, Loc); 8403 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8404 Context.getTrivialTypeSourceInfo(Element, 8405 Loc))); 8406 return Context.getCanonicalType( 8407 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8408 } 8409 8410 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 8411 // C++ [dcl.init.list]p2: 8412 // A constructor is an initializer-list constructor if its first parameter 8413 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8414 // std::initializer_list<E> for some type E, and either there are no other 8415 // parameters or else all other parameters have default arguments. 8416 if (Ctor->getNumParams() < 1 || 8417 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8418 return false; 8419 8420 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8421 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8422 ArgType = RT->getPointeeType().getUnqualifiedType(); 8423 8424 return isStdInitializerList(ArgType, nullptr); 8425 } 8426 8427 /// \brief Determine whether a using statement is in a context where it will be 8428 /// apply in all contexts. 8429 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8430 switch (CurContext->getDeclKind()) { 8431 case Decl::TranslationUnit: 8432 return true; 8433 case Decl::LinkageSpec: 8434 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8435 default: 8436 return false; 8437 } 8438 } 8439 8440 namespace { 8441 8442 // Callback to only accept typo corrections that are namespaces. 8443 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8444 public: 8445 bool ValidateCandidate(const TypoCorrection &candidate) override { 8446 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8447 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8448 return false; 8449 } 8450 }; 8451 8452 } 8453 8454 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8455 CXXScopeSpec &SS, 8456 SourceLocation IdentLoc, 8457 IdentifierInfo *Ident) { 8458 R.clear(); 8459 if (TypoCorrection Corrected = 8460 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8461 llvm::make_unique<NamespaceValidatorCCC>(), 8462 Sema::CTK_ErrorRecovery)) { 8463 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8464 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8465 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8466 Ident->getName().equals(CorrectedStr); 8467 S.diagnoseTypo(Corrected, 8468 S.PDiag(diag::err_using_directive_member_suggest) 8469 << Ident << DC << DroppedSpecifier << SS.getRange(), 8470 S.PDiag(diag::note_namespace_defined_here)); 8471 } else { 8472 S.diagnoseTypo(Corrected, 8473 S.PDiag(diag::err_using_directive_suggest) << Ident, 8474 S.PDiag(diag::note_namespace_defined_here)); 8475 } 8476 R.addDecl(Corrected.getFoundDecl()); 8477 return true; 8478 } 8479 return false; 8480 } 8481 8482 Decl *Sema::ActOnUsingDirective(Scope *S, 8483 SourceLocation UsingLoc, 8484 SourceLocation NamespcLoc, 8485 CXXScopeSpec &SS, 8486 SourceLocation IdentLoc, 8487 IdentifierInfo *NamespcName, 8488 AttributeList *AttrList) { 8489 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8490 assert(NamespcName && "Invalid NamespcName."); 8491 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 8492 8493 // This can only happen along a recovery path. 8494 while (S->isTemplateParamScope()) 8495 S = S->getParent(); 8496 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8497 8498 UsingDirectiveDecl *UDir = nullptr; 8499 NestedNameSpecifier *Qualifier = nullptr; 8500 if (SS.isSet()) 8501 Qualifier = SS.getScopeRep(); 8502 8503 // Lookup namespace name. 8504 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 8505 LookupParsedName(R, S, &SS); 8506 if (R.isAmbiguous()) 8507 return nullptr; 8508 8509 if (R.empty()) { 8510 R.clear(); 8511 // Allow "using namespace std;" or "using namespace ::std;" even if 8512 // "std" hasn't been defined yet, for GCC compatibility. 8513 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 8514 NamespcName->isStr("std")) { 8515 Diag(IdentLoc, diag::ext_using_undefined_std); 8516 R.addDecl(getOrCreateStdNamespace()); 8517 R.resolveKind(); 8518 } 8519 // Otherwise, attempt typo correction. 8520 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 8521 } 8522 8523 if (!R.empty()) { 8524 NamedDecl *Named = R.getRepresentativeDecl(); 8525 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 8526 assert(NS && "expected namespace decl"); 8527 8528 // The use of a nested name specifier may trigger deprecation warnings. 8529 DiagnoseUseOfDecl(Named, IdentLoc); 8530 8531 // C++ [namespace.udir]p1: 8532 // A using-directive specifies that the names in the nominated 8533 // namespace can be used in the scope in which the 8534 // using-directive appears after the using-directive. During 8535 // unqualified name lookup (3.4.1), the names appear as if they 8536 // were declared in the nearest enclosing namespace which 8537 // contains both the using-directive and the nominated 8538 // namespace. [Note: in this context, "contains" means "contains 8539 // directly or indirectly". ] 8540 8541 // Find enclosing context containing both using-directive and 8542 // nominated namespace. 8543 DeclContext *CommonAncestor = cast<DeclContext>(NS); 8544 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 8545 CommonAncestor = CommonAncestor->getParent(); 8546 8547 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 8548 SS.getWithLocInContext(Context), 8549 IdentLoc, Named, CommonAncestor); 8550 8551 if (IsUsingDirectiveInToplevelContext(CurContext) && 8552 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 8553 Diag(IdentLoc, diag::warn_using_directive_in_header); 8554 } 8555 8556 PushUsingDirective(S, UDir); 8557 } else { 8558 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8559 } 8560 8561 if (UDir) 8562 ProcessDeclAttributeList(S, UDir, AttrList); 8563 8564 return UDir; 8565 } 8566 8567 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 8568 // If the scope has an associated entity and the using directive is at 8569 // namespace or translation unit scope, add the UsingDirectiveDecl into 8570 // its lookup structure so qualified name lookup can find it. 8571 DeclContext *Ctx = S->getEntity(); 8572 if (Ctx && !Ctx->isFunctionOrMethod()) 8573 Ctx->addDecl(UDir); 8574 else 8575 // Otherwise, it is at block scope. The using-directives will affect lookup 8576 // only to the end of the scope. 8577 S->PushUsingDirective(UDir); 8578 } 8579 8580 8581 Decl *Sema::ActOnUsingDeclaration(Scope *S, 8582 AccessSpecifier AS, 8583 bool HasUsingKeyword, 8584 SourceLocation UsingLoc, 8585 CXXScopeSpec &SS, 8586 UnqualifiedId &Name, 8587 AttributeList *AttrList, 8588 bool HasTypenameKeyword, 8589 SourceLocation TypenameLoc) { 8590 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8591 8592 switch (Name.getKind()) { 8593 case UnqualifiedId::IK_ImplicitSelfParam: 8594 case UnqualifiedId::IK_Identifier: 8595 case UnqualifiedId::IK_OperatorFunctionId: 8596 case UnqualifiedId::IK_LiteralOperatorId: 8597 case UnqualifiedId::IK_ConversionFunctionId: 8598 break; 8599 8600 case UnqualifiedId::IK_ConstructorName: 8601 case UnqualifiedId::IK_ConstructorTemplateId: 8602 // C++11 inheriting constructors. 8603 Diag(Name.getLocStart(), 8604 getLangOpts().CPlusPlus11 ? 8605 diag::warn_cxx98_compat_using_decl_constructor : 8606 diag::err_using_decl_constructor) 8607 << SS.getRange(); 8608 8609 if (getLangOpts().CPlusPlus11) break; 8610 8611 return nullptr; 8612 8613 case UnqualifiedId::IK_DestructorName: 8614 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 8615 << SS.getRange(); 8616 return nullptr; 8617 8618 case UnqualifiedId::IK_TemplateId: 8619 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 8620 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 8621 return nullptr; 8622 } 8623 8624 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 8625 DeclarationName TargetName = TargetNameInfo.getName(); 8626 if (!TargetName) 8627 return nullptr; 8628 8629 // Warn about access declarations. 8630 if (!HasUsingKeyword) { 8631 Diag(Name.getLocStart(), 8632 getLangOpts().CPlusPlus11 ? diag::err_access_decl 8633 : diag::warn_access_decl_deprecated) 8634 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 8635 } 8636 8637 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 8638 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 8639 return nullptr; 8640 8641 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 8642 TargetNameInfo, AttrList, 8643 /* IsInstantiation */ false, 8644 HasTypenameKeyword, TypenameLoc); 8645 if (UD) 8646 PushOnScopeChains(UD, S, /*AddToContext*/ false); 8647 8648 return UD; 8649 } 8650 8651 /// \brief Determine whether a using declaration considers the given 8652 /// declarations as "equivalent", e.g., if they are redeclarations of 8653 /// the same entity or are both typedefs of the same type. 8654 static bool 8655 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 8656 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 8657 return true; 8658 8659 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 8660 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 8661 return Context.hasSameType(TD1->getUnderlyingType(), 8662 TD2->getUnderlyingType()); 8663 8664 return false; 8665 } 8666 8667 8668 /// Determines whether to create a using shadow decl for a particular 8669 /// decl, given the set of decls existing prior to this using lookup. 8670 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 8671 const LookupResult &Previous, 8672 UsingShadowDecl *&PrevShadow) { 8673 // Diagnose finding a decl which is not from a base class of the 8674 // current class. We do this now because there are cases where this 8675 // function will silently decide not to build a shadow decl, which 8676 // will pre-empt further diagnostics. 8677 // 8678 // We don't need to do this in C++11 because we do the check once on 8679 // the qualifier. 8680 // 8681 // FIXME: diagnose the following if we care enough: 8682 // struct A { int foo; }; 8683 // struct B : A { using A::foo; }; 8684 // template <class T> struct C : A {}; 8685 // template <class T> struct D : C<T> { using B::foo; } // <--- 8686 // This is invalid (during instantiation) in C++03 because B::foo 8687 // resolves to the using decl in B, which is not a base class of D<T>. 8688 // We can't diagnose it immediately because C<T> is an unknown 8689 // specialization. The UsingShadowDecl in D<T> then points directly 8690 // to A::foo, which will look well-formed when we instantiate. 8691 // The right solution is to not collapse the shadow-decl chain. 8692 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 8693 DeclContext *OrigDC = Orig->getDeclContext(); 8694 8695 // Handle enums and anonymous structs. 8696 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 8697 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 8698 while (OrigRec->isAnonymousStructOrUnion()) 8699 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 8700 8701 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 8702 if (OrigDC == CurContext) { 8703 Diag(Using->getLocation(), 8704 diag::err_using_decl_nested_name_specifier_is_current_class) 8705 << Using->getQualifierLoc().getSourceRange(); 8706 Diag(Orig->getLocation(), diag::note_using_decl_target); 8707 return true; 8708 } 8709 8710 Diag(Using->getQualifierLoc().getBeginLoc(), 8711 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8712 << Using->getQualifier() 8713 << cast<CXXRecordDecl>(CurContext) 8714 << Using->getQualifierLoc().getSourceRange(); 8715 Diag(Orig->getLocation(), diag::note_using_decl_target); 8716 return true; 8717 } 8718 } 8719 8720 if (Previous.empty()) return false; 8721 8722 NamedDecl *Target = Orig; 8723 if (isa<UsingShadowDecl>(Target)) 8724 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 8725 8726 // If the target happens to be one of the previous declarations, we 8727 // don't have a conflict. 8728 // 8729 // FIXME: but we might be increasing its access, in which case we 8730 // should redeclare it. 8731 NamedDecl *NonTag = nullptr, *Tag = nullptr; 8732 bool FoundEquivalentDecl = false; 8733 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8734 I != E; ++I) { 8735 NamedDecl *D = (*I)->getUnderlyingDecl(); 8736 // We can have UsingDecls in our Previous results because we use the same 8737 // LookupResult for checking whether the UsingDecl itself is a valid 8738 // redeclaration. 8739 if (isa<UsingDecl>(D)) 8740 continue; 8741 8742 if (IsEquivalentForUsingDecl(Context, D, Target)) { 8743 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 8744 PrevShadow = Shadow; 8745 FoundEquivalentDecl = true; 8746 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 8747 // We don't conflict with an existing using shadow decl of an equivalent 8748 // declaration, but we're not a redeclaration of it. 8749 FoundEquivalentDecl = true; 8750 } 8751 8752 if (isVisible(D)) 8753 (isa<TagDecl>(D) ? Tag : NonTag) = D; 8754 } 8755 8756 if (FoundEquivalentDecl) 8757 return false; 8758 8759 if (FunctionDecl *FD = Target->getAsFunction()) { 8760 NamedDecl *OldDecl = nullptr; 8761 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 8762 /*IsForUsingDecl*/ true)) { 8763 case Ovl_Overload: 8764 return false; 8765 8766 case Ovl_NonFunction: 8767 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8768 break; 8769 8770 // We found a decl with the exact signature. 8771 case Ovl_Match: 8772 // If we're in a record, we want to hide the target, so we 8773 // return true (without a diagnostic) to tell the caller not to 8774 // build a shadow decl. 8775 if (CurContext->isRecord()) 8776 return true; 8777 8778 // If we're not in a record, this is an error. 8779 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8780 break; 8781 } 8782 8783 Diag(Target->getLocation(), diag::note_using_decl_target); 8784 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 8785 return true; 8786 } 8787 8788 // Target is not a function. 8789 8790 if (isa<TagDecl>(Target)) { 8791 // No conflict between a tag and a non-tag. 8792 if (!Tag) return false; 8793 8794 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8795 Diag(Target->getLocation(), diag::note_using_decl_target); 8796 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 8797 return true; 8798 } 8799 8800 // No conflict between a tag and a non-tag. 8801 if (!NonTag) return false; 8802 8803 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8804 Diag(Target->getLocation(), diag::note_using_decl_target); 8805 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 8806 return true; 8807 } 8808 8809 /// Determine whether a direct base class is a virtual base class. 8810 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 8811 if (!Derived->getNumVBases()) 8812 return false; 8813 for (auto &B : Derived->bases()) 8814 if (B.getType()->getAsCXXRecordDecl() == Base) 8815 return B.isVirtual(); 8816 llvm_unreachable("not a direct base class"); 8817 } 8818 8819 /// Builds a shadow declaration corresponding to a 'using' declaration. 8820 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 8821 UsingDecl *UD, 8822 NamedDecl *Orig, 8823 UsingShadowDecl *PrevDecl) { 8824 // If we resolved to another shadow declaration, just coalesce them. 8825 NamedDecl *Target = Orig; 8826 if (isa<UsingShadowDecl>(Target)) { 8827 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 8828 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 8829 } 8830 8831 NamedDecl *NonTemplateTarget = Target; 8832 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 8833 NonTemplateTarget = TargetTD->getTemplatedDecl(); 8834 8835 UsingShadowDecl *Shadow; 8836 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 8837 bool IsVirtualBase = 8838 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 8839 UD->getQualifier()->getAsRecordDecl()); 8840 Shadow = ConstructorUsingShadowDecl::Create( 8841 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 8842 } else { 8843 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 8844 Target); 8845 } 8846 UD->addShadowDecl(Shadow); 8847 8848 Shadow->setAccess(UD->getAccess()); 8849 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 8850 Shadow->setInvalidDecl(); 8851 8852 Shadow->setPreviousDecl(PrevDecl); 8853 8854 if (S) 8855 PushOnScopeChains(Shadow, S); 8856 else 8857 CurContext->addDecl(Shadow); 8858 8859 8860 return Shadow; 8861 } 8862 8863 /// Hides a using shadow declaration. This is required by the current 8864 /// using-decl implementation when a resolvable using declaration in a 8865 /// class is followed by a declaration which would hide or override 8866 /// one or more of the using decl's targets; for example: 8867 /// 8868 /// struct Base { void foo(int); }; 8869 /// struct Derived : Base { 8870 /// using Base::foo; 8871 /// void foo(int); 8872 /// }; 8873 /// 8874 /// The governing language is C++03 [namespace.udecl]p12: 8875 /// 8876 /// When a using-declaration brings names from a base class into a 8877 /// derived class scope, member functions in the derived class 8878 /// override and/or hide member functions with the same name and 8879 /// parameter types in a base class (rather than conflicting). 8880 /// 8881 /// There are two ways to implement this: 8882 /// (1) optimistically create shadow decls when they're not hidden 8883 /// by existing declarations, or 8884 /// (2) don't create any shadow decls (or at least don't make them 8885 /// visible) until we've fully parsed/instantiated the class. 8886 /// The problem with (1) is that we might have to retroactively remove 8887 /// a shadow decl, which requires several O(n) operations because the 8888 /// decl structures are (very reasonably) not designed for removal. 8889 /// (2) avoids this but is very fiddly and phase-dependent. 8890 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 8891 if (Shadow->getDeclName().getNameKind() == 8892 DeclarationName::CXXConversionFunctionName) 8893 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 8894 8895 // Remove it from the DeclContext... 8896 Shadow->getDeclContext()->removeDecl(Shadow); 8897 8898 // ...and the scope, if applicable... 8899 if (S) { 8900 S->RemoveDecl(Shadow); 8901 IdResolver.RemoveDecl(Shadow); 8902 } 8903 8904 // ...and the using decl. 8905 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 8906 8907 // TODO: complain somehow if Shadow was used. It shouldn't 8908 // be possible for this to happen, because...? 8909 } 8910 8911 /// Find the base specifier for a base class with the given type. 8912 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 8913 QualType DesiredBase, 8914 bool &AnyDependentBases) { 8915 // Check whether the named type is a direct base class. 8916 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 8917 for (auto &Base : Derived->bases()) { 8918 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 8919 if (CanonicalDesiredBase == BaseType) 8920 return &Base; 8921 if (BaseType->isDependentType()) 8922 AnyDependentBases = true; 8923 } 8924 return nullptr; 8925 } 8926 8927 namespace { 8928 class UsingValidatorCCC : public CorrectionCandidateCallback { 8929 public: 8930 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 8931 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 8932 : HasTypenameKeyword(HasTypenameKeyword), 8933 IsInstantiation(IsInstantiation), OldNNS(NNS), 8934 RequireMemberOf(RequireMemberOf) {} 8935 8936 bool ValidateCandidate(const TypoCorrection &Candidate) override { 8937 NamedDecl *ND = Candidate.getCorrectionDecl(); 8938 8939 // Keywords are not valid here. 8940 if (!ND || isa<NamespaceDecl>(ND)) 8941 return false; 8942 8943 // Completely unqualified names are invalid for a 'using' declaration. 8944 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 8945 return false; 8946 8947 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 8948 // reject. 8949 8950 if (RequireMemberOf) { 8951 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8952 if (FoundRecord && FoundRecord->isInjectedClassName()) { 8953 // No-one ever wants a using-declaration to name an injected-class-name 8954 // of a base class, unless they're declaring an inheriting constructor. 8955 ASTContext &Ctx = ND->getASTContext(); 8956 if (!Ctx.getLangOpts().CPlusPlus11) 8957 return false; 8958 QualType FoundType = Ctx.getRecordType(FoundRecord); 8959 8960 // Check that the injected-class-name is named as a member of its own 8961 // type; we don't want to suggest 'using Derived::Base;', since that 8962 // means something else. 8963 NestedNameSpecifier *Specifier = 8964 Candidate.WillReplaceSpecifier() 8965 ? Candidate.getCorrectionSpecifier() 8966 : OldNNS; 8967 if (!Specifier->getAsType() || 8968 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 8969 return false; 8970 8971 // Check that this inheriting constructor declaration actually names a 8972 // direct base class of the current class. 8973 bool AnyDependentBases = false; 8974 if (!findDirectBaseWithType(RequireMemberOf, 8975 Ctx.getRecordType(FoundRecord), 8976 AnyDependentBases) && 8977 !AnyDependentBases) 8978 return false; 8979 } else { 8980 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 8981 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 8982 return false; 8983 8984 // FIXME: Check that the base class member is accessible? 8985 } 8986 } else { 8987 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8988 if (FoundRecord && FoundRecord->isInjectedClassName()) 8989 return false; 8990 } 8991 8992 if (isa<TypeDecl>(ND)) 8993 return HasTypenameKeyword || !IsInstantiation; 8994 8995 return !HasTypenameKeyword; 8996 } 8997 8998 private: 8999 bool HasTypenameKeyword; 9000 bool IsInstantiation; 9001 NestedNameSpecifier *OldNNS; 9002 CXXRecordDecl *RequireMemberOf; 9003 }; 9004 } // end anonymous namespace 9005 9006 /// Builds a using declaration. 9007 /// 9008 /// \param IsInstantiation - Whether this call arises from an 9009 /// instantiation of an unresolved using declaration. We treat 9010 /// the lookup differently for these declarations. 9011 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9012 SourceLocation UsingLoc, 9013 CXXScopeSpec &SS, 9014 DeclarationNameInfo NameInfo, 9015 AttributeList *AttrList, 9016 bool IsInstantiation, 9017 bool HasTypenameKeyword, 9018 SourceLocation TypenameLoc) { 9019 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9020 SourceLocation IdentLoc = NameInfo.getLoc(); 9021 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9022 9023 // FIXME: We ignore attributes for now. 9024 9025 if (SS.isEmpty()) { 9026 Diag(IdentLoc, diag::err_using_requires_qualname); 9027 return nullptr; 9028 } 9029 9030 // For an inheriting constructor declaration, the name of the using 9031 // declaration is the name of a constructor in this class, not in the 9032 // base class. 9033 DeclarationNameInfo UsingName = NameInfo; 9034 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9035 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9036 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9037 Context.getCanonicalType(Context.getRecordType(RD)))); 9038 9039 // Do the redeclaration lookup in the current scope. 9040 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9041 ForRedeclaration); 9042 Previous.setHideTags(false); 9043 if (S) { 9044 LookupName(Previous, S); 9045 9046 // It is really dumb that we have to do this. 9047 LookupResult::Filter F = Previous.makeFilter(); 9048 while (F.hasNext()) { 9049 NamedDecl *D = F.next(); 9050 if (!isDeclInScope(D, CurContext, S)) 9051 F.erase(); 9052 // If we found a local extern declaration that's not ordinarily visible, 9053 // and this declaration is being added to a non-block scope, ignore it. 9054 // We're only checking for scope conflicts here, not also for violations 9055 // of the linkage rules. 9056 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9057 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9058 F.erase(); 9059 } 9060 F.done(); 9061 } else { 9062 assert(IsInstantiation && "no scope in non-instantiation"); 9063 assert(CurContext->isRecord() && "scope not record in instantiation"); 9064 LookupQualifiedName(Previous, CurContext); 9065 } 9066 9067 // Check for invalid redeclarations. 9068 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9069 SS, IdentLoc, Previous)) 9070 return nullptr; 9071 9072 // Check for bad qualifiers. 9073 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 9074 return nullptr; 9075 9076 DeclContext *LookupContext = computeDeclContext(SS); 9077 NamedDecl *D; 9078 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9079 if (!LookupContext) { 9080 if (HasTypenameKeyword) { 9081 // FIXME: not all declaration name kinds are legal here 9082 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9083 UsingLoc, TypenameLoc, 9084 QualifierLoc, 9085 IdentLoc, NameInfo.getName()); 9086 } else { 9087 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9088 QualifierLoc, NameInfo); 9089 } 9090 D->setAccess(AS); 9091 CurContext->addDecl(D); 9092 return D; 9093 } 9094 9095 auto Build = [&](bool Invalid) { 9096 UsingDecl *UD = 9097 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9098 UsingName, HasTypenameKeyword); 9099 UD->setAccess(AS); 9100 CurContext->addDecl(UD); 9101 UD->setInvalidDecl(Invalid); 9102 return UD; 9103 }; 9104 auto BuildInvalid = [&]{ return Build(true); }; 9105 auto BuildValid = [&]{ return Build(false); }; 9106 9107 if (RequireCompleteDeclContext(SS, LookupContext)) 9108 return BuildInvalid(); 9109 9110 // Look up the target name. 9111 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9112 9113 // Unlike most lookups, we don't always want to hide tag 9114 // declarations: tag names are visible through the using declaration 9115 // even if hidden by ordinary names, *except* in a dependent context 9116 // where it's important for the sanity of two-phase lookup. 9117 if (!IsInstantiation) 9118 R.setHideTags(false); 9119 9120 // For the purposes of this lookup, we have a base object type 9121 // equal to that of the current context. 9122 if (CurContext->isRecord()) { 9123 R.setBaseObjectType( 9124 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9125 } 9126 9127 LookupQualifiedName(R, LookupContext); 9128 9129 // Try to correct typos if possible. If constructor name lookup finds no 9130 // results, that means the named class has no explicit constructors, and we 9131 // suppressed declaring implicit ones (probably because it's dependent or 9132 // invalid). 9133 if (R.empty() && 9134 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9135 if (TypoCorrection Corrected = CorrectTypo( 9136 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9137 llvm::make_unique<UsingValidatorCCC>( 9138 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9139 dyn_cast<CXXRecordDecl>(CurContext)), 9140 CTK_ErrorRecovery)) { 9141 // We reject any correction for which ND would be NULL. 9142 NamedDecl *ND = Corrected.getCorrectionDecl(); 9143 9144 // We reject candidates where DroppedSpecifier == true, hence the 9145 // literal '0' below. 9146 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9147 << NameInfo.getName() << LookupContext << 0 9148 << SS.getRange()); 9149 9150 // If we corrected to an inheriting constructor, handle it as one. 9151 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9152 if (RD && RD->isInjectedClassName()) { 9153 // The parent of the injected class name is the class itself. 9154 RD = cast<CXXRecordDecl>(RD->getParent()); 9155 9156 // Fix up the information we'll use to build the using declaration. 9157 if (Corrected.WillReplaceSpecifier()) { 9158 NestedNameSpecifierLocBuilder Builder; 9159 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9160 QualifierLoc.getSourceRange()); 9161 QualifierLoc = Builder.getWithLocInContext(Context); 9162 } 9163 9164 // In this case, the name we introduce is the name of a derived class 9165 // constructor. 9166 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9167 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9168 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9169 UsingName.setNamedTypeInfo(nullptr); 9170 for (auto *Ctor : LookupConstructors(RD)) 9171 R.addDecl(Ctor); 9172 R.resolveKind(); 9173 } else { 9174 // FIXME: Pick up all the declarations if we found an overloaded 9175 // function. 9176 UsingName.setName(ND->getDeclName()); 9177 R.addDecl(ND); 9178 } 9179 } else { 9180 Diag(IdentLoc, diag::err_no_member) 9181 << NameInfo.getName() << LookupContext << SS.getRange(); 9182 return BuildInvalid(); 9183 } 9184 } 9185 9186 if (R.isAmbiguous()) 9187 return BuildInvalid(); 9188 9189 if (HasTypenameKeyword) { 9190 // If we asked for a typename and got a non-type decl, error out. 9191 if (!R.getAsSingle<TypeDecl>()) { 9192 Diag(IdentLoc, diag::err_using_typename_non_type); 9193 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9194 Diag((*I)->getUnderlyingDecl()->getLocation(), 9195 diag::note_using_decl_target); 9196 return BuildInvalid(); 9197 } 9198 } else { 9199 // If we asked for a non-typename and we got a type, error out, 9200 // but only if this is an instantiation of an unresolved using 9201 // decl. Otherwise just silently find the type name. 9202 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9203 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9204 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9205 return BuildInvalid(); 9206 } 9207 } 9208 9209 // C++14 [namespace.udecl]p6: 9210 // A using-declaration shall not name a namespace. 9211 if (R.getAsSingle<NamespaceDecl>()) { 9212 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9213 << SS.getRange(); 9214 return BuildInvalid(); 9215 } 9216 9217 // C++14 [namespace.udecl]p7: 9218 // A using-declaration shall not name a scoped enumerator. 9219 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9220 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9221 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9222 << SS.getRange(); 9223 return BuildInvalid(); 9224 } 9225 } 9226 9227 UsingDecl *UD = BuildValid(); 9228 9229 // Some additional rules apply to inheriting constructors. 9230 if (UsingName.getName().getNameKind() == 9231 DeclarationName::CXXConstructorName) { 9232 // Suppress access diagnostics; the access check is instead performed at the 9233 // point of use for an inheriting constructor. 9234 R.suppressDiagnostics(); 9235 if (CheckInheritingConstructorUsingDecl(UD)) 9236 return UD; 9237 } 9238 9239 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9240 UsingShadowDecl *PrevDecl = nullptr; 9241 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9242 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9243 } 9244 9245 return UD; 9246 } 9247 9248 /// Additional checks for a using declaration referring to a constructor name. 9249 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9250 assert(!UD->hasTypename() && "expecting a constructor name"); 9251 9252 const Type *SourceType = UD->getQualifier()->getAsType(); 9253 assert(SourceType && 9254 "Using decl naming constructor doesn't have type in scope spec."); 9255 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9256 9257 // Check whether the named type is a direct base class. 9258 bool AnyDependentBases = false; 9259 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9260 AnyDependentBases); 9261 if (!Base && !AnyDependentBases) { 9262 Diag(UD->getUsingLoc(), 9263 diag::err_using_decl_constructor_not_in_direct_base) 9264 << UD->getNameInfo().getSourceRange() 9265 << QualType(SourceType, 0) << TargetClass; 9266 UD->setInvalidDecl(); 9267 return true; 9268 } 9269 9270 if (Base) 9271 Base->setInheritConstructors(); 9272 9273 return false; 9274 } 9275 9276 /// Checks that the given using declaration is not an invalid 9277 /// redeclaration. Note that this is checking only for the using decl 9278 /// itself, not for any ill-formedness among the UsingShadowDecls. 9279 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9280 bool HasTypenameKeyword, 9281 const CXXScopeSpec &SS, 9282 SourceLocation NameLoc, 9283 const LookupResult &Prev) { 9284 // C++03 [namespace.udecl]p8: 9285 // C++0x [namespace.udecl]p10: 9286 // A using-declaration is a declaration and can therefore be used 9287 // repeatedly where (and only where) multiple declarations are 9288 // allowed. 9289 // 9290 // That's in non-member contexts. 9291 if (!CurContext->getRedeclContext()->isRecord()) 9292 return false; 9293 9294 NestedNameSpecifier *Qual = SS.getScopeRep(); 9295 9296 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9297 NamedDecl *D = *I; 9298 9299 bool DTypename; 9300 NestedNameSpecifier *DQual; 9301 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9302 DTypename = UD->hasTypename(); 9303 DQual = UD->getQualifier(); 9304 } else if (UnresolvedUsingValueDecl *UD 9305 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9306 DTypename = false; 9307 DQual = UD->getQualifier(); 9308 } else if (UnresolvedUsingTypenameDecl *UD 9309 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9310 DTypename = true; 9311 DQual = UD->getQualifier(); 9312 } else continue; 9313 9314 // using decls differ if one says 'typename' and the other doesn't. 9315 // FIXME: non-dependent using decls? 9316 if (HasTypenameKeyword != DTypename) continue; 9317 9318 // using decls differ if they name different scopes (but note that 9319 // template instantiation can cause this check to trigger when it 9320 // didn't before instantiation). 9321 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9322 Context.getCanonicalNestedNameSpecifier(DQual)) 9323 continue; 9324 9325 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9326 Diag(D->getLocation(), diag::note_using_decl) << 1; 9327 return true; 9328 } 9329 9330 return false; 9331 } 9332 9333 9334 /// Checks that the given nested-name qualifier used in a using decl 9335 /// in the current context is appropriately related to the current 9336 /// scope. If an error is found, diagnoses it and returns true. 9337 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9338 const CXXScopeSpec &SS, 9339 const DeclarationNameInfo &NameInfo, 9340 SourceLocation NameLoc) { 9341 DeclContext *NamedContext = computeDeclContext(SS); 9342 9343 if (!CurContext->isRecord()) { 9344 // C++03 [namespace.udecl]p3: 9345 // C++0x [namespace.udecl]p8: 9346 // A using-declaration for a class member shall be a member-declaration. 9347 9348 // If we weren't able to compute a valid scope, it must be a 9349 // dependent class scope. 9350 if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) { 9351 auto *RD = NamedContext 9352 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9353 : nullptr; 9354 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9355 RD = nullptr; 9356 9357 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9358 << SS.getRange(); 9359 9360 // If we have a complete, non-dependent source type, try to suggest a 9361 // way to get the same effect. 9362 if (!RD) 9363 return true; 9364 9365 // Find what this using-declaration was referring to. 9366 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9367 R.setHideTags(false); 9368 R.suppressDiagnostics(); 9369 LookupQualifiedName(R, RD); 9370 9371 if (R.getAsSingle<TypeDecl>()) { 9372 if (getLangOpts().CPlusPlus11) { 9373 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9374 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9375 << 0 // alias declaration 9376 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9377 NameInfo.getName().getAsString() + 9378 " = "); 9379 } else { 9380 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9381 SourceLocation InsertLoc = 9382 getLocForEndOfToken(NameInfo.getLocEnd()); 9383 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9384 << 1 // typedef declaration 9385 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9386 << FixItHint::CreateInsertion( 9387 InsertLoc, " " + NameInfo.getName().getAsString()); 9388 } 9389 } else if (R.getAsSingle<VarDecl>()) { 9390 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9391 // repeating the type of the static data member here. 9392 FixItHint FixIt; 9393 if (getLangOpts().CPlusPlus11) { 9394 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9395 FixIt = FixItHint::CreateReplacement( 9396 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9397 } 9398 9399 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9400 << 2 // reference declaration 9401 << FixIt; 9402 } else if (R.getAsSingle<EnumConstantDecl>()) { 9403 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9404 // repeating the type of the enumeration here, and we can't do so if 9405 // the type is anonymous. 9406 FixItHint FixIt; 9407 if (getLangOpts().CPlusPlus11) { 9408 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9409 FixIt = FixItHint::CreateReplacement( 9410 UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = "); 9411 } 9412 9413 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9414 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 9415 << FixIt; 9416 } 9417 return true; 9418 } 9419 9420 // Otherwise, everything is known to be fine. 9421 return false; 9422 } 9423 9424 // The current scope is a record. 9425 9426 // If the named context is dependent, we can't decide much. 9427 if (!NamedContext) { 9428 // FIXME: in C++0x, we can diagnose if we can prove that the 9429 // nested-name-specifier does not refer to a base class, which is 9430 // still possible in some cases. 9431 9432 // Otherwise we have to conservatively report that things might be 9433 // okay. 9434 return false; 9435 } 9436 9437 if (!NamedContext->isRecord()) { 9438 // Ideally this would point at the last name in the specifier, 9439 // but we don't have that level of source info. 9440 Diag(SS.getRange().getBegin(), 9441 diag::err_using_decl_nested_name_specifier_is_not_class) 9442 << SS.getScopeRep() << SS.getRange(); 9443 return true; 9444 } 9445 9446 if (!NamedContext->isDependentContext() && 9447 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 9448 return true; 9449 9450 if (getLangOpts().CPlusPlus11) { 9451 // C++11 [namespace.udecl]p3: 9452 // In a using-declaration used as a member-declaration, the 9453 // nested-name-specifier shall name a base class of the class 9454 // being defined. 9455 9456 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 9457 cast<CXXRecordDecl>(NamedContext))) { 9458 if (CurContext == NamedContext) { 9459 Diag(NameLoc, 9460 diag::err_using_decl_nested_name_specifier_is_current_class) 9461 << SS.getRange(); 9462 return true; 9463 } 9464 9465 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 9466 Diag(SS.getRange().getBegin(), 9467 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9468 << SS.getScopeRep() 9469 << cast<CXXRecordDecl>(CurContext) 9470 << SS.getRange(); 9471 } 9472 return true; 9473 } 9474 9475 return false; 9476 } 9477 9478 // C++03 [namespace.udecl]p4: 9479 // A using-declaration used as a member-declaration shall refer 9480 // to a member of a base class of the class being defined [etc.]. 9481 9482 // Salient point: SS doesn't have to name a base class as long as 9483 // lookup only finds members from base classes. Therefore we can 9484 // diagnose here only if we can prove that that can't happen, 9485 // i.e. if the class hierarchies provably don't intersect. 9486 9487 // TODO: it would be nice if "definitely valid" results were cached 9488 // in the UsingDecl and UsingShadowDecl so that these checks didn't 9489 // need to be repeated. 9490 9491 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 9492 auto Collect = [&Bases](const CXXRecordDecl *Base) { 9493 Bases.insert(Base); 9494 return true; 9495 }; 9496 9497 // Collect all bases. Return false if we find a dependent base. 9498 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 9499 return false; 9500 9501 // Returns true if the base is dependent or is one of the accumulated base 9502 // classes. 9503 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 9504 return !Bases.count(Base); 9505 }; 9506 9507 // Return false if the class has a dependent base or if it or one 9508 // of its bases is present in the base set of the current context. 9509 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 9510 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 9511 return false; 9512 9513 Diag(SS.getRange().getBegin(), 9514 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9515 << SS.getScopeRep() 9516 << cast<CXXRecordDecl>(CurContext) 9517 << SS.getRange(); 9518 9519 return true; 9520 } 9521 9522 Decl *Sema::ActOnAliasDeclaration(Scope *S, 9523 AccessSpecifier AS, 9524 MultiTemplateParamsArg TemplateParamLists, 9525 SourceLocation UsingLoc, 9526 UnqualifiedId &Name, 9527 AttributeList *AttrList, 9528 TypeResult Type, 9529 Decl *DeclFromDeclSpec) { 9530 // Skip up to the relevant declaration scope. 9531 while (S->isTemplateParamScope()) 9532 S = S->getParent(); 9533 assert((S->getFlags() & Scope::DeclScope) && 9534 "got alias-declaration outside of declaration scope"); 9535 9536 if (Type.isInvalid()) 9537 return nullptr; 9538 9539 bool Invalid = false; 9540 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 9541 TypeSourceInfo *TInfo = nullptr; 9542 GetTypeFromParser(Type.get(), &TInfo); 9543 9544 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 9545 return nullptr; 9546 9547 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 9548 UPPC_DeclarationType)) { 9549 Invalid = true; 9550 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9551 TInfo->getTypeLoc().getBeginLoc()); 9552 } 9553 9554 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 9555 LookupName(Previous, S); 9556 9557 // Warn about shadowing the name of a template parameter. 9558 if (Previous.isSingleResult() && 9559 Previous.getFoundDecl()->isTemplateParameter()) { 9560 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 9561 Previous.clear(); 9562 } 9563 9564 assert(Name.Kind == UnqualifiedId::IK_Identifier && 9565 "name in alias declaration must be an identifier"); 9566 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 9567 Name.StartLocation, 9568 Name.Identifier, TInfo); 9569 9570 NewTD->setAccess(AS); 9571 9572 if (Invalid) 9573 NewTD->setInvalidDecl(); 9574 9575 ProcessDeclAttributeList(S, NewTD, AttrList); 9576 9577 CheckTypedefForVariablyModifiedType(S, NewTD); 9578 Invalid |= NewTD->isInvalidDecl(); 9579 9580 bool Redeclaration = false; 9581 9582 NamedDecl *NewND; 9583 if (TemplateParamLists.size()) { 9584 TypeAliasTemplateDecl *OldDecl = nullptr; 9585 TemplateParameterList *OldTemplateParams = nullptr; 9586 9587 if (TemplateParamLists.size() != 1) { 9588 Diag(UsingLoc, diag::err_alias_template_extra_headers) 9589 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 9590 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 9591 } 9592 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 9593 9594 // Check that we can declare a template here. 9595 if (CheckTemplateDeclScope(S, TemplateParams)) 9596 return nullptr; 9597 9598 // Only consider previous declarations in the same scope. 9599 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 9600 /*ExplicitInstantiationOrSpecialization*/false); 9601 if (!Previous.empty()) { 9602 Redeclaration = true; 9603 9604 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 9605 if (!OldDecl && !Invalid) { 9606 Diag(UsingLoc, diag::err_redefinition_different_kind) 9607 << Name.Identifier; 9608 9609 NamedDecl *OldD = Previous.getRepresentativeDecl(); 9610 if (OldD->getLocation().isValid()) 9611 Diag(OldD->getLocation(), diag::note_previous_definition); 9612 9613 Invalid = true; 9614 } 9615 9616 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 9617 if (TemplateParameterListsAreEqual(TemplateParams, 9618 OldDecl->getTemplateParameters(), 9619 /*Complain=*/true, 9620 TPL_TemplateMatch)) 9621 OldTemplateParams = OldDecl->getTemplateParameters(); 9622 else 9623 Invalid = true; 9624 9625 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 9626 if (!Invalid && 9627 !Context.hasSameType(OldTD->getUnderlyingType(), 9628 NewTD->getUnderlyingType())) { 9629 // FIXME: The C++0x standard does not clearly say this is ill-formed, 9630 // but we can't reasonably accept it. 9631 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 9632 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 9633 if (OldTD->getLocation().isValid()) 9634 Diag(OldTD->getLocation(), diag::note_previous_definition); 9635 Invalid = true; 9636 } 9637 } 9638 } 9639 9640 // Merge any previous default template arguments into our parameters, 9641 // and check the parameter list. 9642 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 9643 TPC_TypeAliasTemplate)) 9644 return nullptr; 9645 9646 TypeAliasTemplateDecl *NewDecl = 9647 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 9648 Name.Identifier, TemplateParams, 9649 NewTD); 9650 NewTD->setDescribedAliasTemplate(NewDecl); 9651 9652 NewDecl->setAccess(AS); 9653 9654 if (Invalid) 9655 NewDecl->setInvalidDecl(); 9656 else if (OldDecl) 9657 NewDecl->setPreviousDecl(OldDecl); 9658 9659 NewND = NewDecl; 9660 } else { 9661 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 9662 setTagNameForLinkagePurposes(TD, NewTD); 9663 handleTagNumbering(TD, S); 9664 } 9665 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 9666 NewND = NewTD; 9667 } 9668 9669 PushOnScopeChains(NewND, S); 9670 ActOnDocumentableDecl(NewND); 9671 return NewND; 9672 } 9673 9674 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 9675 SourceLocation AliasLoc, 9676 IdentifierInfo *Alias, CXXScopeSpec &SS, 9677 SourceLocation IdentLoc, 9678 IdentifierInfo *Ident) { 9679 9680 // Lookup the namespace name. 9681 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 9682 LookupParsedName(R, S, &SS); 9683 9684 if (R.isAmbiguous()) 9685 return nullptr; 9686 9687 if (R.empty()) { 9688 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 9689 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9690 return nullptr; 9691 } 9692 } 9693 assert(!R.isAmbiguous() && !R.empty()); 9694 NamedDecl *ND = R.getRepresentativeDecl(); 9695 9696 // Check if we have a previous declaration with the same name. 9697 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 9698 ForRedeclaration); 9699 LookupName(PrevR, S); 9700 9701 // Check we're not shadowing a template parameter. 9702 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 9703 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 9704 PrevR.clear(); 9705 } 9706 9707 // Filter out any other lookup result from an enclosing scope. 9708 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 9709 /*AllowInlineNamespace*/false); 9710 9711 // Find the previous declaration and check that we can redeclare it. 9712 NamespaceAliasDecl *Prev = nullptr; 9713 if (PrevR.isSingleResult()) { 9714 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 9715 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 9716 // We already have an alias with the same name that points to the same 9717 // namespace; check that it matches. 9718 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 9719 Prev = AD; 9720 } else if (isVisible(PrevDecl)) { 9721 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 9722 << Alias; 9723 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 9724 << AD->getNamespace(); 9725 return nullptr; 9726 } 9727 } else if (isVisible(PrevDecl)) { 9728 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 9729 ? diag::err_redefinition 9730 : diag::err_redefinition_different_kind; 9731 Diag(AliasLoc, DiagID) << Alias; 9732 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9733 return nullptr; 9734 } 9735 } 9736 9737 // The use of a nested name specifier may trigger deprecation warnings. 9738 DiagnoseUseOfDecl(ND, IdentLoc); 9739 9740 NamespaceAliasDecl *AliasDecl = 9741 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 9742 Alias, SS.getWithLocInContext(Context), 9743 IdentLoc, ND); 9744 if (Prev) 9745 AliasDecl->setPreviousDecl(Prev); 9746 9747 PushOnScopeChains(AliasDecl, S); 9748 return AliasDecl; 9749 } 9750 9751 Sema::ImplicitExceptionSpecification 9752 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 9753 CXXMethodDecl *MD) { 9754 CXXRecordDecl *ClassDecl = MD->getParent(); 9755 9756 // C++ [except.spec]p14: 9757 // An implicitly declared special member function (Clause 12) shall have an 9758 // exception-specification. [...] 9759 ImplicitExceptionSpecification ExceptSpec(*this); 9760 if (ClassDecl->isInvalidDecl()) 9761 return ExceptSpec; 9762 9763 // Direct base-class constructors. 9764 for (const auto &B : ClassDecl->bases()) { 9765 if (B.isVirtual()) // Handled below. 9766 continue; 9767 9768 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 9769 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9770 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 9771 // If this is a deleted function, add it anyway. This might be conformant 9772 // with the standard. This might not. I'm not sure. It might not matter. 9773 if (Constructor) 9774 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 9775 } 9776 } 9777 9778 // Virtual base-class constructors. 9779 for (const auto &B : ClassDecl->vbases()) { 9780 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 9781 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9782 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 9783 // If this is a deleted function, add it anyway. This might be conformant 9784 // with the standard. This might not. I'm not sure. It might not matter. 9785 if (Constructor) 9786 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 9787 } 9788 } 9789 9790 // Field constructors. 9791 for (const auto *F : ClassDecl->fields()) { 9792 if (F->hasInClassInitializer()) { 9793 if (Expr *E = F->getInClassInitializer()) 9794 ExceptSpec.CalledExpr(E); 9795 } else if (const RecordType *RecordTy 9796 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 9797 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9798 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 9799 // If this is a deleted function, add it anyway. This might be conformant 9800 // with the standard. This might not. I'm not sure. It might not matter. 9801 // In particular, the problem is that this function never gets called. It 9802 // might just be ill-formed because this function attempts to refer to 9803 // a deleted function here. 9804 if (Constructor) 9805 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9806 } 9807 } 9808 9809 return ExceptSpec; 9810 } 9811 9812 Sema::ImplicitExceptionSpecification 9813 Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc, 9814 CXXConstructorDecl *CD) { 9815 CXXRecordDecl *ClassDecl = CD->getParent(); 9816 9817 // C++ [except.spec]p14: 9818 // An inheriting constructor [...] shall have an exception-specification. [...] 9819 ImplicitExceptionSpecification ExceptSpec(*this); 9820 if (ClassDecl->isInvalidDecl()) 9821 return ExceptSpec; 9822 9823 auto Inherited = CD->getInheritedConstructor(); 9824 InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl()); 9825 9826 // Direct and virtual base-class constructors. 9827 for (bool VBase : {false, true}) { 9828 for (CXXBaseSpecifier &B : 9829 VBase ? ClassDecl->vbases() : ClassDecl->bases()) { 9830 // Don't visit direct vbases twice. 9831 if (B.isVirtual() != VBase) 9832 continue; 9833 9834 CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl(); 9835 if (!BaseClass) 9836 continue; 9837 9838 CXXConstructorDecl *Constructor = 9839 ICI.findConstructorForBase(BaseClass, Inherited.getConstructor()) 9840 .first; 9841 if (!Constructor) 9842 Constructor = LookupDefaultConstructor(BaseClass); 9843 if (Constructor) 9844 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 9845 } 9846 } 9847 9848 // Field constructors. 9849 for (const auto *F : ClassDecl->fields()) { 9850 if (F->hasInClassInitializer()) { 9851 if (Expr *E = F->getInClassInitializer()) 9852 ExceptSpec.CalledExpr(E); 9853 } else if (const RecordType *RecordTy 9854 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 9855 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9856 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 9857 if (Constructor) 9858 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9859 } 9860 } 9861 9862 return ExceptSpec; 9863 } 9864 9865 namespace { 9866 /// RAII object to register a special member as being currently declared. 9867 struct DeclaringSpecialMember { 9868 Sema &S; 9869 Sema::SpecialMemberDecl D; 9870 Sema::ContextRAII SavedContext; 9871 bool WasAlreadyBeingDeclared; 9872 9873 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 9874 : S(S), D(RD, CSM), SavedContext(S, RD) { 9875 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 9876 if (WasAlreadyBeingDeclared) 9877 // This almost never happens, but if it does, ensure that our cache 9878 // doesn't contain a stale result. 9879 S.SpecialMemberCache.clear(); 9880 9881 // FIXME: Register a note to be produced if we encounter an error while 9882 // declaring the special member. 9883 } 9884 ~DeclaringSpecialMember() { 9885 if (!WasAlreadyBeingDeclared) 9886 S.SpecialMembersBeingDeclared.erase(D); 9887 } 9888 9889 /// \brief Are we already trying to declare this special member? 9890 bool isAlreadyBeingDeclared() const { 9891 return WasAlreadyBeingDeclared; 9892 } 9893 }; 9894 } 9895 9896 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 9897 // Look up any existing declarations, but don't trigger declaration of all 9898 // implicit special members with this name. 9899 DeclarationName Name = FD->getDeclName(); 9900 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 9901 ForRedeclaration); 9902 for (auto *D : FD->getParent()->lookup(Name)) 9903 if (auto *Acceptable = R.getAcceptableDecl(D)) 9904 R.addDecl(Acceptable); 9905 R.resolveKind(); 9906 R.suppressDiagnostics(); 9907 9908 CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false); 9909 } 9910 9911 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 9912 CXXRecordDecl *ClassDecl) { 9913 // C++ [class.ctor]p5: 9914 // A default constructor for a class X is a constructor of class X 9915 // that can be called without an argument. If there is no 9916 // user-declared constructor for class X, a default constructor is 9917 // implicitly declared. An implicitly-declared default constructor 9918 // is an inline public member of its class. 9919 assert(ClassDecl->needsImplicitDefaultConstructor() && 9920 "Should not build implicit default constructor!"); 9921 9922 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 9923 if (DSM.isAlreadyBeingDeclared()) 9924 return nullptr; 9925 9926 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9927 CXXDefaultConstructor, 9928 false); 9929 9930 // Create the actual constructor declaration. 9931 CanQualType ClassType 9932 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9933 SourceLocation ClassLoc = ClassDecl->getLocation(); 9934 DeclarationName Name 9935 = Context.DeclarationNames.getCXXConstructorName(ClassType); 9936 DeclarationNameInfo NameInfo(Name, ClassLoc); 9937 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 9938 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 9939 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 9940 /*isImplicitlyDeclared=*/true, Constexpr); 9941 DefaultCon->setAccess(AS_public); 9942 DefaultCon->setDefaulted(); 9943 9944 if (getLangOpts().CUDA) { 9945 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 9946 DefaultCon, 9947 /* ConstRHS */ false, 9948 /* Diagnose */ false); 9949 } 9950 9951 // Build an exception specification pointing back at this constructor. 9952 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 9953 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9954 9955 // We don't need to use SpecialMemberIsTrivial here; triviality for default 9956 // constructors is easy to compute. 9957 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 9958 9959 // Note that we have declared this constructor. 9960 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 9961 9962 Scope *S = getScopeForContext(ClassDecl); 9963 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 9964 9965 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 9966 SetDeclDeleted(DefaultCon, ClassLoc); 9967 9968 if (S) 9969 PushOnScopeChains(DefaultCon, S, false); 9970 ClassDecl->addDecl(DefaultCon); 9971 9972 return DefaultCon; 9973 } 9974 9975 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 9976 CXXConstructorDecl *Constructor) { 9977 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 9978 !Constructor->doesThisDeclarationHaveABody() && 9979 !Constructor->isDeleted()) && 9980 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 9981 9982 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9983 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 9984 9985 SynthesizedFunctionScope Scope(*this, Constructor); 9986 DiagnosticErrorTrap Trap(Diags); 9987 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9988 Trap.hasErrorOccurred()) { 9989 Diag(CurrentLocation, diag::note_member_synthesized_at) 9990 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 9991 Constructor->setInvalidDecl(); 9992 return; 9993 } 9994 9995 // The exception specification is needed because we are defining the 9996 // function. 9997 ResolveExceptionSpec(CurrentLocation, 9998 Constructor->getType()->castAs<FunctionProtoType>()); 9999 10000 SourceLocation Loc = Constructor->getLocEnd().isValid() 10001 ? Constructor->getLocEnd() 10002 : Constructor->getLocation(); 10003 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10004 10005 Constructor->markUsed(Context); 10006 MarkVTableUsed(CurrentLocation, ClassDecl); 10007 10008 if (ASTMutationListener *L = getASTMutationListener()) { 10009 L->CompletedImplicitDefinition(Constructor); 10010 } 10011 10012 DiagnoseUninitializedFields(*this, Constructor); 10013 } 10014 10015 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10016 // Perform any delayed checks on exception specifications. 10017 CheckDelayedMemberExceptionSpecs(); 10018 } 10019 10020 /// Find or create the fake constructor we synthesize to model constructing an 10021 /// object of a derived class via a constructor of a base class. 10022 CXXConstructorDecl * 10023 Sema::findInheritingConstructor(SourceLocation Loc, 10024 CXXConstructorDecl *BaseCtor, 10025 ConstructorUsingShadowDecl *Shadow) { 10026 CXXRecordDecl *Derived = Shadow->getParent(); 10027 SourceLocation UsingLoc = Shadow->getLocation(); 10028 10029 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10030 // For now we use the name of the base class constructor as a member of the 10031 // derived class to indicate a (fake) inherited constructor name. 10032 DeclarationName Name = BaseCtor->getDeclName(); 10033 10034 // Check to see if we already have a fake constructor for this inherited 10035 // constructor call. 10036 for (NamedDecl *Ctor : Derived->lookup(Name)) 10037 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10038 ->getInheritedConstructor() 10039 .getConstructor(), 10040 BaseCtor)) 10041 return cast<CXXConstructorDecl>(Ctor); 10042 10043 DeclarationNameInfo NameInfo(Name, UsingLoc); 10044 TypeSourceInfo *TInfo = 10045 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10046 FunctionProtoTypeLoc ProtoLoc = 10047 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10048 10049 // Check the inherited constructor is valid and find the list of base classes 10050 // from which it was inherited. 10051 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10052 10053 bool Constexpr = 10054 BaseCtor->isConstexpr() && 10055 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10056 false, BaseCtor, &ICI); 10057 10058 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10059 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10060 BaseCtor->isExplicit(), /*Inline=*/true, 10061 /*ImplicitlyDeclared=*/true, Constexpr, 10062 InheritedConstructor(Shadow, BaseCtor)); 10063 if (Shadow->isInvalidDecl()) 10064 DerivedCtor->setInvalidDecl(); 10065 10066 // Build an unevaluated exception specification for this fake constructor. 10067 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10068 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10069 EPI.ExceptionSpec.Type = EST_Unevaluated; 10070 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10071 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10072 FPT->getParamTypes(), EPI)); 10073 10074 // Build the parameter declarations. 10075 SmallVector<ParmVarDecl *, 16> ParamDecls; 10076 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10077 TypeSourceInfo *TInfo = 10078 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10079 ParmVarDecl *PD = ParmVarDecl::Create( 10080 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10081 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10082 PD->setScopeInfo(0, I); 10083 PD->setImplicit(); 10084 // Ensure attributes are propagated onto parameters (this matters for 10085 // format, pass_object_size, ...). 10086 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10087 ParamDecls.push_back(PD); 10088 ProtoLoc.setParam(I, PD); 10089 } 10090 10091 // Set up the new constructor. 10092 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10093 DerivedCtor->setAccess(BaseCtor->getAccess()); 10094 DerivedCtor->setParams(ParamDecls); 10095 Derived->addDecl(DerivedCtor); 10096 10097 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10098 SetDeclDeleted(DerivedCtor, UsingLoc); 10099 10100 return DerivedCtor; 10101 } 10102 10103 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10104 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10105 Ctor->getInheritedConstructor().getShadowDecl()); 10106 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10107 /*Diagnose*/true); 10108 } 10109 10110 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10111 CXXConstructorDecl *Constructor) { 10112 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10113 assert(Constructor->getInheritedConstructor() && 10114 !Constructor->doesThisDeclarationHaveABody() && 10115 !Constructor->isDeleted()); 10116 if (Constructor->isInvalidDecl()) 10117 return; 10118 10119 ConstructorUsingShadowDecl *Shadow = 10120 Constructor->getInheritedConstructor().getShadowDecl(); 10121 CXXConstructorDecl *InheritedCtor = 10122 Constructor->getInheritedConstructor().getConstructor(); 10123 10124 // [class.inhctor.init]p1: 10125 // initialization proceeds as if a defaulted default constructor is used to 10126 // initialize the D object and each base class subobject from which the 10127 // constructor was inherited 10128 10129 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10130 CXXRecordDecl *RD = Shadow->getParent(); 10131 SourceLocation InitLoc = Shadow->getLocation(); 10132 10133 // Initializations are performed "as if by a defaulted default constructor", 10134 // so enter the appropriate scope. 10135 SynthesizedFunctionScope Scope(*this, Constructor); 10136 DiagnosticErrorTrap Trap(Diags); 10137 10138 // Build explicit initializers for all base classes from which the 10139 // constructor was inherited. 10140 SmallVector<CXXCtorInitializer*, 8> Inits; 10141 for (bool VBase : {false, true}) { 10142 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10143 if (B.isVirtual() != VBase) 10144 continue; 10145 10146 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10147 if (!BaseRD) 10148 continue; 10149 10150 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10151 if (!BaseCtor.first) 10152 continue; 10153 10154 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10155 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10156 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10157 10158 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10159 Inits.push_back(new (Context) CXXCtorInitializer( 10160 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10161 SourceLocation())); 10162 } 10163 } 10164 10165 // We now proceed as if for a defaulted default constructor, with the relevant 10166 // initializers replaced. 10167 10168 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits); 10169 if (HadError || Trap.hasErrorOccurred()) { 10170 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD; 10171 Constructor->setInvalidDecl(); 10172 return; 10173 } 10174 10175 // The exception specification is needed because we are defining the 10176 // function. 10177 ResolveExceptionSpec(CurrentLocation, 10178 Constructor->getType()->castAs<FunctionProtoType>()); 10179 10180 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10181 10182 Constructor->markUsed(Context); 10183 MarkVTableUsed(CurrentLocation, ClassDecl); 10184 10185 if (ASTMutationListener *L = getASTMutationListener()) { 10186 L->CompletedImplicitDefinition(Constructor); 10187 } 10188 10189 DiagnoseUninitializedFields(*this, Constructor); 10190 } 10191 10192 Sema::ImplicitExceptionSpecification 10193 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 10194 CXXRecordDecl *ClassDecl = MD->getParent(); 10195 10196 // C++ [except.spec]p14: 10197 // An implicitly declared special member function (Clause 12) shall have 10198 // an exception-specification. 10199 ImplicitExceptionSpecification ExceptSpec(*this); 10200 if (ClassDecl->isInvalidDecl()) 10201 return ExceptSpec; 10202 10203 // Direct base-class destructors. 10204 for (const auto &B : ClassDecl->bases()) { 10205 if (B.isVirtual()) // Handled below. 10206 continue; 10207 10208 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 10209 ExceptSpec.CalledDecl(B.getLocStart(), 10210 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 10211 } 10212 10213 // Virtual base-class destructors. 10214 for (const auto &B : ClassDecl->vbases()) { 10215 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 10216 ExceptSpec.CalledDecl(B.getLocStart(), 10217 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 10218 } 10219 10220 // Field destructors. 10221 for (const auto *F : ClassDecl->fields()) { 10222 if (const RecordType *RecordTy 10223 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 10224 ExceptSpec.CalledDecl(F->getLocation(), 10225 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 10226 } 10227 10228 return ExceptSpec; 10229 } 10230 10231 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10232 // C++ [class.dtor]p2: 10233 // If a class has no user-declared destructor, a destructor is 10234 // declared implicitly. An implicitly-declared destructor is an 10235 // inline public member of its class. 10236 assert(ClassDecl->needsImplicitDestructor()); 10237 10238 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10239 if (DSM.isAlreadyBeingDeclared()) 10240 return nullptr; 10241 10242 // Create the actual destructor declaration. 10243 CanQualType ClassType 10244 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10245 SourceLocation ClassLoc = ClassDecl->getLocation(); 10246 DeclarationName Name 10247 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10248 DeclarationNameInfo NameInfo(Name, ClassLoc); 10249 CXXDestructorDecl *Destructor 10250 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10251 QualType(), nullptr, /*isInline=*/true, 10252 /*isImplicitlyDeclared=*/true); 10253 Destructor->setAccess(AS_public); 10254 Destructor->setDefaulted(); 10255 10256 if (getLangOpts().CUDA) { 10257 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10258 Destructor, 10259 /* ConstRHS */ false, 10260 /* Diagnose */ false); 10261 } 10262 10263 // Build an exception specification pointing back at this destructor. 10264 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10265 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10266 10267 // We don't need to use SpecialMemberIsTrivial here; triviality for 10268 // destructors is easy to compute. 10269 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10270 10271 // Note that we have declared this destructor. 10272 ++ASTContext::NumImplicitDestructorsDeclared; 10273 10274 Scope *S = getScopeForContext(ClassDecl); 10275 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10276 10277 // We can't check whether an implicit destructor is deleted before we complete 10278 // the definition of the class, because its validity depends on the alignment 10279 // of the class. We'll check this from ActOnFields once the class is complete. 10280 if (ClassDecl->isCompleteDefinition() && 10281 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10282 SetDeclDeleted(Destructor, ClassLoc); 10283 10284 // Introduce this destructor into its scope. 10285 if (S) 10286 PushOnScopeChains(Destructor, S, false); 10287 ClassDecl->addDecl(Destructor); 10288 10289 return Destructor; 10290 } 10291 10292 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10293 CXXDestructorDecl *Destructor) { 10294 assert((Destructor->isDefaulted() && 10295 !Destructor->doesThisDeclarationHaveABody() && 10296 !Destructor->isDeleted()) && 10297 "DefineImplicitDestructor - call it for implicit default dtor"); 10298 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10299 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10300 10301 if (Destructor->isInvalidDecl()) 10302 return; 10303 10304 SynthesizedFunctionScope Scope(*this, Destructor); 10305 10306 DiagnosticErrorTrap Trap(Diags); 10307 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10308 Destructor->getParent()); 10309 10310 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 10311 Diag(CurrentLocation, diag::note_member_synthesized_at) 10312 << CXXDestructor << Context.getTagDeclType(ClassDecl); 10313 10314 Destructor->setInvalidDecl(); 10315 return; 10316 } 10317 10318 // The exception specification is needed because we are defining the 10319 // function. 10320 ResolveExceptionSpec(CurrentLocation, 10321 Destructor->getType()->castAs<FunctionProtoType>()); 10322 10323 SourceLocation Loc = Destructor->getLocEnd().isValid() 10324 ? Destructor->getLocEnd() 10325 : Destructor->getLocation(); 10326 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10327 Destructor->markUsed(Context); 10328 MarkVTableUsed(CurrentLocation, ClassDecl); 10329 10330 if (ASTMutationListener *L = getASTMutationListener()) { 10331 L->CompletedImplicitDefinition(Destructor); 10332 } 10333 } 10334 10335 /// \brief Perform any semantic analysis which needs to be delayed until all 10336 /// pending class member declarations have been parsed. 10337 void Sema::ActOnFinishCXXMemberDecls() { 10338 // If the context is an invalid C++ class, just suppress these checks. 10339 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10340 if (Record->isInvalidDecl()) { 10341 DelayedDefaultedMemberExceptionSpecs.clear(); 10342 DelayedExceptionSpecChecks.clear(); 10343 return; 10344 } 10345 } 10346 } 10347 10348 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 10349 // Don't do anything for template patterns. 10350 if (Class->getDescribedClassTemplate()) 10351 return; 10352 10353 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention( 10354 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 10355 10356 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 10357 for (Decl *Member : Class->decls()) { 10358 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 10359 if (!CD) { 10360 // Recurse on nested classes. 10361 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 10362 getDefaultArgExprsForConstructors(S, NestedRD); 10363 continue; 10364 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 10365 continue; 10366 } 10367 10368 CallingConv ActualCallingConv = 10369 CD->getType()->getAs<FunctionProtoType>()->getCallConv(); 10370 10371 // Skip default constructors with typical calling conventions and no default 10372 // arguments. 10373 unsigned NumParams = CD->getNumParams(); 10374 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0) 10375 continue; 10376 10377 if (LastExportedDefaultCtor) { 10378 S.Diag(LastExportedDefaultCtor->getLocation(), 10379 diag::err_attribute_dll_ambiguous_default_ctor) << Class; 10380 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 10381 << CD->getDeclName(); 10382 return; 10383 } 10384 LastExportedDefaultCtor = CD; 10385 10386 for (unsigned I = 0; I != NumParams; ++I) { 10387 // Skip any default arguments that we've already instantiated. 10388 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 10389 continue; 10390 10391 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 10392 CD->getParamDecl(I)).get(); 10393 S.DiscardCleanupsInEvaluationContext(); 10394 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 10395 } 10396 } 10397 } 10398 10399 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10400 auto *RD = dyn_cast<CXXRecordDecl>(D); 10401 10402 // Default constructors that are annotated with __declspec(dllexport) which 10403 // have default arguments or don't use the standard calling convention are 10404 // wrapped with a thunk called the default constructor closure. 10405 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 10406 getDefaultArgExprsForConstructors(*this, RD); 10407 10408 referenceDLLExportedClassMethods(); 10409 } 10410 10411 void Sema::referenceDLLExportedClassMethods() { 10412 if (!DelayedDllExportClasses.empty()) { 10413 // Calling ReferenceDllExportedMethods might cause the current function to 10414 // be called again, so use a local copy of DelayedDllExportClasses. 10415 SmallVector<CXXRecordDecl *, 4> WorkList; 10416 std::swap(DelayedDllExportClasses, WorkList); 10417 for (CXXRecordDecl *Class : WorkList) 10418 ReferenceDllExportedMethods(*this, Class); 10419 } 10420 } 10421 10422 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10423 CXXDestructorDecl *Destructor) { 10424 assert(getLangOpts().CPlusPlus11 && 10425 "adjusting dtor exception specs was introduced in c++11"); 10426 10427 // C++11 [class.dtor]p3: 10428 // A declaration of a destructor that does not have an exception- 10429 // specification is implicitly considered to have the same exception- 10430 // specification as an implicit declaration. 10431 const FunctionProtoType *DtorType = Destructor->getType()-> 10432 getAs<FunctionProtoType>(); 10433 if (DtorType->hasExceptionSpec()) 10434 return; 10435 10436 // Replace the destructor's type, building off the existing one. Fortunately, 10437 // the only thing of interest in the destructor type is its extended info. 10438 // The return and arguments are fixed. 10439 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10440 EPI.ExceptionSpec.Type = EST_Unevaluated; 10441 EPI.ExceptionSpec.SourceDecl = Destructor; 10442 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10443 10444 // FIXME: If the destructor has a body that could throw, and the newly created 10445 // spec doesn't allow exceptions, we should emit a warning, because this 10446 // change in behavior can break conforming C++03 programs at runtime. 10447 // However, we don't have a body or an exception specification yet, so it 10448 // needs to be done somewhere else. 10449 } 10450 10451 namespace { 10452 /// \brief An abstract base class for all helper classes used in building the 10453 // copy/move operators. These classes serve as factory functions and help us 10454 // avoid using the same Expr* in the AST twice. 10455 class ExprBuilder { 10456 ExprBuilder(const ExprBuilder&) = delete; 10457 ExprBuilder &operator=(const ExprBuilder&) = delete; 10458 10459 protected: 10460 static Expr *assertNotNull(Expr *E) { 10461 assert(E && "Expression construction must not fail."); 10462 return E; 10463 } 10464 10465 public: 10466 ExprBuilder() {} 10467 virtual ~ExprBuilder() {} 10468 10469 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10470 }; 10471 10472 class RefBuilder: public ExprBuilder { 10473 VarDecl *Var; 10474 QualType VarType; 10475 10476 public: 10477 Expr *build(Sema &S, SourceLocation Loc) const override { 10478 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10479 } 10480 10481 RefBuilder(VarDecl *Var, QualType VarType) 10482 : Var(Var), VarType(VarType) {} 10483 }; 10484 10485 class ThisBuilder: public ExprBuilder { 10486 public: 10487 Expr *build(Sema &S, SourceLocation Loc) const override { 10488 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 10489 } 10490 }; 10491 10492 class CastBuilder: public ExprBuilder { 10493 const ExprBuilder &Builder; 10494 QualType Type; 10495 ExprValueKind Kind; 10496 const CXXCastPath &Path; 10497 10498 public: 10499 Expr *build(Sema &S, SourceLocation Loc) const override { 10500 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 10501 CK_UncheckedDerivedToBase, Kind, 10502 &Path).get()); 10503 } 10504 10505 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 10506 const CXXCastPath &Path) 10507 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 10508 }; 10509 10510 class DerefBuilder: public ExprBuilder { 10511 const ExprBuilder &Builder; 10512 10513 public: 10514 Expr *build(Sema &S, SourceLocation Loc) const override { 10515 return assertNotNull( 10516 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 10517 } 10518 10519 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10520 }; 10521 10522 class MemberBuilder: public ExprBuilder { 10523 const ExprBuilder &Builder; 10524 QualType Type; 10525 CXXScopeSpec SS; 10526 bool IsArrow; 10527 LookupResult &MemberLookup; 10528 10529 public: 10530 Expr *build(Sema &S, SourceLocation Loc) const override { 10531 return assertNotNull(S.BuildMemberReferenceExpr( 10532 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 10533 nullptr, MemberLookup, nullptr, nullptr).get()); 10534 } 10535 10536 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 10537 LookupResult &MemberLookup) 10538 : Builder(Builder), Type(Type), IsArrow(IsArrow), 10539 MemberLookup(MemberLookup) {} 10540 }; 10541 10542 class MoveCastBuilder: public ExprBuilder { 10543 const ExprBuilder &Builder; 10544 10545 public: 10546 Expr *build(Sema &S, SourceLocation Loc) const override { 10547 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 10548 } 10549 10550 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10551 }; 10552 10553 class LvalueConvBuilder: public ExprBuilder { 10554 const ExprBuilder &Builder; 10555 10556 public: 10557 Expr *build(Sema &S, SourceLocation Loc) const override { 10558 return assertNotNull( 10559 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 10560 } 10561 10562 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10563 }; 10564 10565 class SubscriptBuilder: public ExprBuilder { 10566 const ExprBuilder &Base; 10567 const ExprBuilder &Index; 10568 10569 public: 10570 Expr *build(Sema &S, SourceLocation Loc) const override { 10571 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 10572 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 10573 } 10574 10575 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 10576 : Base(Base), Index(Index) {} 10577 }; 10578 10579 } // end anonymous namespace 10580 10581 /// When generating a defaulted copy or move assignment operator, if a field 10582 /// should be copied with __builtin_memcpy rather than via explicit assignments, 10583 /// do so. This optimization only applies for arrays of scalars, and for arrays 10584 /// of class type where the selected copy/move-assignment operator is trivial. 10585 static StmtResult 10586 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 10587 const ExprBuilder &ToB, const ExprBuilder &FromB) { 10588 // Compute the size of the memory buffer to be copied. 10589 QualType SizeType = S.Context.getSizeType(); 10590 llvm::APInt Size(S.Context.getTypeSize(SizeType), 10591 S.Context.getTypeSizeInChars(T).getQuantity()); 10592 10593 // Take the address of the field references for "from" and "to". We 10594 // directly construct UnaryOperators here because semantic analysis 10595 // does not permit us to take the address of an xvalue. 10596 Expr *From = FromB.build(S, Loc); 10597 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 10598 S.Context.getPointerType(From->getType()), 10599 VK_RValue, OK_Ordinary, Loc); 10600 Expr *To = ToB.build(S, Loc); 10601 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 10602 S.Context.getPointerType(To->getType()), 10603 VK_RValue, OK_Ordinary, Loc); 10604 10605 const Type *E = T->getBaseElementTypeUnsafe(); 10606 bool NeedsCollectableMemCpy = 10607 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 10608 10609 // Create a reference to the __builtin_objc_memmove_collectable function 10610 StringRef MemCpyName = NeedsCollectableMemCpy ? 10611 "__builtin_objc_memmove_collectable" : 10612 "__builtin_memcpy"; 10613 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 10614 Sema::LookupOrdinaryName); 10615 S.LookupName(R, S.TUScope, true); 10616 10617 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 10618 if (!MemCpy) 10619 // Something went horribly wrong earlier, and we will have complained 10620 // about it. 10621 return StmtError(); 10622 10623 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 10624 VK_RValue, Loc, nullptr); 10625 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 10626 10627 Expr *CallArgs[] = { 10628 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 10629 }; 10630 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 10631 Loc, CallArgs, Loc); 10632 10633 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 10634 return Call.getAs<Stmt>(); 10635 } 10636 10637 /// \brief Builds a statement that copies/moves the given entity from \p From to 10638 /// \c To. 10639 /// 10640 /// This routine is used to copy/move the members of a class with an 10641 /// implicitly-declared copy/move assignment operator. When the entities being 10642 /// copied are arrays, this routine builds for loops to copy them. 10643 /// 10644 /// \param S The Sema object used for type-checking. 10645 /// 10646 /// \param Loc The location where the implicit copy/move is being generated. 10647 /// 10648 /// \param T The type of the expressions being copied/moved. Both expressions 10649 /// must have this type. 10650 /// 10651 /// \param To The expression we are copying/moving to. 10652 /// 10653 /// \param From The expression we are copying/moving from. 10654 /// 10655 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 10656 /// Otherwise, it's a non-static member subobject. 10657 /// 10658 /// \param Copying Whether we're copying or moving. 10659 /// 10660 /// \param Depth Internal parameter recording the depth of the recursion. 10661 /// 10662 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 10663 /// if a memcpy should be used instead. 10664 static StmtResult 10665 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 10666 const ExprBuilder &To, const ExprBuilder &From, 10667 bool CopyingBaseSubobject, bool Copying, 10668 unsigned Depth = 0) { 10669 // C++11 [class.copy]p28: 10670 // Each subobject is assigned in the manner appropriate to its type: 10671 // 10672 // - if the subobject is of class type, as if by a call to operator= with 10673 // the subobject as the object expression and the corresponding 10674 // subobject of x as a single function argument (as if by explicit 10675 // qualification; that is, ignoring any possible virtual overriding 10676 // functions in more derived classes); 10677 // 10678 // C++03 [class.copy]p13: 10679 // - if the subobject is of class type, the copy assignment operator for 10680 // the class is used (as if by explicit qualification; that is, 10681 // ignoring any possible virtual overriding functions in more derived 10682 // classes); 10683 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 10684 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 10685 10686 // Look for operator=. 10687 DeclarationName Name 10688 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10689 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 10690 S.LookupQualifiedName(OpLookup, ClassDecl, false); 10691 10692 // Prior to C++11, filter out any result that isn't a copy/move-assignment 10693 // operator. 10694 if (!S.getLangOpts().CPlusPlus11) { 10695 LookupResult::Filter F = OpLookup.makeFilter(); 10696 while (F.hasNext()) { 10697 NamedDecl *D = F.next(); 10698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 10699 if (Method->isCopyAssignmentOperator() || 10700 (!Copying && Method->isMoveAssignmentOperator())) 10701 continue; 10702 10703 F.erase(); 10704 } 10705 F.done(); 10706 } 10707 10708 // Suppress the protected check (C++ [class.protected]) for each of the 10709 // assignment operators we found. This strange dance is required when 10710 // we're assigning via a base classes's copy-assignment operator. To 10711 // ensure that we're getting the right base class subobject (without 10712 // ambiguities), we need to cast "this" to that subobject type; to 10713 // ensure that we don't go through the virtual call mechanism, we need 10714 // to qualify the operator= name with the base class (see below). However, 10715 // this means that if the base class has a protected copy assignment 10716 // operator, the protected member access check will fail. So, we 10717 // rewrite "protected" access to "public" access in this case, since we 10718 // know by construction that we're calling from a derived class. 10719 if (CopyingBaseSubobject) { 10720 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 10721 L != LEnd; ++L) { 10722 if (L.getAccess() == AS_protected) 10723 L.setAccess(AS_public); 10724 } 10725 } 10726 10727 // Create the nested-name-specifier that will be used to qualify the 10728 // reference to operator=; this is required to suppress the virtual 10729 // call mechanism. 10730 CXXScopeSpec SS; 10731 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 10732 SS.MakeTrivial(S.Context, 10733 NestedNameSpecifier::Create(S.Context, nullptr, false, 10734 CanonicalT), 10735 Loc); 10736 10737 // Create the reference to operator=. 10738 ExprResult OpEqualRef 10739 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 10740 SS, /*TemplateKWLoc=*/SourceLocation(), 10741 /*FirstQualifierInScope=*/nullptr, 10742 OpLookup, 10743 /*TemplateArgs=*/nullptr, /*S*/nullptr, 10744 /*SuppressQualifierCheck=*/true); 10745 if (OpEqualRef.isInvalid()) 10746 return StmtError(); 10747 10748 // Build the call to the assignment operator. 10749 10750 Expr *FromInst = From.build(S, Loc); 10751 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 10752 OpEqualRef.getAs<Expr>(), 10753 Loc, FromInst, Loc); 10754 if (Call.isInvalid()) 10755 return StmtError(); 10756 10757 // If we built a call to a trivial 'operator=' while copying an array, 10758 // bail out. We'll replace the whole shebang with a memcpy. 10759 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 10760 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 10761 return StmtResult((Stmt*)nullptr); 10762 10763 // Convert to an expression-statement, and clean up any produced 10764 // temporaries. 10765 return S.ActOnExprStmt(Call); 10766 } 10767 10768 // - if the subobject is of scalar type, the built-in assignment 10769 // operator is used. 10770 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 10771 if (!ArrayTy) { 10772 ExprResult Assignment = S.CreateBuiltinBinOp( 10773 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 10774 if (Assignment.isInvalid()) 10775 return StmtError(); 10776 return S.ActOnExprStmt(Assignment); 10777 } 10778 10779 // - if the subobject is an array, each element is assigned, in the 10780 // manner appropriate to the element type; 10781 10782 // Construct a loop over the array bounds, e.g., 10783 // 10784 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 10785 // 10786 // that will copy each of the array elements. 10787 QualType SizeType = S.Context.getSizeType(); 10788 10789 // Create the iteration variable. 10790 IdentifierInfo *IterationVarName = nullptr; 10791 { 10792 SmallString<8> Str; 10793 llvm::raw_svector_ostream OS(Str); 10794 OS << "__i" << Depth; 10795 IterationVarName = &S.Context.Idents.get(OS.str()); 10796 } 10797 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 10798 IterationVarName, SizeType, 10799 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 10800 SC_None); 10801 10802 // Initialize the iteration variable to zero. 10803 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 10804 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 10805 10806 // Creates a reference to the iteration variable. 10807 RefBuilder IterationVarRef(IterationVar, SizeType); 10808 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 10809 10810 // Create the DeclStmt that holds the iteration variable. 10811 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 10812 10813 // Subscript the "from" and "to" expressions with the iteration variable. 10814 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 10815 MoveCastBuilder FromIndexMove(FromIndexCopy); 10816 const ExprBuilder *FromIndex; 10817 if (Copying) 10818 FromIndex = &FromIndexCopy; 10819 else 10820 FromIndex = &FromIndexMove; 10821 10822 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 10823 10824 // Build the copy/move for an individual element of the array. 10825 StmtResult Copy = 10826 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 10827 ToIndex, *FromIndex, CopyingBaseSubobject, 10828 Copying, Depth + 1); 10829 // Bail out if copying fails or if we determined that we should use memcpy. 10830 if (Copy.isInvalid() || !Copy.get()) 10831 return Copy; 10832 10833 // Create the comparison against the array bound. 10834 llvm::APInt Upper 10835 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 10836 Expr *Comparison 10837 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 10838 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 10839 BO_NE, S.Context.BoolTy, 10840 VK_RValue, OK_Ordinary, Loc, false); 10841 10842 // Create the pre-increment of the iteration variable. 10843 Expr *Increment 10844 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 10845 SizeType, VK_LValue, OK_Ordinary, Loc); 10846 10847 // Construct the loop that copies all elements of this array. 10848 return S.ActOnForStmt( 10849 Loc, Loc, InitStmt, 10850 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 10851 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 10852 } 10853 10854 static StmtResult 10855 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 10856 const ExprBuilder &To, const ExprBuilder &From, 10857 bool CopyingBaseSubobject, bool Copying) { 10858 // Maybe we should use a memcpy? 10859 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 10860 T.isTriviallyCopyableType(S.Context)) 10861 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 10862 10863 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 10864 CopyingBaseSubobject, 10865 Copying, 0)); 10866 10867 // If we ended up picking a trivial assignment operator for an array of a 10868 // non-trivially-copyable class type, just emit a memcpy. 10869 if (!Result.isInvalid() && !Result.get()) 10870 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 10871 10872 return Result; 10873 } 10874 10875 Sema::ImplicitExceptionSpecification 10876 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 10877 CXXRecordDecl *ClassDecl = MD->getParent(); 10878 10879 ImplicitExceptionSpecification ExceptSpec(*this); 10880 if (ClassDecl->isInvalidDecl()) 10881 return ExceptSpec; 10882 10883 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10884 assert(T->getNumParams() == 1 && "not a copy assignment op"); 10885 unsigned ArgQuals = 10886 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10887 10888 // C++ [except.spec]p14: 10889 // An implicitly declared special member function (Clause 12) shall have an 10890 // exception-specification. [...] 10891 10892 // It is unspecified whether or not an implicit copy assignment operator 10893 // attempts to deduplicate calls to assignment operators of virtual bases are 10894 // made. As such, this exception specification is effectively unspecified. 10895 // Based on a similar decision made for constness in C++0x, we're erring on 10896 // the side of assuming such calls to be made regardless of whether they 10897 // actually happen. 10898 for (const auto &Base : ClassDecl->bases()) { 10899 if (Base.isVirtual()) 10900 continue; 10901 10902 CXXRecordDecl *BaseClassDecl 10903 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10904 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10905 ArgQuals, false, 0)) 10906 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10907 } 10908 10909 for (const auto &Base : ClassDecl->vbases()) { 10910 CXXRecordDecl *BaseClassDecl 10911 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10912 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10913 ArgQuals, false, 0)) 10914 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10915 } 10916 10917 for (const auto *Field : ClassDecl->fields()) { 10918 QualType FieldType = Context.getBaseElementType(Field->getType()); 10919 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10920 if (CXXMethodDecl *CopyAssign = 10921 LookupCopyingAssignment(FieldClassDecl, 10922 ArgQuals | FieldType.getCVRQualifiers(), 10923 false, 0)) 10924 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 10925 } 10926 } 10927 10928 return ExceptSpec; 10929 } 10930 10931 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 10932 // Note: The following rules are largely analoguous to the copy 10933 // constructor rules. Note that virtual bases are not taken into account 10934 // for determining the argument type of the operator. Note also that 10935 // operators taking an object instead of a reference are allowed. 10936 assert(ClassDecl->needsImplicitCopyAssignment()); 10937 10938 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 10939 if (DSM.isAlreadyBeingDeclared()) 10940 return nullptr; 10941 10942 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10943 QualType RetType = Context.getLValueReferenceType(ArgType); 10944 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10945 if (Const) 10946 ArgType = ArgType.withConst(); 10947 ArgType = Context.getLValueReferenceType(ArgType); 10948 10949 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10950 CXXCopyAssignment, 10951 Const); 10952 10953 // An implicitly-declared copy assignment operator is an inline public 10954 // member of its class. 10955 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10956 SourceLocation ClassLoc = ClassDecl->getLocation(); 10957 DeclarationNameInfo NameInfo(Name, ClassLoc); 10958 CXXMethodDecl *CopyAssignment = 10959 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10960 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10961 /*isInline=*/true, Constexpr, SourceLocation()); 10962 CopyAssignment->setAccess(AS_public); 10963 CopyAssignment->setDefaulted(); 10964 CopyAssignment->setImplicit(); 10965 10966 if (getLangOpts().CUDA) { 10967 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10968 CopyAssignment, 10969 /* ConstRHS */ Const, 10970 /* Diagnose */ false); 10971 } 10972 10973 // Build an exception specification pointing back at this member. 10974 FunctionProtoType::ExtProtoInfo EPI = 10975 getImplicitMethodEPI(*this, CopyAssignment); 10976 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10977 10978 // Add the parameter to the operator. 10979 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10980 ClassLoc, ClassLoc, 10981 /*Id=*/nullptr, ArgType, 10982 /*TInfo=*/nullptr, SC_None, 10983 nullptr); 10984 CopyAssignment->setParams(FromParam); 10985 10986 CopyAssignment->setTrivial( 10987 ClassDecl->needsOverloadResolutionForCopyAssignment() 10988 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10989 : ClassDecl->hasTrivialCopyAssignment()); 10990 10991 // Note that we have added this copy-assignment operator. 10992 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10993 10994 Scope *S = getScopeForContext(ClassDecl); 10995 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 10996 10997 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10998 SetDeclDeleted(CopyAssignment, ClassLoc); 10999 11000 if (S) 11001 PushOnScopeChains(CopyAssignment, S, false); 11002 ClassDecl->addDecl(CopyAssignment); 11003 11004 return CopyAssignment; 11005 } 11006 11007 /// Diagnose an implicit copy operation for a class which is odr-used, but 11008 /// which is deprecated because the class has a user-declared copy constructor, 11009 /// copy assignment operator, or destructor. 11010 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 11011 SourceLocation UseLoc) { 11012 assert(CopyOp->isImplicit()); 11013 11014 CXXRecordDecl *RD = CopyOp->getParent(); 11015 CXXMethodDecl *UserDeclaredOperation = nullptr; 11016 11017 // In Microsoft mode, assignment operations don't affect constructors and 11018 // vice versa. 11019 if (RD->hasUserDeclaredDestructor()) { 11020 UserDeclaredOperation = RD->getDestructor(); 11021 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11022 RD->hasUserDeclaredCopyConstructor() && 11023 !S.getLangOpts().MSVCCompat) { 11024 // Find any user-declared copy constructor. 11025 for (auto *I : RD->ctors()) { 11026 if (I->isCopyConstructor()) { 11027 UserDeclaredOperation = I; 11028 break; 11029 } 11030 } 11031 assert(UserDeclaredOperation); 11032 } else if (isa<CXXConstructorDecl>(CopyOp) && 11033 RD->hasUserDeclaredCopyAssignment() && 11034 !S.getLangOpts().MSVCCompat) { 11035 // Find any user-declared move assignment operator. 11036 for (auto *I : RD->methods()) { 11037 if (I->isCopyAssignmentOperator()) { 11038 UserDeclaredOperation = I; 11039 break; 11040 } 11041 } 11042 assert(UserDeclaredOperation); 11043 } 11044 11045 if (UserDeclaredOperation) { 11046 S.Diag(UserDeclaredOperation->getLocation(), 11047 diag::warn_deprecated_copy_operation) 11048 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11049 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11050 S.Diag(UseLoc, diag::note_member_synthesized_at) 11051 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 11052 : Sema::CXXCopyAssignment) 11053 << RD; 11054 } 11055 } 11056 11057 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11058 CXXMethodDecl *CopyAssignOperator) { 11059 assert((CopyAssignOperator->isDefaulted() && 11060 CopyAssignOperator->isOverloadedOperator() && 11061 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11062 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11063 !CopyAssignOperator->isDeleted()) && 11064 "DefineImplicitCopyAssignment called for wrong function"); 11065 11066 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11067 11068 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 11069 CopyAssignOperator->setInvalidDecl(); 11070 return; 11071 } 11072 11073 // C++11 [class.copy]p18: 11074 // The [definition of an implicitly declared copy assignment operator] is 11075 // deprecated if the class has a user-declared copy constructor or a 11076 // user-declared destructor. 11077 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11078 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 11079 11080 CopyAssignOperator->markUsed(Context); 11081 11082 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11083 DiagnosticErrorTrap Trap(Diags); 11084 11085 // C++0x [class.copy]p30: 11086 // The implicitly-defined or explicitly-defaulted copy assignment operator 11087 // for a non-union class X performs memberwise copy assignment of its 11088 // subobjects. The direct base classes of X are assigned first, in the 11089 // order of their declaration in the base-specifier-list, and then the 11090 // immediate non-static data members of X are assigned, in the order in 11091 // which they were declared in the class definition. 11092 11093 // The statements that form the synthesized function body. 11094 SmallVector<Stmt*, 8> Statements; 11095 11096 // The parameter for the "other" object, which we are copying from. 11097 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11098 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11099 QualType OtherRefType = Other->getType(); 11100 if (const LValueReferenceType *OtherRef 11101 = OtherRefType->getAs<LValueReferenceType>()) { 11102 OtherRefType = OtherRef->getPointeeType(); 11103 OtherQuals = OtherRefType.getQualifiers(); 11104 } 11105 11106 // Our location for everything implicitly-generated. 11107 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11108 ? CopyAssignOperator->getLocEnd() 11109 : CopyAssignOperator->getLocation(); 11110 11111 // Builds a DeclRefExpr for the "other" object. 11112 RefBuilder OtherRef(Other, OtherRefType); 11113 11114 // Builds the "this" pointer. 11115 ThisBuilder This; 11116 11117 // Assign base classes. 11118 bool Invalid = false; 11119 for (auto &Base : ClassDecl->bases()) { 11120 // Form the assignment: 11121 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11122 QualType BaseType = Base.getType().getUnqualifiedType(); 11123 if (!BaseType->isRecordType()) { 11124 Invalid = true; 11125 continue; 11126 } 11127 11128 CXXCastPath BasePath; 11129 BasePath.push_back(&Base); 11130 11131 // Construct the "from" expression, which is an implicit cast to the 11132 // appropriately-qualified base type. 11133 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11134 VK_LValue, BasePath); 11135 11136 // Dereference "this". 11137 DerefBuilder DerefThis(This); 11138 CastBuilder To(DerefThis, 11139 Context.getCVRQualifiedType( 11140 BaseType, CopyAssignOperator->getTypeQualifiers()), 11141 VK_LValue, BasePath); 11142 11143 // Build the copy. 11144 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11145 To, From, 11146 /*CopyingBaseSubobject=*/true, 11147 /*Copying=*/true); 11148 if (Copy.isInvalid()) { 11149 Diag(CurrentLocation, diag::note_member_synthesized_at) 11150 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11151 CopyAssignOperator->setInvalidDecl(); 11152 return; 11153 } 11154 11155 // Success! Record the copy. 11156 Statements.push_back(Copy.getAs<Expr>()); 11157 } 11158 11159 // Assign non-static members. 11160 for (auto *Field : ClassDecl->fields()) { 11161 // FIXME: We should form some kind of AST representation for the implied 11162 // memcpy in a union copy operation. 11163 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11164 continue; 11165 11166 if (Field->isInvalidDecl()) { 11167 Invalid = true; 11168 continue; 11169 } 11170 11171 // Check for members of reference type; we can't copy those. 11172 if (Field->getType()->isReferenceType()) { 11173 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11174 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11175 Diag(Field->getLocation(), diag::note_declared_at); 11176 Diag(CurrentLocation, diag::note_member_synthesized_at) 11177 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11178 Invalid = true; 11179 continue; 11180 } 11181 11182 // Check for members of const-qualified, non-class type. 11183 QualType BaseType = Context.getBaseElementType(Field->getType()); 11184 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11185 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11186 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11187 Diag(Field->getLocation(), diag::note_declared_at); 11188 Diag(CurrentLocation, diag::note_member_synthesized_at) 11189 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11190 Invalid = true; 11191 continue; 11192 } 11193 11194 // Suppress assigning zero-width bitfields. 11195 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11196 continue; 11197 11198 QualType FieldType = Field->getType().getNonReferenceType(); 11199 if (FieldType->isIncompleteArrayType()) { 11200 assert(ClassDecl->hasFlexibleArrayMember() && 11201 "Incomplete array type is not valid"); 11202 continue; 11203 } 11204 11205 // Build references to the field in the object we're copying from and to. 11206 CXXScopeSpec SS; // Intentionally empty 11207 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11208 LookupMemberName); 11209 MemberLookup.addDecl(Field); 11210 MemberLookup.resolveKind(); 11211 11212 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11213 11214 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11215 11216 // Build the copy of this field. 11217 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11218 To, From, 11219 /*CopyingBaseSubobject=*/false, 11220 /*Copying=*/true); 11221 if (Copy.isInvalid()) { 11222 Diag(CurrentLocation, diag::note_member_synthesized_at) 11223 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11224 CopyAssignOperator->setInvalidDecl(); 11225 return; 11226 } 11227 11228 // Success! Record the copy. 11229 Statements.push_back(Copy.getAs<Stmt>()); 11230 } 11231 11232 if (!Invalid) { 11233 // Add a "return *this;" 11234 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11235 11236 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11237 if (Return.isInvalid()) 11238 Invalid = true; 11239 else { 11240 Statements.push_back(Return.getAs<Stmt>()); 11241 11242 if (Trap.hasErrorOccurred()) { 11243 Diag(CurrentLocation, diag::note_member_synthesized_at) 11244 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11245 Invalid = true; 11246 } 11247 } 11248 } 11249 11250 // The exception specification is needed because we are defining the 11251 // function. 11252 ResolveExceptionSpec(CurrentLocation, 11253 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11254 11255 if (Invalid) { 11256 CopyAssignOperator->setInvalidDecl(); 11257 return; 11258 } 11259 11260 StmtResult Body; 11261 { 11262 CompoundScopeRAII CompoundScope(*this); 11263 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11264 /*isStmtExpr=*/false); 11265 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11266 } 11267 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11268 11269 if (ASTMutationListener *L = getASTMutationListener()) { 11270 L->CompletedImplicitDefinition(CopyAssignOperator); 11271 } 11272 } 11273 11274 Sema::ImplicitExceptionSpecification 11275 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 11276 CXXRecordDecl *ClassDecl = MD->getParent(); 11277 11278 ImplicitExceptionSpecification ExceptSpec(*this); 11279 if (ClassDecl->isInvalidDecl()) 11280 return ExceptSpec; 11281 11282 // C++0x [except.spec]p14: 11283 // An implicitly declared special member function (Clause 12) shall have an 11284 // exception-specification. [...] 11285 11286 // It is unspecified whether or not an implicit move assignment operator 11287 // attempts to deduplicate calls to assignment operators of virtual bases are 11288 // made. As such, this exception specification is effectively unspecified. 11289 // Based on a similar decision made for constness in C++0x, we're erring on 11290 // the side of assuming such calls to be made regardless of whether they 11291 // actually happen. 11292 // Note that a move constructor is not implicitly declared when there are 11293 // virtual bases, but it can still be user-declared and explicitly defaulted. 11294 for (const auto &Base : ClassDecl->bases()) { 11295 if (Base.isVirtual()) 11296 continue; 11297 11298 CXXRecordDecl *BaseClassDecl 11299 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11300 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 11301 0, false, 0)) 11302 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 11303 } 11304 11305 for (const auto &Base : ClassDecl->vbases()) { 11306 CXXRecordDecl *BaseClassDecl 11307 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11308 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 11309 0, false, 0)) 11310 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 11311 } 11312 11313 for (const auto *Field : ClassDecl->fields()) { 11314 QualType FieldType = Context.getBaseElementType(Field->getType()); 11315 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 11316 if (CXXMethodDecl *MoveAssign = 11317 LookupMovingAssignment(FieldClassDecl, 11318 FieldType.getCVRQualifiers(), 11319 false, 0)) 11320 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 11321 } 11322 } 11323 11324 return ExceptSpec; 11325 } 11326 11327 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11328 assert(ClassDecl->needsImplicitMoveAssignment()); 11329 11330 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11331 if (DSM.isAlreadyBeingDeclared()) 11332 return nullptr; 11333 11334 // Note: The following rules are largely analoguous to the move 11335 // constructor rules. 11336 11337 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11338 QualType RetType = Context.getLValueReferenceType(ArgType); 11339 ArgType = Context.getRValueReferenceType(ArgType); 11340 11341 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11342 CXXMoveAssignment, 11343 false); 11344 11345 // An implicitly-declared move assignment operator is an inline public 11346 // member of its class. 11347 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11348 SourceLocation ClassLoc = ClassDecl->getLocation(); 11349 DeclarationNameInfo NameInfo(Name, ClassLoc); 11350 CXXMethodDecl *MoveAssignment = 11351 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11352 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11353 /*isInline=*/true, Constexpr, SourceLocation()); 11354 MoveAssignment->setAccess(AS_public); 11355 MoveAssignment->setDefaulted(); 11356 MoveAssignment->setImplicit(); 11357 11358 if (getLangOpts().CUDA) { 11359 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11360 MoveAssignment, 11361 /* ConstRHS */ false, 11362 /* Diagnose */ false); 11363 } 11364 11365 // Build an exception specification pointing back at this member. 11366 FunctionProtoType::ExtProtoInfo EPI = 11367 getImplicitMethodEPI(*this, MoveAssignment); 11368 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11369 11370 // Add the parameter to the operator. 11371 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11372 ClassLoc, ClassLoc, 11373 /*Id=*/nullptr, ArgType, 11374 /*TInfo=*/nullptr, SC_None, 11375 nullptr); 11376 MoveAssignment->setParams(FromParam); 11377 11378 MoveAssignment->setTrivial( 11379 ClassDecl->needsOverloadResolutionForMoveAssignment() 11380 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11381 : ClassDecl->hasTrivialMoveAssignment()); 11382 11383 // Note that we have added this copy-assignment operator. 11384 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11385 11386 Scope *S = getScopeForContext(ClassDecl); 11387 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11388 11389 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11390 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11391 SetDeclDeleted(MoveAssignment, ClassLoc); 11392 } 11393 11394 if (S) 11395 PushOnScopeChains(MoveAssignment, S, false); 11396 ClassDecl->addDecl(MoveAssignment); 11397 11398 return MoveAssignment; 11399 } 11400 11401 /// Check if we're implicitly defining a move assignment operator for a class 11402 /// with virtual bases. Such a move assignment might move-assign the virtual 11403 /// base multiple times. 11404 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11405 SourceLocation CurrentLocation) { 11406 assert(!Class->isDependentContext() && "should not define dependent move"); 11407 11408 // Only a virtual base could get implicitly move-assigned multiple times. 11409 // Only a non-trivial move assignment can observe this. We only want to 11410 // diagnose if we implicitly define an assignment operator that assigns 11411 // two base classes, both of which move-assign the same virtual base. 11412 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11413 Class->getNumBases() < 2) 11414 return; 11415 11416 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11417 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11418 VBaseMap VBases; 11419 11420 for (auto &BI : Class->bases()) { 11421 Worklist.push_back(&BI); 11422 while (!Worklist.empty()) { 11423 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11424 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11425 11426 // If the base has no non-trivial move assignment operators, 11427 // we don't care about moves from it. 11428 if (!Base->hasNonTrivialMoveAssignment()) 11429 continue; 11430 11431 // If there's nothing virtual here, skip it. 11432 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11433 continue; 11434 11435 // If we're not actually going to call a move assignment for this base, 11436 // or the selected move assignment is trivial, skip it. 11437 Sema::SpecialMemberOverloadResult *SMOR = 11438 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11439 /*ConstArg*/false, /*VolatileArg*/false, 11440 /*RValueThis*/true, /*ConstThis*/false, 11441 /*VolatileThis*/false); 11442 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 11443 !SMOR->getMethod()->isMoveAssignmentOperator()) 11444 continue; 11445 11446 if (BaseSpec->isVirtual()) { 11447 // We're going to move-assign this virtual base, and its move 11448 // assignment operator is not trivial. If this can happen for 11449 // multiple distinct direct bases of Class, diagnose it. (If it 11450 // only happens in one base, we'll diagnose it when synthesizing 11451 // that base class's move assignment operator.) 11452 CXXBaseSpecifier *&Existing = 11453 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11454 .first->second; 11455 if (Existing && Existing != &BI) { 11456 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11457 << Class << Base; 11458 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11459 << (Base->getCanonicalDecl() == 11460 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11461 << Base << Existing->getType() << Existing->getSourceRange(); 11462 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11463 << (Base->getCanonicalDecl() == 11464 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11465 << Base << BI.getType() << BaseSpec->getSourceRange(); 11466 11467 // Only diagnose each vbase once. 11468 Existing = nullptr; 11469 } 11470 } else { 11471 // Only walk over bases that have defaulted move assignment operators. 11472 // We assume that any user-provided move assignment operator handles 11473 // the multiple-moves-of-vbase case itself somehow. 11474 if (!SMOR->getMethod()->isDefaulted()) 11475 continue; 11476 11477 // We're going to move the base classes of Base. Add them to the list. 11478 for (auto &BI : Base->bases()) 11479 Worklist.push_back(&BI); 11480 } 11481 } 11482 } 11483 } 11484 11485 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11486 CXXMethodDecl *MoveAssignOperator) { 11487 assert((MoveAssignOperator->isDefaulted() && 11488 MoveAssignOperator->isOverloadedOperator() && 11489 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11490 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11491 !MoveAssignOperator->isDeleted()) && 11492 "DefineImplicitMoveAssignment called for wrong function"); 11493 11494 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11495 11496 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 11497 MoveAssignOperator->setInvalidDecl(); 11498 return; 11499 } 11500 11501 MoveAssignOperator->markUsed(Context); 11502 11503 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11504 DiagnosticErrorTrap Trap(Diags); 11505 11506 // C++0x [class.copy]p28: 11507 // The implicitly-defined or move assignment operator for a non-union class 11508 // X performs memberwise move assignment of its subobjects. The direct base 11509 // classes of X are assigned first, in the order of their declaration in the 11510 // base-specifier-list, and then the immediate non-static data members of X 11511 // are assigned, in the order in which they were declared in the class 11512 // definition. 11513 11514 // Issue a warning if our implicit move assignment operator will move 11515 // from a virtual base more than once. 11516 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11517 11518 // The statements that form the synthesized function body. 11519 SmallVector<Stmt*, 8> Statements; 11520 11521 // The parameter for the "other" object, which we are move from. 11522 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11523 QualType OtherRefType = Other->getType()-> 11524 getAs<RValueReferenceType>()->getPointeeType(); 11525 assert(!OtherRefType.getQualifiers() && 11526 "Bad argument type of defaulted move assignment"); 11527 11528 // Our location for everything implicitly-generated. 11529 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11530 ? MoveAssignOperator->getLocEnd() 11531 : MoveAssignOperator->getLocation(); 11532 11533 // Builds a reference to the "other" object. 11534 RefBuilder OtherRef(Other, OtherRefType); 11535 // Cast to rvalue. 11536 MoveCastBuilder MoveOther(OtherRef); 11537 11538 // Builds the "this" pointer. 11539 ThisBuilder This; 11540 11541 // Assign base classes. 11542 bool Invalid = false; 11543 for (auto &Base : ClassDecl->bases()) { 11544 // C++11 [class.copy]p28: 11545 // It is unspecified whether subobjects representing virtual base classes 11546 // are assigned more than once by the implicitly-defined copy assignment 11547 // operator. 11548 // FIXME: Do not assign to a vbase that will be assigned by some other base 11549 // class. For a move-assignment, this can result in the vbase being moved 11550 // multiple times. 11551 11552 // Form the assignment: 11553 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11554 QualType BaseType = Base.getType().getUnqualifiedType(); 11555 if (!BaseType->isRecordType()) { 11556 Invalid = true; 11557 continue; 11558 } 11559 11560 CXXCastPath BasePath; 11561 BasePath.push_back(&Base); 11562 11563 // Construct the "from" expression, which is an implicit cast to the 11564 // appropriately-qualified base type. 11565 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11566 11567 // Dereference "this". 11568 DerefBuilder DerefThis(This); 11569 11570 // Implicitly cast "this" to the appropriately-qualified base type. 11571 CastBuilder To(DerefThis, 11572 Context.getCVRQualifiedType( 11573 BaseType, MoveAssignOperator->getTypeQualifiers()), 11574 VK_LValue, BasePath); 11575 11576 // Build the move. 11577 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11578 To, From, 11579 /*CopyingBaseSubobject=*/true, 11580 /*Copying=*/false); 11581 if (Move.isInvalid()) { 11582 Diag(CurrentLocation, diag::note_member_synthesized_at) 11583 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11584 MoveAssignOperator->setInvalidDecl(); 11585 return; 11586 } 11587 11588 // Success! Record the move. 11589 Statements.push_back(Move.getAs<Expr>()); 11590 } 11591 11592 // Assign non-static members. 11593 for (auto *Field : ClassDecl->fields()) { 11594 // FIXME: We should form some kind of AST representation for the implied 11595 // memcpy in a union copy operation. 11596 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11597 continue; 11598 11599 if (Field->isInvalidDecl()) { 11600 Invalid = true; 11601 continue; 11602 } 11603 11604 // Check for members of reference type; we can't move those. 11605 if (Field->getType()->isReferenceType()) { 11606 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11607 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11608 Diag(Field->getLocation(), diag::note_declared_at); 11609 Diag(CurrentLocation, diag::note_member_synthesized_at) 11610 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11611 Invalid = true; 11612 continue; 11613 } 11614 11615 // Check for members of const-qualified, non-class type. 11616 QualType BaseType = Context.getBaseElementType(Field->getType()); 11617 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11618 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11619 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11620 Diag(Field->getLocation(), diag::note_declared_at); 11621 Diag(CurrentLocation, diag::note_member_synthesized_at) 11622 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11623 Invalid = true; 11624 continue; 11625 } 11626 11627 // Suppress assigning zero-width bitfields. 11628 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11629 continue; 11630 11631 QualType FieldType = Field->getType().getNonReferenceType(); 11632 if (FieldType->isIncompleteArrayType()) { 11633 assert(ClassDecl->hasFlexibleArrayMember() && 11634 "Incomplete array type is not valid"); 11635 continue; 11636 } 11637 11638 // Build references to the field in the object we're copying from and to. 11639 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11640 LookupMemberName); 11641 MemberLookup.addDecl(Field); 11642 MemberLookup.resolveKind(); 11643 MemberBuilder From(MoveOther, OtherRefType, 11644 /*IsArrow=*/false, MemberLookup); 11645 MemberBuilder To(This, getCurrentThisType(), 11646 /*IsArrow=*/true, MemberLookup); 11647 11648 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 11649 "Member reference with rvalue base must be rvalue except for reference " 11650 "members, which aren't allowed for move assignment."); 11651 11652 // Build the move of this field. 11653 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 11654 To, From, 11655 /*CopyingBaseSubobject=*/false, 11656 /*Copying=*/false); 11657 if (Move.isInvalid()) { 11658 Diag(CurrentLocation, diag::note_member_synthesized_at) 11659 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11660 MoveAssignOperator->setInvalidDecl(); 11661 return; 11662 } 11663 11664 // Success! Record the copy. 11665 Statements.push_back(Move.getAs<Stmt>()); 11666 } 11667 11668 if (!Invalid) { 11669 // Add a "return *this;" 11670 ExprResult ThisObj = 11671 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11672 11673 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11674 if (Return.isInvalid()) 11675 Invalid = true; 11676 else { 11677 Statements.push_back(Return.getAs<Stmt>()); 11678 11679 if (Trap.hasErrorOccurred()) { 11680 Diag(CurrentLocation, diag::note_member_synthesized_at) 11681 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11682 Invalid = true; 11683 } 11684 } 11685 } 11686 11687 // The exception specification is needed because we are defining the 11688 // function. 11689 ResolveExceptionSpec(CurrentLocation, 11690 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11691 11692 if (Invalid) { 11693 MoveAssignOperator->setInvalidDecl(); 11694 return; 11695 } 11696 11697 StmtResult Body; 11698 { 11699 CompoundScopeRAII CompoundScope(*this); 11700 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11701 /*isStmtExpr=*/false); 11702 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11703 } 11704 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 11705 11706 if (ASTMutationListener *L = getASTMutationListener()) { 11707 L->CompletedImplicitDefinition(MoveAssignOperator); 11708 } 11709 } 11710 11711 Sema::ImplicitExceptionSpecification 11712 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 11713 CXXRecordDecl *ClassDecl = MD->getParent(); 11714 11715 ImplicitExceptionSpecification ExceptSpec(*this); 11716 if (ClassDecl->isInvalidDecl()) 11717 return ExceptSpec; 11718 11719 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 11720 assert(T->getNumParams() >= 1 && "not a copy ctor"); 11721 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 11722 11723 // C++ [except.spec]p14: 11724 // An implicitly declared special member function (Clause 12) shall have an 11725 // exception-specification. [...] 11726 for (const auto &Base : ClassDecl->bases()) { 11727 // Virtual bases are handled below. 11728 if (Base.isVirtual()) 11729 continue; 11730 11731 CXXRecordDecl *BaseClassDecl 11732 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11733 if (CXXConstructorDecl *CopyConstructor = 11734 LookupCopyingConstructor(BaseClassDecl, Quals)) 11735 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 11736 } 11737 for (const auto &Base : ClassDecl->vbases()) { 11738 CXXRecordDecl *BaseClassDecl 11739 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11740 if (CXXConstructorDecl *CopyConstructor = 11741 LookupCopyingConstructor(BaseClassDecl, Quals)) 11742 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 11743 } 11744 for (const auto *Field : ClassDecl->fields()) { 11745 QualType FieldType = Context.getBaseElementType(Field->getType()); 11746 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 11747 if (CXXConstructorDecl *CopyConstructor = 11748 LookupCopyingConstructor(FieldClassDecl, 11749 Quals | FieldType.getCVRQualifiers())) 11750 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 11751 } 11752 } 11753 11754 return ExceptSpec; 11755 } 11756 11757 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 11758 CXXRecordDecl *ClassDecl) { 11759 // C++ [class.copy]p4: 11760 // If the class definition does not explicitly declare a copy 11761 // constructor, one is declared implicitly. 11762 assert(ClassDecl->needsImplicitCopyConstructor()); 11763 11764 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 11765 if (DSM.isAlreadyBeingDeclared()) 11766 return nullptr; 11767 11768 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11769 QualType ArgType = ClassType; 11770 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 11771 if (Const) 11772 ArgType = ArgType.withConst(); 11773 ArgType = Context.getLValueReferenceType(ArgType); 11774 11775 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11776 CXXCopyConstructor, 11777 Const); 11778 11779 DeclarationName Name 11780 = Context.DeclarationNames.getCXXConstructorName( 11781 Context.getCanonicalType(ClassType)); 11782 SourceLocation ClassLoc = ClassDecl->getLocation(); 11783 DeclarationNameInfo NameInfo(Name, ClassLoc); 11784 11785 // An implicitly-declared copy constructor is an inline public 11786 // member of its class. 11787 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 11788 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11789 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11790 Constexpr); 11791 CopyConstructor->setAccess(AS_public); 11792 CopyConstructor->setDefaulted(); 11793 11794 if (getLangOpts().CUDA) { 11795 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 11796 CopyConstructor, 11797 /* ConstRHS */ Const, 11798 /* Diagnose */ false); 11799 } 11800 11801 // Build an exception specification pointing back at this member. 11802 FunctionProtoType::ExtProtoInfo EPI = 11803 getImplicitMethodEPI(*this, CopyConstructor); 11804 CopyConstructor->setType( 11805 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11806 11807 // Add the parameter to the constructor. 11808 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 11809 ClassLoc, ClassLoc, 11810 /*IdentifierInfo=*/nullptr, 11811 ArgType, /*TInfo=*/nullptr, 11812 SC_None, nullptr); 11813 CopyConstructor->setParams(FromParam); 11814 11815 CopyConstructor->setTrivial( 11816 ClassDecl->needsOverloadResolutionForCopyConstructor() 11817 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 11818 : ClassDecl->hasTrivialCopyConstructor()); 11819 11820 // Note that we have declared this constructor. 11821 ++ASTContext::NumImplicitCopyConstructorsDeclared; 11822 11823 Scope *S = getScopeForContext(ClassDecl); 11824 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 11825 11826 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 11827 SetDeclDeleted(CopyConstructor, ClassLoc); 11828 11829 if (S) 11830 PushOnScopeChains(CopyConstructor, S, false); 11831 ClassDecl->addDecl(CopyConstructor); 11832 11833 return CopyConstructor; 11834 } 11835 11836 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 11837 CXXConstructorDecl *CopyConstructor) { 11838 assert((CopyConstructor->isDefaulted() && 11839 CopyConstructor->isCopyConstructor() && 11840 !CopyConstructor->doesThisDeclarationHaveABody() && 11841 !CopyConstructor->isDeleted()) && 11842 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 11843 11844 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 11845 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 11846 11847 // C++11 [class.copy]p7: 11848 // The [definition of an implicitly declared copy constructor] is 11849 // deprecated if the class has a user-declared copy assignment operator 11850 // or a user-declared destructor. 11851 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 11852 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 11853 11854 SynthesizedFunctionScope Scope(*this, CopyConstructor); 11855 DiagnosticErrorTrap Trap(Diags); 11856 11857 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 11858 Trap.hasErrorOccurred()) { 11859 Diag(CurrentLocation, diag::note_member_synthesized_at) 11860 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 11861 CopyConstructor->setInvalidDecl(); 11862 } else { 11863 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 11864 ? CopyConstructor->getLocEnd() 11865 : CopyConstructor->getLocation(); 11866 Sema::CompoundScopeRAII CompoundScope(*this); 11867 CopyConstructor->setBody( 11868 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 11869 } 11870 11871 // The exception specification is needed because we are defining the 11872 // function. 11873 ResolveExceptionSpec(CurrentLocation, 11874 CopyConstructor->getType()->castAs<FunctionProtoType>()); 11875 11876 CopyConstructor->markUsed(Context); 11877 MarkVTableUsed(CurrentLocation, ClassDecl); 11878 11879 if (ASTMutationListener *L = getASTMutationListener()) { 11880 L->CompletedImplicitDefinition(CopyConstructor); 11881 } 11882 } 11883 11884 Sema::ImplicitExceptionSpecification 11885 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 11886 CXXRecordDecl *ClassDecl = MD->getParent(); 11887 11888 // C++ [except.spec]p14: 11889 // An implicitly declared special member function (Clause 12) shall have an 11890 // exception-specification. [...] 11891 ImplicitExceptionSpecification ExceptSpec(*this); 11892 if (ClassDecl->isInvalidDecl()) 11893 return ExceptSpec; 11894 11895 // Direct base-class constructors. 11896 for (const auto &B : ClassDecl->bases()) { 11897 if (B.isVirtual()) // Handled below. 11898 continue; 11899 11900 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11901 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11902 CXXConstructorDecl *Constructor = 11903 LookupMovingConstructor(BaseClassDecl, 0); 11904 // If this is a deleted function, add it anyway. This might be conformant 11905 // with the standard. This might not. I'm not sure. It might not matter. 11906 if (Constructor) 11907 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11908 } 11909 } 11910 11911 // Virtual base-class constructors. 11912 for (const auto &B : ClassDecl->vbases()) { 11913 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11914 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11915 CXXConstructorDecl *Constructor = 11916 LookupMovingConstructor(BaseClassDecl, 0); 11917 // If this is a deleted function, add it anyway. This might be conformant 11918 // with the standard. This might not. I'm not sure. It might not matter. 11919 if (Constructor) 11920 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11921 } 11922 } 11923 11924 // Field constructors. 11925 for (const auto *F : ClassDecl->fields()) { 11926 QualType FieldType = Context.getBaseElementType(F->getType()); 11927 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 11928 CXXConstructorDecl *Constructor = 11929 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 11930 // If this is a deleted function, add it anyway. This might be conformant 11931 // with the standard. This might not. I'm not sure. It might not matter. 11932 // In particular, the problem is that this function never gets called. It 11933 // might just be ill-formed because this function attempts to refer to 11934 // a deleted function here. 11935 if (Constructor) 11936 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 11937 } 11938 } 11939 11940 return ExceptSpec; 11941 } 11942 11943 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 11944 CXXRecordDecl *ClassDecl) { 11945 assert(ClassDecl->needsImplicitMoveConstructor()); 11946 11947 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11948 if (DSM.isAlreadyBeingDeclared()) 11949 return nullptr; 11950 11951 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11952 QualType ArgType = Context.getRValueReferenceType(ClassType); 11953 11954 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11955 CXXMoveConstructor, 11956 false); 11957 11958 DeclarationName Name 11959 = Context.DeclarationNames.getCXXConstructorName( 11960 Context.getCanonicalType(ClassType)); 11961 SourceLocation ClassLoc = ClassDecl->getLocation(); 11962 DeclarationNameInfo NameInfo(Name, ClassLoc); 11963 11964 // C++11 [class.copy]p11: 11965 // An implicitly-declared copy/move constructor is an inline public 11966 // member of its class. 11967 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11968 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11969 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11970 Constexpr); 11971 MoveConstructor->setAccess(AS_public); 11972 MoveConstructor->setDefaulted(); 11973 11974 if (getLangOpts().CUDA) { 11975 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11976 MoveConstructor, 11977 /* ConstRHS */ false, 11978 /* Diagnose */ false); 11979 } 11980 11981 // Build an exception specification pointing back at this member. 11982 FunctionProtoType::ExtProtoInfo EPI = 11983 getImplicitMethodEPI(*this, MoveConstructor); 11984 MoveConstructor->setType( 11985 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11986 11987 // Add the parameter to the constructor. 11988 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11989 ClassLoc, ClassLoc, 11990 /*IdentifierInfo=*/nullptr, 11991 ArgType, /*TInfo=*/nullptr, 11992 SC_None, nullptr); 11993 MoveConstructor->setParams(FromParam); 11994 11995 MoveConstructor->setTrivial( 11996 ClassDecl->needsOverloadResolutionForMoveConstructor() 11997 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11998 : ClassDecl->hasTrivialMoveConstructor()); 11999 12000 // Note that we have declared this constructor. 12001 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12002 12003 Scope *S = getScopeForContext(ClassDecl); 12004 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12005 12006 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12007 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12008 SetDeclDeleted(MoveConstructor, ClassLoc); 12009 } 12010 12011 if (S) 12012 PushOnScopeChains(MoveConstructor, S, false); 12013 ClassDecl->addDecl(MoveConstructor); 12014 12015 return MoveConstructor; 12016 } 12017 12018 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12019 CXXConstructorDecl *MoveConstructor) { 12020 assert((MoveConstructor->isDefaulted() && 12021 MoveConstructor->isMoveConstructor() && 12022 !MoveConstructor->doesThisDeclarationHaveABody() && 12023 !MoveConstructor->isDeleted()) && 12024 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12025 12026 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12027 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12028 12029 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12030 DiagnosticErrorTrap Trap(Diags); 12031 12032 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 12033 Trap.hasErrorOccurred()) { 12034 Diag(CurrentLocation, diag::note_member_synthesized_at) 12035 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 12036 MoveConstructor->setInvalidDecl(); 12037 } else { 12038 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12039 ? MoveConstructor->getLocEnd() 12040 : MoveConstructor->getLocation(); 12041 Sema::CompoundScopeRAII CompoundScope(*this); 12042 MoveConstructor->setBody(ActOnCompoundStmt( 12043 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12044 } 12045 12046 // The exception specification is needed because we are defining the 12047 // function. 12048 ResolveExceptionSpec(CurrentLocation, 12049 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12050 12051 MoveConstructor->markUsed(Context); 12052 MarkVTableUsed(CurrentLocation, ClassDecl); 12053 12054 if (ASTMutationListener *L = getASTMutationListener()) { 12055 L->CompletedImplicitDefinition(MoveConstructor); 12056 } 12057 } 12058 12059 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12060 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12061 } 12062 12063 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12064 SourceLocation CurrentLocation, 12065 CXXConversionDecl *Conv) { 12066 CXXRecordDecl *Lambda = Conv->getParent(); 12067 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 12068 // If we are defining a specialization of a conversion to function-ptr 12069 // cache the deduced template arguments for this specialization 12070 // so that we can use them to retrieve the corresponding call-operator 12071 // and static-invoker. 12072 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 12073 12074 // Retrieve the corresponding call-operator specialization. 12075 if (Lambda->isGenericLambda()) { 12076 assert(Conv->isFunctionTemplateSpecialization()); 12077 FunctionTemplateDecl *CallOpTemplate = 12078 CallOp->getDescribedFunctionTemplate(); 12079 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 12080 void *InsertPos = nullptr; 12081 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 12082 DeducedTemplateArgs->asArray(), 12083 InsertPos); 12084 assert(CallOpSpec && 12085 "Conversion operator must have a corresponding call operator"); 12086 CallOp = cast<CXXMethodDecl>(CallOpSpec); 12087 } 12088 // Mark the call operator referenced (and add to pending instantiations 12089 // if necessary). 12090 // For both the conversion and static-invoker template specializations 12091 // we construct their body's in this function, so no need to add them 12092 // to the PendingInstantiations. 12093 MarkFunctionReferenced(CurrentLocation, CallOp); 12094 12095 SynthesizedFunctionScope Scope(*this, Conv); 12096 DiagnosticErrorTrap Trap(Diags); 12097 12098 // Retrieve the static invoker... 12099 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12100 // ... and get the corresponding specialization for a generic lambda. 12101 if (Lambda->isGenericLambda()) { 12102 assert(DeducedTemplateArgs && 12103 "Must have deduced template arguments from Conversion Operator"); 12104 FunctionTemplateDecl *InvokeTemplate = 12105 Invoker->getDescribedFunctionTemplate(); 12106 void *InsertPos = nullptr; 12107 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 12108 DeducedTemplateArgs->asArray(), 12109 InsertPos); 12110 assert(InvokeSpec && 12111 "Must have a corresponding static invoker specialization"); 12112 Invoker = cast<CXXMethodDecl>(InvokeSpec); 12113 } 12114 // Construct the body of the conversion function { return __invoke; }. 12115 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12116 VK_LValue, Conv->getLocation()).get(); 12117 assert(FunctionRef && "Can't refer to __invoke function?"); 12118 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12119 Conv->setBody(new (Context) CompoundStmt(Context, Return, 12120 Conv->getLocation(), 12121 Conv->getLocation())); 12122 12123 Conv->markUsed(Context); 12124 Conv->setReferenced(); 12125 12126 // Fill in the __invoke function with a dummy implementation. IR generation 12127 // will fill in the actual details. 12128 Invoker->markUsed(Context); 12129 Invoker->setReferenced(); 12130 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12131 12132 if (ASTMutationListener *L = getASTMutationListener()) { 12133 L->CompletedImplicitDefinition(Conv); 12134 L->CompletedImplicitDefinition(Invoker); 12135 } 12136 } 12137 12138 12139 12140 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12141 SourceLocation CurrentLocation, 12142 CXXConversionDecl *Conv) 12143 { 12144 assert(!Conv->getParent()->isGenericLambda()); 12145 12146 Conv->markUsed(Context); 12147 12148 SynthesizedFunctionScope Scope(*this, Conv); 12149 DiagnosticErrorTrap Trap(Diags); 12150 12151 // Copy-initialize the lambda object as needed to capture it. 12152 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12153 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12154 12155 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12156 Conv->getLocation(), 12157 Conv, DerefThis); 12158 12159 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12160 // behavior. Note that only the general conversion function does this 12161 // (since it's unusable otherwise); in the case where we inline the 12162 // block literal, it has block literal lifetime semantics. 12163 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12164 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12165 CK_CopyAndAutoreleaseBlockObject, 12166 BuildBlock.get(), nullptr, VK_RValue); 12167 12168 if (BuildBlock.isInvalid()) { 12169 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12170 Conv->setInvalidDecl(); 12171 return; 12172 } 12173 12174 // Create the return statement that returns the block from the conversion 12175 // function. 12176 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12177 if (Return.isInvalid()) { 12178 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12179 Conv->setInvalidDecl(); 12180 return; 12181 } 12182 12183 // Set the body of the conversion function. 12184 Stmt *ReturnS = Return.get(); 12185 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 12186 Conv->getLocation(), 12187 Conv->getLocation())); 12188 12189 // We're done; notify the mutation listener, if any. 12190 if (ASTMutationListener *L = getASTMutationListener()) { 12191 L->CompletedImplicitDefinition(Conv); 12192 } 12193 } 12194 12195 /// \brief Determine whether the given list arguments contains exactly one 12196 /// "real" (non-default) argument. 12197 static bool hasOneRealArgument(MultiExprArg Args) { 12198 switch (Args.size()) { 12199 case 0: 12200 return false; 12201 12202 default: 12203 if (!Args[1]->isDefaultArgument()) 12204 return false; 12205 12206 // fall through 12207 case 1: 12208 return !Args[0]->isDefaultArgument(); 12209 } 12210 12211 return false; 12212 } 12213 12214 ExprResult 12215 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12216 NamedDecl *FoundDecl, 12217 CXXConstructorDecl *Constructor, 12218 MultiExprArg ExprArgs, 12219 bool HadMultipleCandidates, 12220 bool IsListInitialization, 12221 bool IsStdInitListInitialization, 12222 bool RequiresZeroInit, 12223 unsigned ConstructKind, 12224 SourceRange ParenRange) { 12225 bool Elidable = false; 12226 12227 // C++0x [class.copy]p34: 12228 // When certain criteria are met, an implementation is allowed to 12229 // omit the copy/move construction of a class object, even if the 12230 // copy/move constructor and/or destructor for the object have 12231 // side effects. [...] 12232 // - when a temporary class object that has not been bound to a 12233 // reference (12.2) would be copied/moved to a class object 12234 // with the same cv-unqualified type, the copy/move operation 12235 // can be omitted by constructing the temporary object 12236 // directly into the target of the omitted copy/move 12237 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12238 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12239 Expr *SubExpr = ExprArgs[0]; 12240 Elidable = SubExpr->isTemporaryObject( 12241 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12242 } 12243 12244 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12245 FoundDecl, Constructor, 12246 Elidable, ExprArgs, HadMultipleCandidates, 12247 IsListInitialization, 12248 IsStdInitListInitialization, RequiresZeroInit, 12249 ConstructKind, ParenRange); 12250 } 12251 12252 ExprResult 12253 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12254 NamedDecl *FoundDecl, 12255 CXXConstructorDecl *Constructor, 12256 bool Elidable, 12257 MultiExprArg ExprArgs, 12258 bool HadMultipleCandidates, 12259 bool IsListInitialization, 12260 bool IsStdInitListInitialization, 12261 bool RequiresZeroInit, 12262 unsigned ConstructKind, 12263 SourceRange ParenRange) { 12264 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12265 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12266 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12267 return ExprError(); 12268 } 12269 12270 return BuildCXXConstructExpr( 12271 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12272 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12273 RequiresZeroInit, ConstructKind, ParenRange); 12274 } 12275 12276 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12277 /// including handling of its default argument expressions. 12278 ExprResult 12279 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12280 CXXConstructorDecl *Constructor, 12281 bool Elidable, 12282 MultiExprArg ExprArgs, 12283 bool HadMultipleCandidates, 12284 bool IsListInitialization, 12285 bool IsStdInitListInitialization, 12286 bool RequiresZeroInit, 12287 unsigned ConstructKind, 12288 SourceRange ParenRange) { 12289 assert(declaresSameEntity( 12290 Constructor->getParent(), 12291 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12292 "given constructor for wrong type"); 12293 MarkFunctionReferenced(ConstructLoc, Constructor); 12294 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12295 return ExprError(); 12296 12297 return CXXConstructExpr::Create( 12298 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12299 ExprArgs, HadMultipleCandidates, IsListInitialization, 12300 IsStdInitListInitialization, RequiresZeroInit, 12301 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12302 ParenRange); 12303 } 12304 12305 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12306 assert(Field->hasInClassInitializer()); 12307 12308 // If we already have the in-class initializer nothing needs to be done. 12309 if (Field->getInClassInitializer()) 12310 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12311 12312 // Maybe we haven't instantiated the in-class initializer. Go check the 12313 // pattern FieldDecl to see if it has one. 12314 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12315 12316 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12317 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12318 DeclContext::lookup_result Lookup = 12319 ClassPattern->lookup(Field->getDeclName()); 12320 12321 // Lookup can return at most two results: the pattern for the field, or the 12322 // injected class name of the parent record. No other member can have the 12323 // same name as the field. 12324 // In modules mode, lookup can return multiple results (coming from 12325 // different modules). 12326 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12327 "more than two lookup results for field name"); 12328 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12329 if (!Pattern) { 12330 assert(isa<CXXRecordDecl>(Lookup[0]) && 12331 "cannot have other non-field member with same name"); 12332 for (auto L : Lookup) 12333 if (isa<FieldDecl>(L)) { 12334 Pattern = cast<FieldDecl>(L); 12335 break; 12336 } 12337 assert(Pattern && "We must have set the Pattern!"); 12338 } 12339 12340 if (InstantiateInClassInitializer(Loc, Field, Pattern, 12341 getTemplateInstantiationArgs(Field))) 12342 return ExprError(); 12343 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12344 } 12345 12346 // DR1351: 12347 // If the brace-or-equal-initializer of a non-static data member 12348 // invokes a defaulted default constructor of its class or of an 12349 // enclosing class in a potentially evaluated subexpression, the 12350 // program is ill-formed. 12351 // 12352 // This resolution is unworkable: the exception specification of the 12353 // default constructor can be needed in an unevaluated context, in 12354 // particular, in the operand of a noexcept-expression, and we can be 12355 // unable to compute an exception specification for an enclosed class. 12356 // 12357 // Any attempt to resolve the exception specification of a defaulted default 12358 // constructor before the initializer is lexically complete will ultimately 12359 // come here at which point we can diagnose it. 12360 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12361 if (OutermostClass == ParentRD) { 12362 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 12363 << ParentRD << Field; 12364 } else { 12365 Diag(Field->getLocEnd(), 12366 diag::err_in_class_initializer_not_yet_parsed_outer_class) 12367 << ParentRD << OutermostClass << Field; 12368 } 12369 12370 return ExprError(); 12371 } 12372 12373 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12374 if (VD->isInvalidDecl()) return; 12375 12376 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12377 if (ClassDecl->isInvalidDecl()) return; 12378 if (ClassDecl->hasIrrelevantDestructor()) return; 12379 if (ClassDecl->isDependentContext()) return; 12380 12381 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12382 MarkFunctionReferenced(VD->getLocation(), Destructor); 12383 CheckDestructorAccess(VD->getLocation(), Destructor, 12384 PDiag(diag::err_access_dtor_var) 12385 << VD->getDeclName() 12386 << VD->getType()); 12387 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12388 12389 if (Destructor->isTrivial()) return; 12390 if (!VD->hasGlobalStorage()) return; 12391 12392 // Emit warning for non-trivial dtor in global scope (a real global, 12393 // class-static, function-static). 12394 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12395 12396 // TODO: this should be re-enabled for static locals by !CXAAtExit 12397 if (!VD->isStaticLocal()) 12398 Diag(VD->getLocation(), diag::warn_global_destructor); 12399 } 12400 12401 /// \brief Given a constructor and the set of arguments provided for the 12402 /// constructor, convert the arguments and add any required default arguments 12403 /// to form a proper call to this constructor. 12404 /// 12405 /// \returns true if an error occurred, false otherwise. 12406 bool 12407 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12408 MultiExprArg ArgsPtr, 12409 SourceLocation Loc, 12410 SmallVectorImpl<Expr*> &ConvertedArgs, 12411 bool AllowExplicit, 12412 bool IsListInitialization) { 12413 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12414 unsigned NumArgs = ArgsPtr.size(); 12415 Expr **Args = ArgsPtr.data(); 12416 12417 const FunctionProtoType *Proto 12418 = Constructor->getType()->getAs<FunctionProtoType>(); 12419 assert(Proto && "Constructor without a prototype?"); 12420 unsigned NumParams = Proto->getNumParams(); 12421 12422 // If too few arguments are available, we'll fill in the rest with defaults. 12423 if (NumArgs < NumParams) 12424 ConvertedArgs.reserve(NumParams); 12425 else 12426 ConvertedArgs.reserve(NumArgs); 12427 12428 VariadicCallType CallType = 12429 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12430 SmallVector<Expr *, 8> AllArgs; 12431 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12432 Proto, 0, 12433 llvm::makeArrayRef(Args, NumArgs), 12434 AllArgs, 12435 CallType, AllowExplicit, 12436 IsListInitialization); 12437 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12438 12439 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12440 12441 CheckConstructorCall(Constructor, 12442 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12443 Proto, Loc); 12444 12445 return Invalid; 12446 } 12447 12448 static inline bool 12449 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12450 const FunctionDecl *FnDecl) { 12451 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12452 if (isa<NamespaceDecl>(DC)) { 12453 return SemaRef.Diag(FnDecl->getLocation(), 12454 diag::err_operator_new_delete_declared_in_namespace) 12455 << FnDecl->getDeclName(); 12456 } 12457 12458 if (isa<TranslationUnitDecl>(DC) && 12459 FnDecl->getStorageClass() == SC_Static) { 12460 return SemaRef.Diag(FnDecl->getLocation(), 12461 diag::err_operator_new_delete_declared_static) 12462 << FnDecl->getDeclName(); 12463 } 12464 12465 return false; 12466 } 12467 12468 static inline bool 12469 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12470 CanQualType ExpectedResultType, 12471 CanQualType ExpectedFirstParamType, 12472 unsigned DependentParamTypeDiag, 12473 unsigned InvalidParamTypeDiag) { 12474 QualType ResultType = 12475 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12476 12477 // Check that the result type is not dependent. 12478 if (ResultType->isDependentType()) 12479 return SemaRef.Diag(FnDecl->getLocation(), 12480 diag::err_operator_new_delete_dependent_result_type) 12481 << FnDecl->getDeclName() << ExpectedResultType; 12482 12483 // Check that the result type is what we expect. 12484 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12485 return SemaRef.Diag(FnDecl->getLocation(), 12486 diag::err_operator_new_delete_invalid_result_type) 12487 << FnDecl->getDeclName() << ExpectedResultType; 12488 12489 // A function template must have at least 2 parameters. 12490 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12491 return SemaRef.Diag(FnDecl->getLocation(), 12492 diag::err_operator_new_delete_template_too_few_parameters) 12493 << FnDecl->getDeclName(); 12494 12495 // The function decl must have at least 1 parameter. 12496 if (FnDecl->getNumParams() == 0) 12497 return SemaRef.Diag(FnDecl->getLocation(), 12498 diag::err_operator_new_delete_too_few_parameters) 12499 << FnDecl->getDeclName(); 12500 12501 // Check the first parameter type is not dependent. 12502 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12503 if (FirstParamType->isDependentType()) 12504 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12505 << FnDecl->getDeclName() << ExpectedFirstParamType; 12506 12507 // Check that the first parameter type is what we expect. 12508 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12509 ExpectedFirstParamType) 12510 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12511 << FnDecl->getDeclName() << ExpectedFirstParamType; 12512 12513 return false; 12514 } 12515 12516 static bool 12517 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12518 // C++ [basic.stc.dynamic.allocation]p1: 12519 // A program is ill-formed if an allocation function is declared in a 12520 // namespace scope other than global scope or declared static in global 12521 // scope. 12522 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12523 return true; 12524 12525 CanQualType SizeTy = 12526 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12527 12528 // C++ [basic.stc.dynamic.allocation]p1: 12529 // The return type shall be void*. The first parameter shall have type 12530 // std::size_t. 12531 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12532 SizeTy, 12533 diag::err_operator_new_dependent_param_type, 12534 diag::err_operator_new_param_type)) 12535 return true; 12536 12537 // C++ [basic.stc.dynamic.allocation]p1: 12538 // The first parameter shall not have an associated default argument. 12539 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12540 return SemaRef.Diag(FnDecl->getLocation(), 12541 diag::err_operator_new_default_arg) 12542 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12543 12544 return false; 12545 } 12546 12547 static bool 12548 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12549 // C++ [basic.stc.dynamic.deallocation]p1: 12550 // A program is ill-formed if deallocation functions are declared in a 12551 // namespace scope other than global scope or declared static in global 12552 // scope. 12553 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12554 return true; 12555 12556 // C++ [basic.stc.dynamic.deallocation]p2: 12557 // Each deallocation function shall return void and its first parameter 12558 // shall be void*. 12559 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 12560 SemaRef.Context.VoidPtrTy, 12561 diag::err_operator_delete_dependent_param_type, 12562 diag::err_operator_delete_param_type)) 12563 return true; 12564 12565 return false; 12566 } 12567 12568 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12569 /// of this overloaded operator is well-formed. If so, returns false; 12570 /// otherwise, emits appropriate diagnostics and returns true. 12571 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12572 assert(FnDecl && FnDecl->isOverloadedOperator() && 12573 "Expected an overloaded operator declaration"); 12574 12575 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12576 12577 // C++ [over.oper]p5: 12578 // The allocation and deallocation functions, operator new, 12579 // operator new[], operator delete and operator delete[], are 12580 // described completely in 3.7.3. The attributes and restrictions 12581 // found in the rest of this subclause do not apply to them unless 12582 // explicitly stated in 3.7.3. 12583 if (Op == OO_Delete || Op == OO_Array_Delete) 12584 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12585 12586 if (Op == OO_New || Op == OO_Array_New) 12587 return CheckOperatorNewDeclaration(*this, FnDecl); 12588 12589 // C++ [over.oper]p6: 12590 // An operator function shall either be a non-static member 12591 // function or be a non-member function and have at least one 12592 // parameter whose type is a class, a reference to a class, an 12593 // enumeration, or a reference to an enumeration. 12594 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12595 if (MethodDecl->isStatic()) 12596 return Diag(FnDecl->getLocation(), 12597 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12598 } else { 12599 bool ClassOrEnumParam = false; 12600 for (auto Param : FnDecl->parameters()) { 12601 QualType ParamType = Param->getType().getNonReferenceType(); 12602 if (ParamType->isDependentType() || ParamType->isRecordType() || 12603 ParamType->isEnumeralType()) { 12604 ClassOrEnumParam = true; 12605 break; 12606 } 12607 } 12608 12609 if (!ClassOrEnumParam) 12610 return Diag(FnDecl->getLocation(), 12611 diag::err_operator_overload_needs_class_or_enum) 12612 << FnDecl->getDeclName(); 12613 } 12614 12615 // C++ [over.oper]p8: 12616 // An operator function cannot have default arguments (8.3.6), 12617 // except where explicitly stated below. 12618 // 12619 // Only the function-call operator allows default arguments 12620 // (C++ [over.call]p1). 12621 if (Op != OO_Call) { 12622 for (auto Param : FnDecl->parameters()) { 12623 if (Param->hasDefaultArg()) 12624 return Diag(Param->getLocation(), 12625 diag::err_operator_overload_default_arg) 12626 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12627 } 12628 } 12629 12630 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12631 { false, false, false } 12632 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12633 , { Unary, Binary, MemberOnly } 12634 #include "clang/Basic/OperatorKinds.def" 12635 }; 12636 12637 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12638 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12639 bool MustBeMemberOperator = OperatorUses[Op][2]; 12640 12641 // C++ [over.oper]p8: 12642 // [...] Operator functions cannot have more or fewer parameters 12643 // than the number required for the corresponding operator, as 12644 // described in the rest of this subclause. 12645 unsigned NumParams = FnDecl->getNumParams() 12646 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12647 if (Op != OO_Call && 12648 ((NumParams == 1 && !CanBeUnaryOperator) || 12649 (NumParams == 2 && !CanBeBinaryOperator) || 12650 (NumParams < 1) || (NumParams > 2))) { 12651 // We have the wrong number of parameters. 12652 unsigned ErrorKind; 12653 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12654 ErrorKind = 2; // 2 -> unary or binary. 12655 } else if (CanBeUnaryOperator) { 12656 ErrorKind = 0; // 0 -> unary 12657 } else { 12658 assert(CanBeBinaryOperator && 12659 "All non-call overloaded operators are unary or binary!"); 12660 ErrorKind = 1; // 1 -> binary 12661 } 12662 12663 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12664 << FnDecl->getDeclName() << NumParams << ErrorKind; 12665 } 12666 12667 // Overloaded operators other than operator() cannot be variadic. 12668 if (Op != OO_Call && 12669 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12670 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12671 << FnDecl->getDeclName(); 12672 } 12673 12674 // Some operators must be non-static member functions. 12675 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12676 return Diag(FnDecl->getLocation(), 12677 diag::err_operator_overload_must_be_member) 12678 << FnDecl->getDeclName(); 12679 } 12680 12681 // C++ [over.inc]p1: 12682 // The user-defined function called operator++ implements the 12683 // prefix and postfix ++ operator. If this function is a member 12684 // function with no parameters, or a non-member function with one 12685 // parameter of class or enumeration type, it defines the prefix 12686 // increment operator ++ for objects of that type. If the function 12687 // is a member function with one parameter (which shall be of type 12688 // int) or a non-member function with two parameters (the second 12689 // of which shall be of type int), it defines the postfix 12690 // increment operator ++ for objects of that type. 12691 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12692 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12693 QualType ParamType = LastParam->getType(); 12694 12695 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12696 !ParamType->isDependentType()) 12697 return Diag(LastParam->getLocation(), 12698 diag::err_operator_overload_post_incdec_must_be_int) 12699 << LastParam->getType() << (Op == OO_MinusMinus); 12700 } 12701 12702 return false; 12703 } 12704 12705 static bool 12706 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12707 FunctionTemplateDecl *TpDecl) { 12708 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 12709 12710 // Must have one or two template parameters. 12711 if (TemplateParams->size() == 1) { 12712 NonTypeTemplateParmDecl *PmDecl = 12713 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 12714 12715 // The template parameter must be a char parameter pack. 12716 if (PmDecl && PmDecl->isTemplateParameterPack() && 12717 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 12718 return false; 12719 12720 } else if (TemplateParams->size() == 2) { 12721 TemplateTypeParmDecl *PmType = 12722 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 12723 NonTypeTemplateParmDecl *PmArgs = 12724 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 12725 12726 // The second template parameter must be a parameter pack with the 12727 // first template parameter as its type. 12728 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 12729 PmArgs->isTemplateParameterPack()) { 12730 const TemplateTypeParmType *TArgs = 12731 PmArgs->getType()->getAs<TemplateTypeParmType>(); 12732 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 12733 TArgs->getIndex() == PmType->getIndex()) { 12734 if (SemaRef.ActiveTemplateInstantiations.empty()) 12735 SemaRef.Diag(TpDecl->getLocation(), 12736 diag::ext_string_literal_operator_template); 12737 return false; 12738 } 12739 } 12740 } 12741 12742 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 12743 diag::err_literal_operator_template) 12744 << TpDecl->getTemplateParameters()->getSourceRange(); 12745 return true; 12746 } 12747 12748 /// CheckLiteralOperatorDeclaration - Check whether the declaration 12749 /// of this literal operator function is well-formed. If so, returns 12750 /// false; otherwise, emits appropriate diagnostics and returns true. 12751 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 12752 if (isa<CXXMethodDecl>(FnDecl)) { 12753 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 12754 << FnDecl->getDeclName(); 12755 return true; 12756 } 12757 12758 if (FnDecl->isExternC()) { 12759 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 12760 return true; 12761 } 12762 12763 // This might be the definition of a literal operator template. 12764 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 12765 12766 // This might be a specialization of a literal operator template. 12767 if (!TpDecl) 12768 TpDecl = FnDecl->getPrimaryTemplate(); 12769 12770 // template <char...> type operator "" name() and 12771 // template <class T, T...> type operator "" name() are the only valid 12772 // template signatures, and the only valid signatures with no parameters. 12773 if (TpDecl) { 12774 if (FnDecl->param_size() != 0) { 12775 Diag(FnDecl->getLocation(), 12776 diag::err_literal_operator_template_with_params); 12777 return true; 12778 } 12779 12780 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 12781 return true; 12782 12783 } else if (FnDecl->param_size() == 1) { 12784 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 12785 12786 QualType ParamType = Param->getType().getUnqualifiedType(); 12787 12788 // Only unsigned long long int, long double, any character type, and const 12789 // char * are allowed as the only parameters. 12790 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 12791 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 12792 Context.hasSameType(ParamType, Context.CharTy) || 12793 Context.hasSameType(ParamType, Context.WideCharTy) || 12794 Context.hasSameType(ParamType, Context.Char16Ty) || 12795 Context.hasSameType(ParamType, Context.Char32Ty)) { 12796 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 12797 QualType InnerType = Ptr->getPointeeType(); 12798 12799 // Pointer parameter must be a const char *. 12800 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 12801 Context.CharTy) && 12802 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 12803 Diag(Param->getSourceRange().getBegin(), 12804 diag::err_literal_operator_param) 12805 << ParamType << "'const char *'" << Param->getSourceRange(); 12806 return true; 12807 } 12808 12809 } else if (ParamType->isRealFloatingType()) { 12810 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12811 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 12812 return true; 12813 12814 } else if (ParamType->isIntegerType()) { 12815 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12816 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 12817 return true; 12818 12819 } else { 12820 Diag(Param->getSourceRange().getBegin(), 12821 diag::err_literal_operator_invalid_param) 12822 << ParamType << Param->getSourceRange(); 12823 return true; 12824 } 12825 12826 } else if (FnDecl->param_size() == 2) { 12827 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 12828 12829 // First, verify that the first parameter is correct. 12830 12831 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 12832 12833 // Two parameter function must have a pointer to const as a 12834 // first parameter; let's strip those qualifiers. 12835 const PointerType *PT = FirstParamType->getAs<PointerType>(); 12836 12837 if (!PT) { 12838 Diag((*Param)->getSourceRange().getBegin(), 12839 diag::err_literal_operator_param) 12840 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12841 return true; 12842 } 12843 12844 QualType PointeeType = PT->getPointeeType(); 12845 // First parameter must be const 12846 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 12847 Diag((*Param)->getSourceRange().getBegin(), 12848 diag::err_literal_operator_param) 12849 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12850 return true; 12851 } 12852 12853 QualType InnerType = PointeeType.getUnqualifiedType(); 12854 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 12855 // are allowed as the first parameter to a two-parameter function 12856 if (!(Context.hasSameType(InnerType, Context.CharTy) || 12857 Context.hasSameType(InnerType, Context.WideCharTy) || 12858 Context.hasSameType(InnerType, Context.Char16Ty) || 12859 Context.hasSameType(InnerType, Context.Char32Ty))) { 12860 Diag((*Param)->getSourceRange().getBegin(), 12861 diag::err_literal_operator_param) 12862 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12863 return true; 12864 } 12865 12866 // Move on to the second and final parameter. 12867 ++Param; 12868 12869 // The second parameter must be a std::size_t. 12870 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 12871 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 12872 Diag((*Param)->getSourceRange().getBegin(), 12873 diag::err_literal_operator_param) 12874 << SecondParamType << Context.getSizeType() 12875 << (*Param)->getSourceRange(); 12876 return true; 12877 } 12878 } else { 12879 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 12880 return true; 12881 } 12882 12883 // Parameters are good. 12884 12885 // A parameter-declaration-clause containing a default argument is not 12886 // equivalent to any of the permitted forms. 12887 for (auto Param : FnDecl->parameters()) { 12888 if (Param->hasDefaultArg()) { 12889 Diag(Param->getDefaultArgRange().getBegin(), 12890 diag::err_literal_operator_default_argument) 12891 << Param->getDefaultArgRange(); 12892 break; 12893 } 12894 } 12895 12896 StringRef LiteralName 12897 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 12898 if (LiteralName[0] != '_') { 12899 // C++11 [usrlit.suffix]p1: 12900 // Literal suffix identifiers that do not start with an underscore 12901 // are reserved for future standardization. 12902 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 12903 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 12904 } 12905 12906 return false; 12907 } 12908 12909 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 12910 /// linkage specification, including the language and (if present) 12911 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 12912 /// language string literal. LBraceLoc, if valid, provides the location of 12913 /// the '{' brace. Otherwise, this linkage specification does not 12914 /// have any braces. 12915 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 12916 Expr *LangStr, 12917 SourceLocation LBraceLoc) { 12918 StringLiteral *Lit = cast<StringLiteral>(LangStr); 12919 if (!Lit->isAscii()) { 12920 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 12921 << LangStr->getSourceRange(); 12922 return nullptr; 12923 } 12924 12925 StringRef Lang = Lit->getString(); 12926 LinkageSpecDecl::LanguageIDs Language; 12927 if (Lang == "C") 12928 Language = LinkageSpecDecl::lang_c; 12929 else if (Lang == "C++") 12930 Language = LinkageSpecDecl::lang_cxx; 12931 else { 12932 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 12933 << LangStr->getSourceRange(); 12934 return nullptr; 12935 } 12936 12937 // FIXME: Add all the various semantics of linkage specifications 12938 12939 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 12940 LangStr->getExprLoc(), Language, 12941 LBraceLoc.isValid()); 12942 CurContext->addDecl(D); 12943 PushDeclContext(S, D); 12944 return D; 12945 } 12946 12947 /// ActOnFinishLinkageSpecification - Complete the definition of 12948 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 12949 /// valid, it's the position of the closing '}' brace in a linkage 12950 /// specification that uses braces. 12951 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 12952 Decl *LinkageSpec, 12953 SourceLocation RBraceLoc) { 12954 if (RBraceLoc.isValid()) { 12955 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 12956 LSDecl->setRBraceLoc(RBraceLoc); 12957 } 12958 PopDeclContext(); 12959 return LinkageSpec; 12960 } 12961 12962 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 12963 AttributeList *AttrList, 12964 SourceLocation SemiLoc) { 12965 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 12966 // Attribute declarations appertain to empty declaration so we handle 12967 // them here. 12968 if (AttrList) 12969 ProcessDeclAttributeList(S, ED, AttrList); 12970 12971 CurContext->addDecl(ED); 12972 return ED; 12973 } 12974 12975 /// \brief Perform semantic analysis for the variable declaration that 12976 /// occurs within a C++ catch clause, returning the newly-created 12977 /// variable. 12978 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 12979 TypeSourceInfo *TInfo, 12980 SourceLocation StartLoc, 12981 SourceLocation Loc, 12982 IdentifierInfo *Name) { 12983 bool Invalid = false; 12984 QualType ExDeclType = TInfo->getType(); 12985 12986 // Arrays and functions decay. 12987 if (ExDeclType->isArrayType()) 12988 ExDeclType = Context.getArrayDecayedType(ExDeclType); 12989 else if (ExDeclType->isFunctionType()) 12990 ExDeclType = Context.getPointerType(ExDeclType); 12991 12992 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 12993 // The exception-declaration shall not denote a pointer or reference to an 12994 // incomplete type, other than [cv] void*. 12995 // N2844 forbids rvalue references. 12996 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 12997 Diag(Loc, diag::err_catch_rvalue_ref); 12998 Invalid = true; 12999 } 13000 13001 if (ExDeclType->isVariablyModifiedType()) { 13002 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13003 Invalid = true; 13004 } 13005 13006 QualType BaseType = ExDeclType; 13007 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13008 unsigned DK = diag::err_catch_incomplete; 13009 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13010 BaseType = Ptr->getPointeeType(); 13011 Mode = 1; 13012 DK = diag::err_catch_incomplete_ptr; 13013 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13014 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13015 BaseType = Ref->getPointeeType(); 13016 Mode = 2; 13017 DK = diag::err_catch_incomplete_ref; 13018 } 13019 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13020 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13021 Invalid = true; 13022 13023 if (!Invalid && !ExDeclType->isDependentType() && 13024 RequireNonAbstractType(Loc, ExDeclType, 13025 diag::err_abstract_type_in_decl, 13026 AbstractVariableType)) 13027 Invalid = true; 13028 13029 // Only the non-fragile NeXT runtime currently supports C++ catches 13030 // of ObjC types, and no runtime supports catching ObjC types by value. 13031 if (!Invalid && getLangOpts().ObjC1) { 13032 QualType T = ExDeclType; 13033 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13034 T = RT->getPointeeType(); 13035 13036 if (T->isObjCObjectType()) { 13037 Diag(Loc, diag::err_objc_object_catch); 13038 Invalid = true; 13039 } else if (T->isObjCObjectPointerType()) { 13040 // FIXME: should this be a test for macosx-fragile specifically? 13041 if (getLangOpts().ObjCRuntime.isFragile()) 13042 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13043 } 13044 } 13045 13046 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13047 ExDeclType, TInfo, SC_None); 13048 ExDecl->setExceptionVariable(true); 13049 13050 // In ARC, infer 'retaining' for variables of retainable type. 13051 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13052 Invalid = true; 13053 13054 if (!Invalid && !ExDeclType->isDependentType()) { 13055 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13056 // Insulate this from anything else we might currently be parsing. 13057 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 13058 13059 // C++ [except.handle]p16: 13060 // The object declared in an exception-declaration or, if the 13061 // exception-declaration does not specify a name, a temporary (12.2) is 13062 // copy-initialized (8.5) from the exception object. [...] 13063 // The object is destroyed when the handler exits, after the destruction 13064 // of any automatic objects initialized within the handler. 13065 // 13066 // We just pretend to initialize the object with itself, then make sure 13067 // it can be destroyed later. 13068 QualType initType = Context.getExceptionObjectType(ExDeclType); 13069 13070 InitializedEntity entity = 13071 InitializedEntity::InitializeVariable(ExDecl); 13072 InitializationKind initKind = 13073 InitializationKind::CreateCopy(Loc, SourceLocation()); 13074 13075 Expr *opaqueValue = 13076 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13077 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13078 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13079 if (result.isInvalid()) 13080 Invalid = true; 13081 else { 13082 // If the constructor used was non-trivial, set this as the 13083 // "initializer". 13084 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13085 if (!construct->getConstructor()->isTrivial()) { 13086 Expr *init = MaybeCreateExprWithCleanups(construct); 13087 ExDecl->setInit(init); 13088 } 13089 13090 // And make sure it's destructable. 13091 FinalizeVarWithDestructor(ExDecl, recordType); 13092 } 13093 } 13094 } 13095 13096 if (Invalid) 13097 ExDecl->setInvalidDecl(); 13098 13099 return ExDecl; 13100 } 13101 13102 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13103 /// handler. 13104 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13105 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13106 bool Invalid = D.isInvalidType(); 13107 13108 // Check for unexpanded parameter packs. 13109 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13110 UPPC_ExceptionType)) { 13111 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13112 D.getIdentifierLoc()); 13113 Invalid = true; 13114 } 13115 13116 IdentifierInfo *II = D.getIdentifier(); 13117 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13118 LookupOrdinaryName, 13119 ForRedeclaration)) { 13120 // The scope should be freshly made just for us. There is just no way 13121 // it contains any previous declaration, except for function parameters in 13122 // a function-try-block's catch statement. 13123 assert(!S->isDeclScope(PrevDecl)); 13124 if (isDeclInScope(PrevDecl, CurContext, S)) { 13125 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13126 << D.getIdentifier(); 13127 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13128 Invalid = true; 13129 } else if (PrevDecl->isTemplateParameter()) 13130 // Maybe we will complain about the shadowed template parameter. 13131 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13132 } 13133 13134 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13135 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13136 << D.getCXXScopeSpec().getRange(); 13137 Invalid = true; 13138 } 13139 13140 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13141 D.getLocStart(), 13142 D.getIdentifierLoc(), 13143 D.getIdentifier()); 13144 if (Invalid) 13145 ExDecl->setInvalidDecl(); 13146 13147 // Add the exception declaration into this scope. 13148 if (II) 13149 PushOnScopeChains(ExDecl, S); 13150 else 13151 CurContext->addDecl(ExDecl); 13152 13153 ProcessDeclAttributes(S, ExDecl, D); 13154 return ExDecl; 13155 } 13156 13157 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13158 Expr *AssertExpr, 13159 Expr *AssertMessageExpr, 13160 SourceLocation RParenLoc) { 13161 StringLiteral *AssertMessage = 13162 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13163 13164 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13165 return nullptr; 13166 13167 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13168 AssertMessage, RParenLoc, false); 13169 } 13170 13171 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13172 Expr *AssertExpr, 13173 StringLiteral *AssertMessage, 13174 SourceLocation RParenLoc, 13175 bool Failed) { 13176 assert(AssertExpr != nullptr && "Expected non-null condition"); 13177 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13178 !Failed) { 13179 // In a static_assert-declaration, the constant-expression shall be a 13180 // constant expression that can be contextually converted to bool. 13181 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13182 if (Converted.isInvalid()) 13183 Failed = true; 13184 13185 llvm::APSInt Cond; 13186 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13187 diag::err_static_assert_expression_is_not_constant, 13188 /*AllowFold=*/false).isInvalid()) 13189 Failed = true; 13190 13191 if (!Failed && !Cond) { 13192 SmallString<256> MsgBuffer; 13193 llvm::raw_svector_ostream Msg(MsgBuffer); 13194 if (AssertMessage) 13195 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13196 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13197 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13198 Failed = true; 13199 } 13200 } 13201 13202 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13203 AssertExpr, AssertMessage, RParenLoc, 13204 Failed); 13205 13206 CurContext->addDecl(Decl); 13207 return Decl; 13208 } 13209 13210 /// \brief Perform semantic analysis of the given friend type declaration. 13211 /// 13212 /// \returns A friend declaration that. 13213 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13214 SourceLocation FriendLoc, 13215 TypeSourceInfo *TSInfo) { 13216 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13217 13218 QualType T = TSInfo->getType(); 13219 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13220 13221 // C++03 [class.friend]p2: 13222 // An elaborated-type-specifier shall be used in a friend declaration 13223 // for a class.* 13224 // 13225 // * The class-key of the elaborated-type-specifier is required. 13226 if (!ActiveTemplateInstantiations.empty()) { 13227 // Do not complain about the form of friend template types during 13228 // template instantiation; we will already have complained when the 13229 // template was declared. 13230 } else { 13231 if (!T->isElaboratedTypeSpecifier()) { 13232 // If we evaluated the type to a record type, suggest putting 13233 // a tag in front. 13234 if (const RecordType *RT = T->getAs<RecordType>()) { 13235 RecordDecl *RD = RT->getDecl(); 13236 13237 SmallString<16> InsertionText(" "); 13238 InsertionText += RD->getKindName(); 13239 13240 Diag(TypeRange.getBegin(), 13241 getLangOpts().CPlusPlus11 ? 13242 diag::warn_cxx98_compat_unelaborated_friend_type : 13243 diag::ext_unelaborated_friend_type) 13244 << (unsigned) RD->getTagKind() 13245 << T 13246 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13247 InsertionText); 13248 } else { 13249 Diag(FriendLoc, 13250 getLangOpts().CPlusPlus11 ? 13251 diag::warn_cxx98_compat_nonclass_type_friend : 13252 diag::ext_nonclass_type_friend) 13253 << T 13254 << TypeRange; 13255 } 13256 } else if (T->getAs<EnumType>()) { 13257 Diag(FriendLoc, 13258 getLangOpts().CPlusPlus11 ? 13259 diag::warn_cxx98_compat_enum_friend : 13260 diag::ext_enum_friend) 13261 << T 13262 << TypeRange; 13263 } 13264 13265 // C++11 [class.friend]p3: 13266 // A friend declaration that does not declare a function shall have one 13267 // of the following forms: 13268 // friend elaborated-type-specifier ; 13269 // friend simple-type-specifier ; 13270 // friend typename-specifier ; 13271 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13272 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13273 } 13274 13275 // If the type specifier in a friend declaration designates a (possibly 13276 // cv-qualified) class type, that class is declared as a friend; otherwise, 13277 // the friend declaration is ignored. 13278 return FriendDecl::Create(Context, CurContext, 13279 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13280 FriendLoc); 13281 } 13282 13283 /// Handle a friend tag declaration where the scope specifier was 13284 /// templated. 13285 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13286 unsigned TagSpec, SourceLocation TagLoc, 13287 CXXScopeSpec &SS, 13288 IdentifierInfo *Name, 13289 SourceLocation NameLoc, 13290 AttributeList *Attr, 13291 MultiTemplateParamsArg TempParamLists) { 13292 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13293 13294 bool isExplicitSpecialization = false; 13295 bool Invalid = false; 13296 13297 if (TemplateParameterList *TemplateParams = 13298 MatchTemplateParametersToScopeSpecifier( 13299 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13300 isExplicitSpecialization, Invalid)) { 13301 if (TemplateParams->size() > 0) { 13302 // This is a declaration of a class template. 13303 if (Invalid) 13304 return nullptr; 13305 13306 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13307 NameLoc, Attr, TemplateParams, AS_public, 13308 /*ModulePrivateLoc=*/SourceLocation(), 13309 FriendLoc, TempParamLists.size() - 1, 13310 TempParamLists.data()).get(); 13311 } else { 13312 // The "template<>" header is extraneous. 13313 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13314 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13315 isExplicitSpecialization = true; 13316 } 13317 } 13318 13319 if (Invalid) return nullptr; 13320 13321 bool isAllExplicitSpecializations = true; 13322 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13323 if (TempParamLists[I]->size()) { 13324 isAllExplicitSpecializations = false; 13325 break; 13326 } 13327 } 13328 13329 // FIXME: don't ignore attributes. 13330 13331 // If it's explicit specializations all the way down, just forget 13332 // about the template header and build an appropriate non-templated 13333 // friend. TODO: for source fidelity, remember the headers. 13334 if (isAllExplicitSpecializations) { 13335 if (SS.isEmpty()) { 13336 bool Owned = false; 13337 bool IsDependent = false; 13338 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13339 Attr, AS_public, 13340 /*ModulePrivateLoc=*/SourceLocation(), 13341 MultiTemplateParamsArg(), Owned, IsDependent, 13342 /*ScopedEnumKWLoc=*/SourceLocation(), 13343 /*ScopedEnumUsesClassTag=*/false, 13344 /*UnderlyingType=*/TypeResult(), 13345 /*IsTypeSpecifier=*/false); 13346 } 13347 13348 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13349 ElaboratedTypeKeyword Keyword 13350 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13351 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13352 *Name, NameLoc); 13353 if (T.isNull()) 13354 return nullptr; 13355 13356 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13357 if (isa<DependentNameType>(T)) { 13358 DependentNameTypeLoc TL = 13359 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13360 TL.setElaboratedKeywordLoc(TagLoc); 13361 TL.setQualifierLoc(QualifierLoc); 13362 TL.setNameLoc(NameLoc); 13363 } else { 13364 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13365 TL.setElaboratedKeywordLoc(TagLoc); 13366 TL.setQualifierLoc(QualifierLoc); 13367 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13368 } 13369 13370 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13371 TSI, FriendLoc, TempParamLists); 13372 Friend->setAccess(AS_public); 13373 CurContext->addDecl(Friend); 13374 return Friend; 13375 } 13376 13377 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13378 13379 13380 13381 // Handle the case of a templated-scope friend class. e.g. 13382 // template <class T> class A<T>::B; 13383 // FIXME: we don't support these right now. 13384 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13385 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13386 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13387 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13388 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13389 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13390 TL.setElaboratedKeywordLoc(TagLoc); 13391 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13392 TL.setNameLoc(NameLoc); 13393 13394 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13395 TSI, FriendLoc, TempParamLists); 13396 Friend->setAccess(AS_public); 13397 Friend->setUnsupportedFriend(true); 13398 CurContext->addDecl(Friend); 13399 return Friend; 13400 } 13401 13402 13403 /// Handle a friend type declaration. This works in tandem with 13404 /// ActOnTag. 13405 /// 13406 /// Notes on friend class templates: 13407 /// 13408 /// We generally treat friend class declarations as if they were 13409 /// declaring a class. So, for example, the elaborated type specifier 13410 /// in a friend declaration is required to obey the restrictions of a 13411 /// class-head (i.e. no typedefs in the scope chain), template 13412 /// parameters are required to match up with simple template-ids, &c. 13413 /// However, unlike when declaring a template specialization, it's 13414 /// okay to refer to a template specialization without an empty 13415 /// template parameter declaration, e.g. 13416 /// friend class A<T>::B<unsigned>; 13417 /// We permit this as a special case; if there are any template 13418 /// parameters present at all, require proper matching, i.e. 13419 /// template <> template \<class T> friend class A<int>::B; 13420 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13421 MultiTemplateParamsArg TempParams) { 13422 SourceLocation Loc = DS.getLocStart(); 13423 13424 assert(DS.isFriendSpecified()); 13425 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13426 13427 // Try to convert the decl specifier to a type. This works for 13428 // friend templates because ActOnTag never produces a ClassTemplateDecl 13429 // for a TUK_Friend. 13430 Declarator TheDeclarator(DS, Declarator::MemberContext); 13431 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13432 QualType T = TSI->getType(); 13433 if (TheDeclarator.isInvalidType()) 13434 return nullptr; 13435 13436 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13437 return nullptr; 13438 13439 // This is definitely an error in C++98. It's probably meant to 13440 // be forbidden in C++0x, too, but the specification is just 13441 // poorly written. 13442 // 13443 // The problem is with declarations like the following: 13444 // template <T> friend A<T>::foo; 13445 // where deciding whether a class C is a friend or not now hinges 13446 // on whether there exists an instantiation of A that causes 13447 // 'foo' to equal C. There are restrictions on class-heads 13448 // (which we declare (by fiat) elaborated friend declarations to 13449 // be) that makes this tractable. 13450 // 13451 // FIXME: handle "template <> friend class A<T>;", which 13452 // is possibly well-formed? Who even knows? 13453 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13454 Diag(Loc, diag::err_tagless_friend_type_template) 13455 << DS.getSourceRange(); 13456 return nullptr; 13457 } 13458 13459 // C++98 [class.friend]p1: A friend of a class is a function 13460 // or class that is not a member of the class . . . 13461 // This is fixed in DR77, which just barely didn't make the C++03 13462 // deadline. It's also a very silly restriction that seriously 13463 // affects inner classes and which nobody else seems to implement; 13464 // thus we never diagnose it, not even in -pedantic. 13465 // 13466 // But note that we could warn about it: it's always useless to 13467 // friend one of your own members (it's not, however, worthless to 13468 // friend a member of an arbitrary specialization of your template). 13469 13470 Decl *D; 13471 if (!TempParams.empty()) 13472 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13473 TempParams, 13474 TSI, 13475 DS.getFriendSpecLoc()); 13476 else 13477 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13478 13479 if (!D) 13480 return nullptr; 13481 13482 D->setAccess(AS_public); 13483 CurContext->addDecl(D); 13484 13485 return D; 13486 } 13487 13488 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13489 MultiTemplateParamsArg TemplateParams) { 13490 const DeclSpec &DS = D.getDeclSpec(); 13491 13492 assert(DS.isFriendSpecified()); 13493 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13494 13495 SourceLocation Loc = D.getIdentifierLoc(); 13496 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13497 13498 // C++ [class.friend]p1 13499 // A friend of a class is a function or class.... 13500 // Note that this sees through typedefs, which is intended. 13501 // It *doesn't* see through dependent types, which is correct 13502 // according to [temp.arg.type]p3: 13503 // If a declaration acquires a function type through a 13504 // type dependent on a template-parameter and this causes 13505 // a declaration that does not use the syntactic form of a 13506 // function declarator to have a function type, the program 13507 // is ill-formed. 13508 if (!TInfo->getType()->isFunctionType()) { 13509 Diag(Loc, diag::err_unexpected_friend); 13510 13511 // It might be worthwhile to try to recover by creating an 13512 // appropriate declaration. 13513 return nullptr; 13514 } 13515 13516 // C++ [namespace.memdef]p3 13517 // - If a friend declaration in a non-local class first declares a 13518 // class or function, the friend class or function is a member 13519 // of the innermost enclosing namespace. 13520 // - The name of the friend is not found by simple name lookup 13521 // until a matching declaration is provided in that namespace 13522 // scope (either before or after the class declaration granting 13523 // friendship). 13524 // - If a friend function is called, its name may be found by the 13525 // name lookup that considers functions from namespaces and 13526 // classes associated with the types of the function arguments. 13527 // - When looking for a prior declaration of a class or a function 13528 // declared as a friend, scopes outside the innermost enclosing 13529 // namespace scope are not considered. 13530 13531 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13532 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13533 DeclarationName Name = NameInfo.getName(); 13534 assert(Name); 13535 13536 // Check for unexpanded parameter packs. 13537 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13538 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13539 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13540 return nullptr; 13541 13542 // The context we found the declaration in, or in which we should 13543 // create the declaration. 13544 DeclContext *DC; 13545 Scope *DCScope = S; 13546 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13547 ForRedeclaration); 13548 13549 // There are five cases here. 13550 // - There's no scope specifier and we're in a local class. Only look 13551 // for functions declared in the immediately-enclosing block scope. 13552 // We recover from invalid scope qualifiers as if they just weren't there. 13553 FunctionDecl *FunctionContainingLocalClass = nullptr; 13554 if ((SS.isInvalid() || !SS.isSet()) && 13555 (FunctionContainingLocalClass = 13556 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13557 // C++11 [class.friend]p11: 13558 // If a friend declaration appears in a local class and the name 13559 // specified is an unqualified name, a prior declaration is 13560 // looked up without considering scopes that are outside the 13561 // innermost enclosing non-class scope. For a friend function 13562 // declaration, if there is no prior declaration, the program is 13563 // ill-formed. 13564 13565 // Find the innermost enclosing non-class scope. This is the block 13566 // scope containing the local class definition (or for a nested class, 13567 // the outer local class). 13568 DCScope = S->getFnParent(); 13569 13570 // Look up the function name in the scope. 13571 Previous.clear(LookupLocalFriendName); 13572 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13573 13574 if (!Previous.empty()) { 13575 // All possible previous declarations must have the same context: 13576 // either they were declared at block scope or they are members of 13577 // one of the enclosing local classes. 13578 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13579 } else { 13580 // This is ill-formed, but provide the context that we would have 13581 // declared the function in, if we were permitted to, for error recovery. 13582 DC = FunctionContainingLocalClass; 13583 } 13584 adjustContextForLocalExternDecl(DC); 13585 13586 // C++ [class.friend]p6: 13587 // A function can be defined in a friend declaration of a class if and 13588 // only if the class is a non-local class (9.8), the function name is 13589 // unqualified, and the function has namespace scope. 13590 if (D.isFunctionDefinition()) { 13591 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13592 } 13593 13594 // - There's no scope specifier, in which case we just go to the 13595 // appropriate scope and look for a function or function template 13596 // there as appropriate. 13597 } else if (SS.isInvalid() || !SS.isSet()) { 13598 // C++11 [namespace.memdef]p3: 13599 // If the name in a friend declaration is neither qualified nor 13600 // a template-id and the declaration is a function or an 13601 // elaborated-type-specifier, the lookup to determine whether 13602 // the entity has been previously declared shall not consider 13603 // any scopes outside the innermost enclosing namespace. 13604 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 13605 13606 // Find the appropriate context according to the above. 13607 DC = CurContext; 13608 13609 // Skip class contexts. If someone can cite chapter and verse 13610 // for this behavior, that would be nice --- it's what GCC and 13611 // EDG do, and it seems like a reasonable intent, but the spec 13612 // really only says that checks for unqualified existing 13613 // declarations should stop at the nearest enclosing namespace, 13614 // not that they should only consider the nearest enclosing 13615 // namespace. 13616 while (DC->isRecord()) 13617 DC = DC->getParent(); 13618 13619 DeclContext *LookupDC = DC; 13620 while (LookupDC->isTransparentContext()) 13621 LookupDC = LookupDC->getParent(); 13622 13623 while (true) { 13624 LookupQualifiedName(Previous, LookupDC); 13625 13626 if (!Previous.empty()) { 13627 DC = LookupDC; 13628 break; 13629 } 13630 13631 if (isTemplateId) { 13632 if (isa<TranslationUnitDecl>(LookupDC)) break; 13633 } else { 13634 if (LookupDC->isFileContext()) break; 13635 } 13636 LookupDC = LookupDC->getParent(); 13637 } 13638 13639 DCScope = getScopeForDeclContext(S, DC); 13640 13641 // - There's a non-dependent scope specifier, in which case we 13642 // compute it and do a previous lookup there for a function 13643 // or function template. 13644 } else if (!SS.getScopeRep()->isDependent()) { 13645 DC = computeDeclContext(SS); 13646 if (!DC) return nullptr; 13647 13648 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13649 13650 LookupQualifiedName(Previous, DC); 13651 13652 // Ignore things found implicitly in the wrong scope. 13653 // TODO: better diagnostics for this case. Suggesting the right 13654 // qualified scope would be nice... 13655 LookupResult::Filter F = Previous.makeFilter(); 13656 while (F.hasNext()) { 13657 NamedDecl *D = F.next(); 13658 if (!DC->InEnclosingNamespaceSetOf( 13659 D->getDeclContext()->getRedeclContext())) 13660 F.erase(); 13661 } 13662 F.done(); 13663 13664 if (Previous.empty()) { 13665 D.setInvalidType(); 13666 Diag(Loc, diag::err_qualified_friend_not_found) 13667 << Name << TInfo->getType(); 13668 return nullptr; 13669 } 13670 13671 // C++ [class.friend]p1: A friend of a class is a function or 13672 // class that is not a member of the class . . . 13673 if (DC->Equals(CurContext)) 13674 Diag(DS.getFriendSpecLoc(), 13675 getLangOpts().CPlusPlus11 ? 13676 diag::warn_cxx98_compat_friend_is_member : 13677 diag::err_friend_is_member); 13678 13679 if (D.isFunctionDefinition()) { 13680 // C++ [class.friend]p6: 13681 // A function can be defined in a friend declaration of a class if and 13682 // only if the class is a non-local class (9.8), the function name is 13683 // unqualified, and the function has namespace scope. 13684 SemaDiagnosticBuilder DB 13685 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 13686 13687 DB << SS.getScopeRep(); 13688 if (DC->isFileContext()) 13689 DB << FixItHint::CreateRemoval(SS.getRange()); 13690 SS.clear(); 13691 } 13692 13693 // - There's a scope specifier that does not match any template 13694 // parameter lists, in which case we use some arbitrary context, 13695 // create a method or method template, and wait for instantiation. 13696 // - There's a scope specifier that does match some template 13697 // parameter lists, which we don't handle right now. 13698 } else { 13699 if (D.isFunctionDefinition()) { 13700 // C++ [class.friend]p6: 13701 // A function can be defined in a friend declaration of a class if and 13702 // only if the class is a non-local class (9.8), the function name is 13703 // unqualified, and the function has namespace scope. 13704 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 13705 << SS.getScopeRep(); 13706 } 13707 13708 DC = CurContext; 13709 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 13710 } 13711 13712 if (!DC->isRecord()) { 13713 int DiagArg = -1; 13714 switch (D.getName().getKind()) { 13715 case UnqualifiedId::IK_ConstructorTemplateId: 13716 case UnqualifiedId::IK_ConstructorName: 13717 DiagArg = 0; 13718 break; 13719 case UnqualifiedId::IK_DestructorName: 13720 DiagArg = 1; 13721 break; 13722 case UnqualifiedId::IK_ConversionFunctionId: 13723 DiagArg = 2; 13724 break; 13725 case UnqualifiedId::IK_Identifier: 13726 case UnqualifiedId::IK_ImplicitSelfParam: 13727 case UnqualifiedId::IK_LiteralOperatorId: 13728 case UnqualifiedId::IK_OperatorFunctionId: 13729 case UnqualifiedId::IK_TemplateId: 13730 break; 13731 } 13732 // This implies that it has to be an operator or function. 13733 if (DiagArg >= 0) { 13734 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 13735 return nullptr; 13736 } 13737 } 13738 13739 // FIXME: This is an egregious hack to cope with cases where the scope stack 13740 // does not contain the declaration context, i.e., in an out-of-line 13741 // definition of a class. 13742 Scope FakeDCScope(S, Scope::DeclScope, Diags); 13743 if (!DCScope) { 13744 FakeDCScope.setEntity(DC); 13745 DCScope = &FakeDCScope; 13746 } 13747 13748 bool AddToScope = true; 13749 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 13750 TemplateParams, AddToScope); 13751 if (!ND) return nullptr; 13752 13753 assert(ND->getLexicalDeclContext() == CurContext); 13754 13755 // If we performed typo correction, we might have added a scope specifier 13756 // and changed the decl context. 13757 DC = ND->getDeclContext(); 13758 13759 // Add the function declaration to the appropriate lookup tables, 13760 // adjusting the redeclarations list as necessary. We don't 13761 // want to do this yet if the friending class is dependent. 13762 // 13763 // Also update the scope-based lookup if the target context's 13764 // lookup context is in lexical scope. 13765 if (!CurContext->isDependentContext()) { 13766 DC = DC->getRedeclContext(); 13767 DC->makeDeclVisibleInContext(ND); 13768 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13769 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 13770 } 13771 13772 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 13773 D.getIdentifierLoc(), ND, 13774 DS.getFriendSpecLoc()); 13775 FrD->setAccess(AS_public); 13776 CurContext->addDecl(FrD); 13777 13778 if (ND->isInvalidDecl()) { 13779 FrD->setInvalidDecl(); 13780 } else { 13781 if (DC->isRecord()) CheckFriendAccess(ND); 13782 13783 FunctionDecl *FD; 13784 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 13785 FD = FTD->getTemplatedDecl(); 13786 else 13787 FD = cast<FunctionDecl>(ND); 13788 13789 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 13790 // default argument expression, that declaration shall be a definition 13791 // and shall be the only declaration of the function or function 13792 // template in the translation unit. 13793 if (functionDeclHasDefaultArgument(FD)) { 13794 // We can't look at FD->getPreviousDecl() because it may not have been set 13795 // if we're in a dependent context. If the function is known to be a 13796 // redeclaration, we will have narrowed Previous down to the right decl. 13797 if (D.isRedeclaration()) { 13798 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 13799 Diag(Previous.getRepresentativeDecl()->getLocation(), 13800 diag::note_previous_declaration); 13801 } else if (!D.isFunctionDefinition()) 13802 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 13803 } 13804 13805 // Mark templated-scope function declarations as unsupported. 13806 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 13807 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 13808 << SS.getScopeRep() << SS.getRange() 13809 << cast<CXXRecordDecl>(CurContext); 13810 FrD->setUnsupportedFriend(true); 13811 } 13812 } 13813 13814 return ND; 13815 } 13816 13817 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 13818 AdjustDeclIfTemplate(Dcl); 13819 13820 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 13821 if (!Fn) { 13822 Diag(DelLoc, diag::err_deleted_non_function); 13823 return; 13824 } 13825 13826 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 13827 // Don't consider the implicit declaration we generate for explicit 13828 // specializations. FIXME: Do not generate these implicit declarations. 13829 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 13830 Prev->getPreviousDecl()) && 13831 !Prev->isDefined()) { 13832 Diag(DelLoc, diag::err_deleted_decl_not_first); 13833 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 13834 Prev->isImplicit() ? diag::note_previous_implicit_declaration 13835 : diag::note_previous_declaration); 13836 } 13837 // If the declaration wasn't the first, we delete the function anyway for 13838 // recovery. 13839 Fn = Fn->getCanonicalDecl(); 13840 } 13841 13842 // dllimport/dllexport cannot be deleted. 13843 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 13844 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 13845 Fn->setInvalidDecl(); 13846 } 13847 13848 if (Fn->isDeleted()) 13849 return; 13850 13851 // See if we're deleting a function which is already known to override a 13852 // non-deleted virtual function. 13853 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 13854 bool IssuedDiagnostic = false; 13855 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 13856 E = MD->end_overridden_methods(); 13857 I != E; ++I) { 13858 if (!(*MD->begin_overridden_methods())->isDeleted()) { 13859 if (!IssuedDiagnostic) { 13860 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 13861 IssuedDiagnostic = true; 13862 } 13863 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 13864 } 13865 } 13866 } 13867 13868 // C++11 [basic.start.main]p3: 13869 // A program that defines main as deleted [...] is ill-formed. 13870 if (Fn->isMain()) 13871 Diag(DelLoc, diag::err_deleted_main); 13872 13873 Fn->setDeletedAsWritten(); 13874 } 13875 13876 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 13877 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 13878 13879 if (MD) { 13880 if (MD->getParent()->isDependentType()) { 13881 MD->setDefaulted(); 13882 MD->setExplicitlyDefaulted(); 13883 return; 13884 } 13885 13886 CXXSpecialMember Member = getSpecialMember(MD); 13887 if (Member == CXXInvalid) { 13888 if (!MD->isInvalidDecl()) 13889 Diag(DefaultLoc, diag::err_default_special_members); 13890 return; 13891 } 13892 13893 MD->setDefaulted(); 13894 MD->setExplicitlyDefaulted(); 13895 13896 // If this definition appears within the record, do the checking when 13897 // the record is complete. 13898 const FunctionDecl *Primary = MD; 13899 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 13900 // Ask the template instantiation pattern that actually had the 13901 // '= default' on it. 13902 Primary = Pattern; 13903 13904 // If the method was defaulted on its first declaration, we will have 13905 // already performed the checking in CheckCompletedCXXClass. Such a 13906 // declaration doesn't trigger an implicit definition. 13907 if (Primary->getCanonicalDecl()->isDefaulted()) 13908 return; 13909 13910 CheckExplicitlyDefaultedSpecialMember(MD); 13911 13912 if (!MD->isInvalidDecl()) 13913 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 13914 } else { 13915 Diag(DefaultLoc, diag::err_default_special_members); 13916 } 13917 } 13918 13919 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 13920 for (Stmt *SubStmt : S->children()) { 13921 if (!SubStmt) 13922 continue; 13923 if (isa<ReturnStmt>(SubStmt)) 13924 Self.Diag(SubStmt->getLocStart(), 13925 diag::err_return_in_constructor_handler); 13926 if (!isa<Expr>(SubStmt)) 13927 SearchForReturnInStmt(Self, SubStmt); 13928 } 13929 } 13930 13931 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 13932 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 13933 CXXCatchStmt *Handler = TryBlock->getHandler(I); 13934 SearchForReturnInStmt(*this, Handler); 13935 } 13936 } 13937 13938 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 13939 const CXXMethodDecl *Old) { 13940 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 13941 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 13942 13943 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 13944 13945 // If the calling conventions match, everything is fine 13946 if (NewCC == OldCC) 13947 return false; 13948 13949 // If the calling conventions mismatch because the new function is static, 13950 // suppress the calling convention mismatch error; the error about static 13951 // function override (err_static_overrides_virtual from 13952 // Sema::CheckFunctionDeclaration) is more clear. 13953 if (New->getStorageClass() == SC_Static) 13954 return false; 13955 13956 Diag(New->getLocation(), 13957 diag::err_conflicting_overriding_cc_attributes) 13958 << New->getDeclName() << New->getType() << Old->getType(); 13959 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 13960 return true; 13961 } 13962 13963 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 13964 const CXXMethodDecl *Old) { 13965 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 13966 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 13967 13968 if (Context.hasSameType(NewTy, OldTy) || 13969 NewTy->isDependentType() || OldTy->isDependentType()) 13970 return false; 13971 13972 // Check if the return types are covariant 13973 QualType NewClassTy, OldClassTy; 13974 13975 /// Both types must be pointers or references to classes. 13976 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 13977 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 13978 NewClassTy = NewPT->getPointeeType(); 13979 OldClassTy = OldPT->getPointeeType(); 13980 } 13981 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 13982 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 13983 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 13984 NewClassTy = NewRT->getPointeeType(); 13985 OldClassTy = OldRT->getPointeeType(); 13986 } 13987 } 13988 } 13989 13990 // The return types aren't either both pointers or references to a class type. 13991 if (NewClassTy.isNull()) { 13992 Diag(New->getLocation(), 13993 diag::err_different_return_type_for_overriding_virtual_function) 13994 << New->getDeclName() << NewTy << OldTy 13995 << New->getReturnTypeSourceRange(); 13996 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13997 << Old->getReturnTypeSourceRange(); 13998 13999 return true; 14000 } 14001 14002 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14003 // C++14 [class.virtual]p8: 14004 // If the class type in the covariant return type of D::f differs from 14005 // that of B::f, the class type in the return type of D::f shall be 14006 // complete at the point of declaration of D::f or shall be the class 14007 // type D. 14008 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14009 if (!RT->isBeingDefined() && 14010 RequireCompleteType(New->getLocation(), NewClassTy, 14011 diag::err_covariant_return_incomplete, 14012 New->getDeclName())) 14013 return true; 14014 } 14015 14016 // Check if the new class derives from the old class. 14017 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14018 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14019 << New->getDeclName() << NewTy << OldTy 14020 << New->getReturnTypeSourceRange(); 14021 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14022 << Old->getReturnTypeSourceRange(); 14023 return true; 14024 } 14025 14026 // Check if we the conversion from derived to base is valid. 14027 if (CheckDerivedToBaseConversion( 14028 NewClassTy, OldClassTy, 14029 diag::err_covariant_return_inaccessible_base, 14030 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14031 New->getLocation(), New->getReturnTypeSourceRange(), 14032 New->getDeclName(), nullptr)) { 14033 // FIXME: this note won't trigger for delayed access control 14034 // diagnostics, and it's impossible to get an undelayed error 14035 // here from access control during the original parse because 14036 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14037 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14038 << Old->getReturnTypeSourceRange(); 14039 return true; 14040 } 14041 } 14042 14043 // The qualifiers of the return types must be the same. 14044 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14045 Diag(New->getLocation(), 14046 diag::err_covariant_return_type_different_qualifications) 14047 << New->getDeclName() << NewTy << OldTy 14048 << New->getReturnTypeSourceRange(); 14049 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14050 << Old->getReturnTypeSourceRange(); 14051 return true; 14052 } 14053 14054 14055 // The new class type must have the same or less qualifiers as the old type. 14056 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14057 Diag(New->getLocation(), 14058 diag::err_covariant_return_type_class_type_more_qualified) 14059 << New->getDeclName() << NewTy << OldTy 14060 << New->getReturnTypeSourceRange(); 14061 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14062 << Old->getReturnTypeSourceRange(); 14063 return true; 14064 } 14065 14066 return false; 14067 } 14068 14069 /// \brief Mark the given method pure. 14070 /// 14071 /// \param Method the method to be marked pure. 14072 /// 14073 /// \param InitRange the source range that covers the "0" initializer. 14074 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14075 SourceLocation EndLoc = InitRange.getEnd(); 14076 if (EndLoc.isValid()) 14077 Method->setRangeEnd(EndLoc); 14078 14079 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14080 Method->setPure(); 14081 return false; 14082 } 14083 14084 if (!Method->isInvalidDecl()) 14085 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14086 << Method->getDeclName() << InitRange; 14087 return true; 14088 } 14089 14090 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14091 if (D->getFriendObjectKind()) 14092 Diag(D->getLocation(), diag::err_pure_friend); 14093 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14094 CheckPureMethod(M, ZeroLoc); 14095 else 14096 Diag(D->getLocation(), diag::err_illegal_initializer); 14097 } 14098 14099 /// \brief Determine whether the given declaration is a static data member. 14100 static bool isStaticDataMember(const Decl *D) { 14101 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14102 return Var->isStaticDataMember(); 14103 14104 return false; 14105 } 14106 14107 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 14108 /// an initializer for the out-of-line declaration 'Dcl'. The scope 14109 /// is a fresh scope pushed for just this purpose. 14110 /// 14111 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14112 /// static data member of class X, names should be looked up in the scope of 14113 /// class X. 14114 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14115 // If there is no declaration, there was an error parsing it. 14116 if (!D || D->isInvalidDecl()) 14117 return; 14118 14119 // We will always have a nested name specifier here, but this declaration 14120 // might not be out of line if the specifier names the current namespace: 14121 // extern int n; 14122 // int ::n = 0; 14123 if (D->isOutOfLine()) 14124 EnterDeclaratorContext(S, D->getDeclContext()); 14125 14126 // If we are parsing the initializer for a static data member, push a 14127 // new expression evaluation context that is associated with this static 14128 // data member. 14129 if (isStaticDataMember(D)) 14130 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 14131 } 14132 14133 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 14134 /// initializer for the out-of-line declaration 'D'. 14135 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14136 // If there is no declaration, there was an error parsing it. 14137 if (!D || D->isInvalidDecl()) 14138 return; 14139 14140 if (isStaticDataMember(D)) 14141 PopExpressionEvaluationContext(); 14142 14143 if (D->isOutOfLine()) 14144 ExitDeclaratorContext(S); 14145 } 14146 14147 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14148 /// C++ if/switch/while/for statement. 14149 /// e.g: "if (int x = f()) {...}" 14150 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14151 // C++ 6.4p2: 14152 // The declarator shall not specify a function or an array. 14153 // The type-specifier-seq shall not contain typedef and shall not declare a 14154 // new class or enumeration. 14155 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14156 "Parser allowed 'typedef' as storage class of condition decl."); 14157 14158 Decl *Dcl = ActOnDeclarator(S, D); 14159 if (!Dcl) 14160 return true; 14161 14162 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14163 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14164 << D.getSourceRange(); 14165 return true; 14166 } 14167 14168 return Dcl; 14169 } 14170 14171 void Sema::LoadExternalVTableUses() { 14172 if (!ExternalSource) 14173 return; 14174 14175 SmallVector<ExternalVTableUse, 4> VTables; 14176 ExternalSource->ReadUsedVTables(VTables); 14177 SmallVector<VTableUse, 4> NewUses; 14178 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14179 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14180 = VTablesUsed.find(VTables[I].Record); 14181 // Even if a definition wasn't required before, it may be required now. 14182 if (Pos != VTablesUsed.end()) { 14183 if (!Pos->second && VTables[I].DefinitionRequired) 14184 Pos->second = true; 14185 continue; 14186 } 14187 14188 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14189 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14190 } 14191 14192 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14193 } 14194 14195 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14196 bool DefinitionRequired) { 14197 // Ignore any vtable uses in unevaluated operands or for classes that do 14198 // not have a vtable. 14199 if (!Class->isDynamicClass() || Class->isDependentContext() || 14200 CurContext->isDependentContext() || isUnevaluatedContext()) 14201 return; 14202 14203 // Try to insert this class into the map. 14204 LoadExternalVTableUses(); 14205 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14206 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14207 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14208 if (!Pos.second) { 14209 // If we already had an entry, check to see if we are promoting this vtable 14210 // to require a definition. If so, we need to reappend to the VTableUses 14211 // list, since we may have already processed the first entry. 14212 if (DefinitionRequired && !Pos.first->second) { 14213 Pos.first->second = true; 14214 } else { 14215 // Otherwise, we can early exit. 14216 return; 14217 } 14218 } else { 14219 // The Microsoft ABI requires that we perform the destructor body 14220 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14221 // the deleting destructor is emitted with the vtable, not with the 14222 // destructor definition as in the Itanium ABI. 14223 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14224 CXXDestructorDecl *DD = Class->getDestructor(); 14225 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14226 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14227 // If this is an out-of-line declaration, marking it referenced will 14228 // not do anything. Manually call CheckDestructor to look up operator 14229 // delete(). 14230 ContextRAII SavedContext(*this, DD); 14231 CheckDestructor(DD); 14232 } else { 14233 MarkFunctionReferenced(Loc, Class->getDestructor()); 14234 } 14235 } 14236 } 14237 } 14238 14239 // Local classes need to have their virtual members marked 14240 // immediately. For all other classes, we mark their virtual members 14241 // at the end of the translation unit. 14242 if (Class->isLocalClass()) 14243 MarkVirtualMembersReferenced(Loc, Class); 14244 else 14245 VTableUses.push_back(std::make_pair(Class, Loc)); 14246 } 14247 14248 bool Sema::DefineUsedVTables() { 14249 LoadExternalVTableUses(); 14250 if (VTableUses.empty()) 14251 return false; 14252 14253 // Note: The VTableUses vector could grow as a result of marking 14254 // the members of a class as "used", so we check the size each 14255 // time through the loop and prefer indices (which are stable) to 14256 // iterators (which are not). 14257 bool DefinedAnything = false; 14258 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14259 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14260 if (!Class) 14261 continue; 14262 14263 SourceLocation Loc = VTableUses[I].second; 14264 14265 bool DefineVTable = true; 14266 14267 // If this class has a key function, but that key function is 14268 // defined in another translation unit, we don't need to emit the 14269 // vtable even though we're using it. 14270 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14271 if (KeyFunction && !KeyFunction->hasBody()) { 14272 // The key function is in another translation unit. 14273 DefineVTable = false; 14274 TemplateSpecializationKind TSK = 14275 KeyFunction->getTemplateSpecializationKind(); 14276 assert(TSK != TSK_ExplicitInstantiationDefinition && 14277 TSK != TSK_ImplicitInstantiation && 14278 "Instantiations don't have key functions"); 14279 (void)TSK; 14280 } else if (!KeyFunction) { 14281 // If we have a class with no key function that is the subject 14282 // of an explicit instantiation declaration, suppress the 14283 // vtable; it will live with the explicit instantiation 14284 // definition. 14285 bool IsExplicitInstantiationDeclaration 14286 = Class->getTemplateSpecializationKind() 14287 == TSK_ExplicitInstantiationDeclaration; 14288 for (auto R : Class->redecls()) { 14289 TemplateSpecializationKind TSK 14290 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14291 if (TSK == TSK_ExplicitInstantiationDeclaration) 14292 IsExplicitInstantiationDeclaration = true; 14293 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14294 IsExplicitInstantiationDeclaration = false; 14295 break; 14296 } 14297 } 14298 14299 if (IsExplicitInstantiationDeclaration) 14300 DefineVTable = false; 14301 } 14302 14303 // The exception specifications for all virtual members may be needed even 14304 // if we are not providing an authoritative form of the vtable in this TU. 14305 // We may choose to emit it available_externally anyway. 14306 if (!DefineVTable) { 14307 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14308 continue; 14309 } 14310 14311 // Mark all of the virtual members of this class as referenced, so 14312 // that we can build a vtable. Then, tell the AST consumer that a 14313 // vtable for this class is required. 14314 DefinedAnything = true; 14315 MarkVirtualMembersReferenced(Loc, Class); 14316 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14317 if (VTablesUsed[Canonical]) 14318 Consumer.HandleVTable(Class); 14319 14320 // Optionally warn if we're emitting a weak vtable. 14321 if (Class->isExternallyVisible() && 14322 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 14323 const FunctionDecl *KeyFunctionDef = nullptr; 14324 if (!KeyFunction || 14325 (KeyFunction->hasBody(KeyFunctionDef) && 14326 KeyFunctionDef->isInlined())) 14327 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 14328 TSK_ExplicitInstantiationDefinition 14329 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 14330 << Class; 14331 } 14332 } 14333 VTableUses.clear(); 14334 14335 return DefinedAnything; 14336 } 14337 14338 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14339 const CXXRecordDecl *RD) { 14340 for (const auto *I : RD->methods()) 14341 if (I->isVirtual() && !I->isPure()) 14342 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14343 } 14344 14345 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14346 const CXXRecordDecl *RD) { 14347 // Mark all functions which will appear in RD's vtable as used. 14348 CXXFinalOverriderMap FinalOverriders; 14349 RD->getFinalOverriders(FinalOverriders); 14350 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14351 E = FinalOverriders.end(); 14352 I != E; ++I) { 14353 for (OverridingMethods::const_iterator OI = I->second.begin(), 14354 OE = I->second.end(); 14355 OI != OE; ++OI) { 14356 assert(OI->second.size() > 0 && "no final overrider"); 14357 CXXMethodDecl *Overrider = OI->second.front().Method; 14358 14359 // C++ [basic.def.odr]p2: 14360 // [...] A virtual member function is used if it is not pure. [...] 14361 if (!Overrider->isPure()) 14362 MarkFunctionReferenced(Loc, Overrider); 14363 } 14364 } 14365 14366 // Only classes that have virtual bases need a VTT. 14367 if (RD->getNumVBases() == 0) 14368 return; 14369 14370 for (const auto &I : RD->bases()) { 14371 const CXXRecordDecl *Base = 14372 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14373 if (Base->getNumVBases() == 0) 14374 continue; 14375 MarkVirtualMembersReferenced(Loc, Base); 14376 } 14377 } 14378 14379 /// SetIvarInitializers - This routine builds initialization ASTs for the 14380 /// Objective-C implementation whose ivars need be initialized. 14381 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14382 if (!getLangOpts().CPlusPlus) 14383 return; 14384 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14385 SmallVector<ObjCIvarDecl*, 8> ivars; 14386 CollectIvarsToConstructOrDestruct(OID, ivars); 14387 if (ivars.empty()) 14388 return; 14389 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14390 for (unsigned i = 0; i < ivars.size(); i++) { 14391 FieldDecl *Field = ivars[i]; 14392 if (Field->isInvalidDecl()) 14393 continue; 14394 14395 CXXCtorInitializer *Member; 14396 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14397 InitializationKind InitKind = 14398 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14399 14400 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14401 ExprResult MemberInit = 14402 InitSeq.Perform(*this, InitEntity, InitKind, None); 14403 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14404 // Note, MemberInit could actually come back empty if no initialization 14405 // is required (e.g., because it would call a trivial default constructor) 14406 if (!MemberInit.get() || MemberInit.isInvalid()) 14407 continue; 14408 14409 Member = 14410 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14411 SourceLocation(), 14412 MemberInit.getAs<Expr>(), 14413 SourceLocation()); 14414 AllToInit.push_back(Member); 14415 14416 // Be sure that the destructor is accessible and is marked as referenced. 14417 if (const RecordType *RecordTy = 14418 Context.getBaseElementType(Field->getType()) 14419 ->getAs<RecordType>()) { 14420 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14421 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14422 MarkFunctionReferenced(Field->getLocation(), Destructor); 14423 CheckDestructorAccess(Field->getLocation(), Destructor, 14424 PDiag(diag::err_access_dtor_ivar) 14425 << Context.getBaseElementType(Field->getType())); 14426 } 14427 } 14428 } 14429 ObjCImplementation->setIvarInitializers(Context, 14430 AllToInit.data(), AllToInit.size()); 14431 } 14432 } 14433 14434 static 14435 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14436 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14437 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14438 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14439 Sema &S) { 14440 if (Ctor->isInvalidDecl()) 14441 return; 14442 14443 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14444 14445 // Target may not be determinable yet, for instance if this is a dependent 14446 // call in an uninstantiated template. 14447 if (Target) { 14448 const FunctionDecl *FNTarget = nullptr; 14449 (void)Target->hasBody(FNTarget); 14450 Target = const_cast<CXXConstructorDecl*>( 14451 cast_or_null<CXXConstructorDecl>(FNTarget)); 14452 } 14453 14454 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14455 // Avoid dereferencing a null pointer here. 14456 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14457 14458 if (!Current.insert(Canonical).second) 14459 return; 14460 14461 // We know that beyond here, we aren't chaining into a cycle. 14462 if (!Target || !Target->isDelegatingConstructor() || 14463 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14464 Valid.insert(Current.begin(), Current.end()); 14465 Current.clear(); 14466 // We've hit a cycle. 14467 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14468 Current.count(TCanonical)) { 14469 // If we haven't diagnosed this cycle yet, do so now. 14470 if (!Invalid.count(TCanonical)) { 14471 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14472 diag::warn_delegating_ctor_cycle) 14473 << Ctor; 14474 14475 // Don't add a note for a function delegating directly to itself. 14476 if (TCanonical != Canonical) 14477 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14478 14479 CXXConstructorDecl *C = Target; 14480 while (C->getCanonicalDecl() != Canonical) { 14481 const FunctionDecl *FNTarget = nullptr; 14482 (void)C->getTargetConstructor()->hasBody(FNTarget); 14483 assert(FNTarget && "Ctor cycle through bodiless function"); 14484 14485 C = const_cast<CXXConstructorDecl*>( 14486 cast<CXXConstructorDecl>(FNTarget)); 14487 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14488 } 14489 } 14490 14491 Invalid.insert(Current.begin(), Current.end()); 14492 Current.clear(); 14493 } else { 14494 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14495 } 14496 } 14497 14498 14499 void Sema::CheckDelegatingCtorCycles() { 14500 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14501 14502 for (DelegatingCtorDeclsType::iterator 14503 I = DelegatingCtorDecls.begin(ExternalSource), 14504 E = DelegatingCtorDecls.end(); 14505 I != E; ++I) 14506 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14507 14508 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14509 CE = Invalid.end(); 14510 CI != CE; ++CI) 14511 (*CI)->setInvalidDecl(); 14512 } 14513 14514 namespace { 14515 /// \brief AST visitor that finds references to the 'this' expression. 14516 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14517 Sema &S; 14518 14519 public: 14520 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14521 14522 bool VisitCXXThisExpr(CXXThisExpr *E) { 14523 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14524 << E->isImplicit(); 14525 return false; 14526 } 14527 }; 14528 } 14529 14530 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14531 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14532 if (!TSInfo) 14533 return false; 14534 14535 TypeLoc TL = TSInfo->getTypeLoc(); 14536 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14537 if (!ProtoTL) 14538 return false; 14539 14540 // C++11 [expr.prim.general]p3: 14541 // [The expression this] shall not appear before the optional 14542 // cv-qualifier-seq and it shall not appear within the declaration of a 14543 // static member function (although its type and value category are defined 14544 // within a static member function as they are within a non-static member 14545 // function). [ Note: this is because declaration matching does not occur 14546 // until the complete declarator is known. - end note ] 14547 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14548 FindCXXThisExpr Finder(*this); 14549 14550 // If the return type came after the cv-qualifier-seq, check it now. 14551 if (Proto->hasTrailingReturn() && 14552 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14553 return true; 14554 14555 // Check the exception specification. 14556 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14557 return true; 14558 14559 return checkThisInStaticMemberFunctionAttributes(Method); 14560 } 14561 14562 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14563 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14564 if (!TSInfo) 14565 return false; 14566 14567 TypeLoc TL = TSInfo->getTypeLoc(); 14568 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14569 if (!ProtoTL) 14570 return false; 14571 14572 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14573 FindCXXThisExpr Finder(*this); 14574 14575 switch (Proto->getExceptionSpecType()) { 14576 case EST_Unparsed: 14577 case EST_Uninstantiated: 14578 case EST_Unevaluated: 14579 case EST_BasicNoexcept: 14580 case EST_DynamicNone: 14581 case EST_MSAny: 14582 case EST_None: 14583 break; 14584 14585 case EST_ComputedNoexcept: 14586 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14587 return true; 14588 14589 case EST_Dynamic: 14590 for (const auto &E : Proto->exceptions()) { 14591 if (!Finder.TraverseType(E)) 14592 return true; 14593 } 14594 break; 14595 } 14596 14597 return false; 14598 } 14599 14600 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14601 FindCXXThisExpr Finder(*this); 14602 14603 // Check attributes. 14604 for (const auto *A : Method->attrs()) { 14605 // FIXME: This should be emitted by tblgen. 14606 Expr *Arg = nullptr; 14607 ArrayRef<Expr *> Args; 14608 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14609 Arg = G->getArg(); 14610 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14611 Arg = G->getArg(); 14612 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14613 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14614 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14615 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14616 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14617 Arg = ETLF->getSuccessValue(); 14618 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14619 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14620 Arg = STLF->getSuccessValue(); 14621 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14622 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14623 Arg = LR->getArg(); 14624 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14625 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14626 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14627 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14628 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14629 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14630 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14631 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14632 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14633 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14634 14635 if (Arg && !Finder.TraverseStmt(Arg)) 14636 return true; 14637 14638 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14639 if (!Finder.TraverseStmt(Args[I])) 14640 return true; 14641 } 14642 } 14643 14644 return false; 14645 } 14646 14647 void Sema::checkExceptionSpecification( 14648 bool IsTopLevel, ExceptionSpecificationType EST, 14649 ArrayRef<ParsedType> DynamicExceptions, 14650 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 14651 SmallVectorImpl<QualType> &Exceptions, 14652 FunctionProtoType::ExceptionSpecInfo &ESI) { 14653 Exceptions.clear(); 14654 ESI.Type = EST; 14655 if (EST == EST_Dynamic) { 14656 Exceptions.reserve(DynamicExceptions.size()); 14657 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 14658 // FIXME: Preserve type source info. 14659 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 14660 14661 if (IsTopLevel) { 14662 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 14663 collectUnexpandedParameterPacks(ET, Unexpanded); 14664 if (!Unexpanded.empty()) { 14665 DiagnoseUnexpandedParameterPacks( 14666 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 14667 Unexpanded); 14668 continue; 14669 } 14670 } 14671 14672 // Check that the type is valid for an exception spec, and 14673 // drop it if not. 14674 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 14675 Exceptions.push_back(ET); 14676 } 14677 ESI.Exceptions = Exceptions; 14678 return; 14679 } 14680 14681 if (EST == EST_ComputedNoexcept) { 14682 // If an error occurred, there's no expression here. 14683 if (NoexceptExpr) { 14684 assert((NoexceptExpr->isTypeDependent() || 14685 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 14686 Context.BoolTy) && 14687 "Parser should have made sure that the expression is boolean"); 14688 if (IsTopLevel && NoexceptExpr && 14689 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 14690 ESI.Type = EST_BasicNoexcept; 14691 return; 14692 } 14693 14694 if (!NoexceptExpr->isValueDependent()) 14695 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 14696 diag::err_noexcept_needs_constant_expression, 14697 /*AllowFold*/ false).get(); 14698 ESI.NoexceptExpr = NoexceptExpr; 14699 } 14700 return; 14701 } 14702 } 14703 14704 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 14705 ExceptionSpecificationType EST, 14706 SourceRange SpecificationRange, 14707 ArrayRef<ParsedType> DynamicExceptions, 14708 ArrayRef<SourceRange> DynamicExceptionRanges, 14709 Expr *NoexceptExpr) { 14710 if (!MethodD) 14711 return; 14712 14713 // Dig out the method we're referring to. 14714 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 14715 MethodD = FunTmpl->getTemplatedDecl(); 14716 14717 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 14718 if (!Method) 14719 return; 14720 14721 // Check the exception specification. 14722 llvm::SmallVector<QualType, 4> Exceptions; 14723 FunctionProtoType::ExceptionSpecInfo ESI; 14724 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 14725 DynamicExceptionRanges, NoexceptExpr, Exceptions, 14726 ESI); 14727 14728 // Update the exception specification on the function type. 14729 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 14730 14731 if (Method->isStatic()) 14732 checkThisInStaticMemberFunctionExceptionSpec(Method); 14733 14734 if (Method->isVirtual()) { 14735 // Check overrides, which we previously had to delay. 14736 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 14737 OEnd = Method->end_overridden_methods(); 14738 O != OEnd; ++O) 14739 CheckOverridingFunctionExceptionSpec(Method, *O); 14740 } 14741 } 14742 14743 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 14744 /// 14745 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 14746 SourceLocation DeclStart, 14747 Declarator &D, Expr *BitWidth, 14748 InClassInitStyle InitStyle, 14749 AccessSpecifier AS, 14750 AttributeList *MSPropertyAttr) { 14751 IdentifierInfo *II = D.getIdentifier(); 14752 if (!II) { 14753 Diag(DeclStart, diag::err_anonymous_property); 14754 return nullptr; 14755 } 14756 SourceLocation Loc = D.getIdentifierLoc(); 14757 14758 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14759 QualType T = TInfo->getType(); 14760 if (getLangOpts().CPlusPlus) { 14761 CheckExtraCXXDefaultArguments(D); 14762 14763 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14764 UPPC_DataMemberType)) { 14765 D.setInvalidType(); 14766 T = Context.IntTy; 14767 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14768 } 14769 } 14770 14771 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14772 14773 if (D.getDeclSpec().isInlineSpecified()) 14774 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14775 << getLangOpts().CPlusPlus1z; 14776 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14777 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14778 diag::err_invalid_thread) 14779 << DeclSpec::getSpecifierName(TSCS); 14780 14781 // Check to see if this name was declared as a member previously 14782 NamedDecl *PrevDecl = nullptr; 14783 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14784 LookupName(Previous, S); 14785 switch (Previous.getResultKind()) { 14786 case LookupResult::Found: 14787 case LookupResult::FoundUnresolvedValue: 14788 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14789 break; 14790 14791 case LookupResult::FoundOverloaded: 14792 PrevDecl = Previous.getRepresentativeDecl(); 14793 break; 14794 14795 case LookupResult::NotFound: 14796 case LookupResult::NotFoundInCurrentInstantiation: 14797 case LookupResult::Ambiguous: 14798 break; 14799 } 14800 14801 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14802 // Maybe we will complain about the shadowed template parameter. 14803 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14804 // Just pretend that we didn't see the previous declaration. 14805 PrevDecl = nullptr; 14806 } 14807 14808 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14809 PrevDecl = nullptr; 14810 14811 SourceLocation TSSL = D.getLocStart(); 14812 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 14813 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 14814 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 14815 ProcessDeclAttributes(TUScope, NewPD, D); 14816 NewPD->setAccess(AS); 14817 14818 if (NewPD->isInvalidDecl()) 14819 Record->setInvalidDecl(); 14820 14821 if (D.getDeclSpec().isModulePrivateSpecified()) 14822 NewPD->setModulePrivate(); 14823 14824 if (NewPD->isInvalidDecl() && PrevDecl) { 14825 // Don't introduce NewFD into scope; there's already something 14826 // with the same name in the same scope. 14827 } else if (II) { 14828 PushOnScopeChains(NewPD, S); 14829 } else 14830 Record->addDecl(NewPD); 14831 14832 return NewPD; 14833 } 14834