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/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt *SubStmt : Node->children()) 77 IsInvalid |= Visit(SubStmt); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If we have a throw-all spec at this point, ignore the function. 166 if (ComputedEST == EST_None) 167 return; 168 169 switch(EST) { 170 // If this function can throw any exceptions, make a note of that. 171 case EST_MSAny: 172 case EST_None: 173 ClearExceptions(); 174 ComputedEST = EST; 175 return; 176 // FIXME: If the call to this decl is using any of its default arguments, we 177 // need to search them for potentially-throwing calls. 178 // If this function has a basic noexcept, it doesn't affect the outcome. 179 case EST_BasicNoexcept: 180 return; 181 // If we're still at noexcept(true) and there's a nothrow() callee, 182 // change to that specification. 183 case EST_DynamicNone: 184 if (ComputedEST == EST_BasicNoexcept) 185 ComputedEST = EST_DynamicNone; 186 return; 187 // Check out noexcept specs. 188 case EST_ComputedNoexcept: 189 { 190 FunctionProtoType::NoexceptResult NR = 191 Proto->getNoexceptSpec(Self->Context); 192 assert(NR != FunctionProtoType::NR_NoNoexcept && 193 "Must have noexcept result for EST_ComputedNoexcept."); 194 assert(NR != FunctionProtoType::NR_Dependent && 195 "Should not generate implicit declarations for dependent cases, " 196 "and don't know how to handle them anyway."); 197 // noexcept(false) -> no spec on the new function 198 if (NR == FunctionProtoType::NR_Throw) { 199 ClearExceptions(); 200 ComputedEST = EST_None; 201 } 202 // noexcept(true) won't change anything either. 203 return; 204 } 205 default: 206 break; 207 } 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (const auto &E : Proto->exceptions()) 214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 215 Exceptions.push_back(E); 216 } 217 218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 219 if (!E || ComputedEST == EST_MSAny) 220 return; 221 222 // FIXME: 223 // 224 // C++0x [except.spec]p14: 225 // [An] implicit exception-specification specifies the type-id T if and 226 // only if T is allowed by the exception-specification of a function directly 227 // invoked by f's implicit definition; f shall allow all exceptions if any 228 // function it directly invokes allows all exceptions, and f shall allow no 229 // exceptions if every function it directly invokes allows no exceptions. 230 // 231 // Note in particular that if an implicit exception-specification is generated 232 // for a function containing a throw-expression, that specification can still 233 // be noexcept(true). 234 // 235 // Note also that 'directly invoked' is not defined in the standard, and there 236 // is no indication that we should only consider potentially-evaluated calls. 237 // 238 // Ultimately we should implement the intent of the standard: the exception 239 // specification should be the set of exceptions which can be thrown by the 240 // implicit definition. For now, we assume that any non-nothrow expression can 241 // throw any exception. 242 243 if (Self->canThrow(E)) 244 ComputedEST = EST_None; 245 } 246 247 bool 248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 249 SourceLocation EqualLoc) { 250 if (RequireCompleteType(Param->getLocation(), Param->getType(), 251 diag::err_typecheck_decl_incomplete_type)) { 252 Param->setInvalidDecl(); 253 return true; 254 } 255 256 // C++ [dcl.fct.default]p5 257 // A default argument expression is implicitly converted (clause 258 // 4) to the parameter type. The default argument expression has 259 // the same semantic constraints as the initializer expression in 260 // a declaration of a variable of the parameter type, using the 261 // copy-initialization semantics (8.5). 262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 263 Param); 264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 265 EqualLoc); 266 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 268 if (Result.isInvalid()) 269 return true; 270 Arg = Result.getAs<Expr>(); 271 272 CheckCompletedExpr(Arg, EqualLoc); 273 Arg = MaybeCreateExprWithCleanups(Arg); 274 275 // Okay: add the default argument to the parameter 276 Param->setDefaultArg(Arg); 277 278 // We have already instantiated this parameter; provide each of the 279 // instantiations with the uninstantiated default argument. 280 UnparsedDefaultArgInstantiationsMap::iterator InstPos 281 = UnparsedDefaultArgInstantiations.find(Param); 282 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 285 286 // We're done tracking this parameter's instantiations. 287 UnparsedDefaultArgInstantiations.erase(InstPos); 288 } 289 290 return false; 291 } 292 293 /// ActOnParamDefaultArgument - Check whether the default argument 294 /// provided for a function parameter is well-formed. If so, attach it 295 /// to the parameter declaration. 296 void 297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 298 Expr *DefaultArg) { 299 if (!param || !DefaultArg) 300 return; 301 302 ParmVarDecl *Param = cast<ParmVarDecl>(param); 303 UnparsedDefaultArgLocs.erase(Param); 304 305 // Default arguments are only permitted in C++ 306 if (!getLangOpts().CPlusPlus) { 307 Diag(EqualLoc, diag::err_param_default_argument) 308 << DefaultArg->getSourceRange(); 309 Param->setInvalidDecl(); 310 return; 311 } 312 313 // Check for unexpanded parameter packs. 314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 315 Param->setInvalidDecl(); 316 return; 317 } 318 319 // C++11 [dcl.fct.default]p3 320 // A default argument expression [...] shall not be specified for a 321 // parameter pack. 322 if (Param->isParameterPack()) { 323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 324 << DefaultArg->getSourceRange(); 325 return; 326 } 327 328 // Check that the default argument is well-formed 329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 330 if (DefaultArgChecker.Visit(DefaultArg)) { 331 Param->setInvalidDecl(); 332 return; 333 } 334 335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 336 } 337 338 /// ActOnParamUnparsedDefaultArgument - We've seen a default 339 /// argument for a function parameter, but we can't parse it yet 340 /// because we're inside a class definition. Note that this default 341 /// argument will be parsed later. 342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 343 SourceLocation EqualLoc, 344 SourceLocation ArgLoc) { 345 if (!param) 346 return; 347 348 ParmVarDecl *Param = cast<ParmVarDecl>(param); 349 Param->setUnparsedDefaultArg(); 350 UnparsedDefaultArgLocs[Param] = ArgLoc; 351 } 352 353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 354 /// the default argument for the parameter param failed. 355 void Sema::ActOnParamDefaultArgumentError(Decl *param, 356 SourceLocation EqualLoc) { 357 if (!param) 358 return; 359 360 ParmVarDecl *Param = cast<ParmVarDecl>(param); 361 Param->setInvalidDecl(); 362 UnparsedDefaultArgLocs.erase(Param); 363 Param->setDefaultArg(new(Context) 364 OpaqueValueExpr(EqualLoc, 365 Param->getType().getNonReferenceType(), 366 VK_RValue)); 367 } 368 369 /// CheckExtraCXXDefaultArguments - Check for any extra default 370 /// arguments in the declarator, which is not a function declaration 371 /// or definition and therefore is not permitted to have default 372 /// arguments. This routine should be invoked for every declarator 373 /// that is not a function declaration or definition. 374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 375 // C++ [dcl.fct.default]p3 376 // A default argument expression shall be specified only in the 377 // parameter-declaration-clause of a function declaration or in a 378 // template-parameter (14.1). It shall not be specified for a 379 // parameter pack. If it is specified in a 380 // parameter-declaration-clause, it shall not occur within a 381 // declarator or abstract-declarator of a parameter-declaration. 382 bool MightBeFunction = D.isFunctionDeclarationContext(); 383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 384 DeclaratorChunk &chunk = D.getTypeObject(i); 385 if (chunk.Kind == DeclaratorChunk::Function) { 386 if (MightBeFunction) { 387 // This is a function declaration. It can have default arguments, but 388 // keep looking in case its return type is a function type with default 389 // arguments. 390 MightBeFunction = false; 391 continue; 392 } 393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 394 ++argIdx) { 395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 396 if (Param->hasUnparsedDefaultArg()) { 397 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 398 SourceRange SR; 399 if (Toks->size() > 1) 400 SR = SourceRange((*Toks)[1].getLocation(), 401 Toks->back().getLocation()); 402 else 403 SR = UnparsedDefaultArgLocs[Param]; 404 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 405 << SR; 406 delete Toks; 407 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficent, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found our guy. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter. 551 // It's important to use getInit() here; getDefaultArg() 552 // strips off any top-level ExprWithCleanups. 553 NewParam->setHasInheritedDefaultArg(); 554 if (OldParam->hasUnparsedDefaultArg()) 555 NewParam->setUnparsedDefaultArg(); 556 else if (OldParam->hasUninstantiatedDefaultArg()) 557 NewParam->setUninstantiatedDefaultArg( 558 OldParam->getUninstantiatedDefaultArg()); 559 else 560 NewParam->setDefaultArg(OldParam->getInit()); 561 } else if (NewParamHasDfl) { 562 if (New->getDescribedFunctionTemplate()) { 563 // Paragraph 4, quoted above, only applies to non-template functions. 564 Diag(NewParam->getLocation(), 565 diag::err_param_default_argument_template_redecl) 566 << NewParam->getDefaultArgRange(); 567 Diag(PrevForDefaultArgs->getLocation(), 568 diag::note_template_prev_declaration) 569 << false; 570 } else if (New->getTemplateSpecializationKind() 571 != TSK_ImplicitInstantiation && 572 New->getTemplateSpecializationKind() != TSK_Undeclared) { 573 // C++ [temp.expr.spec]p21: 574 // Default function arguments shall not be specified in a declaration 575 // or a definition for one of the following explicit specializations: 576 // - the explicit specialization of a function template; 577 // - the explicit specialization of a member function template; 578 // - the explicit specialization of a member function of a class 579 // template where the class template specialization to which the 580 // member function specialization belongs is implicitly 581 // instantiated. 582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 584 << New->getDeclName() 585 << NewParam->getDefaultArgRange(); 586 } else if (New->getDeclContext()->isDependentContext()) { 587 // C++ [dcl.fct.default]p6 (DR217): 588 // Default arguments for a member function of a class template shall 589 // be specified on the initial declaration of the member function 590 // within the class template. 591 // 592 // Reading the tea leaves a bit in DR217 and its reference to DR205 593 // leads me to the conclusion that one cannot add default function 594 // arguments for an out-of-line definition of a member function of a 595 // dependent type. 596 int WhichKind = 2; 597 if (CXXRecordDecl *Record 598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 599 if (Record->getDescribedClassTemplate()) 600 WhichKind = 0; 601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 602 WhichKind = 1; 603 else 604 WhichKind = 2; 605 } 606 607 Diag(NewParam->getLocation(), 608 diag::err_param_default_argument_member_template_redecl) 609 << WhichKind 610 << NewParam->getDefaultArgRange(); 611 } 612 } 613 } 614 615 // DR1344: If a default argument is added outside a class definition and that 616 // default argument makes the function a special member function, the program 617 // is ill-formed. This can only happen for constructors. 618 if (isa<CXXConstructorDecl>(New) && 619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 622 if (NewSM != OldSM) { 623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 624 assert(NewParam->hasDefaultArg()); 625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 626 << NewParam->getDefaultArgRange() << NewSM; 627 Diag(Old->getLocation(), diag::note_previous_declaration); 628 } 629 } 630 631 const FunctionDecl *Def; 632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 633 // template has a constexpr specifier then all its declarations shall 634 // contain the constexpr specifier. 635 if (New->isConstexpr() != Old->isConstexpr()) { 636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 637 << New << New->isConstexpr(); 638 Diag(Old->getLocation(), diag::note_previous_declaration); 639 Invalid = true; 640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 641 Old->isDefined(Def)) { 642 // C++11 [dcl.fcn.spec]p4: 643 // If the definition of a function appears in a translation unit before its 644 // first declaration as inline, the program is ill-formed. 645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 646 Diag(Def->getLocation(), diag::note_previous_definition); 647 Invalid = true; 648 } 649 650 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 651 // argument expression, that declaration shall be a definition and shall be 652 // the only declaration of the function or function template in the 653 // translation unit. 654 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 655 functionDeclHasDefaultArgument(Old)) { 656 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 657 Diag(Old->getLocation(), diag::note_previous_declaration); 658 Invalid = true; 659 } 660 661 if (CheckEquivalentExceptionSpec(Old, New)) 662 Invalid = true; 663 664 return Invalid; 665 } 666 667 /// \brief Merge the exception specifications of two variable declarations. 668 /// 669 /// This is called when there's a redeclaration of a VarDecl. The function 670 /// checks if the redeclaration might have an exception specification and 671 /// validates compatibility and merges the specs if necessary. 672 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 673 // Shortcut if exceptions are disabled. 674 if (!getLangOpts().CXXExceptions) 675 return; 676 677 assert(Context.hasSameType(New->getType(), Old->getType()) && 678 "Should only be called if types are otherwise the same."); 679 680 QualType NewType = New->getType(); 681 QualType OldType = Old->getType(); 682 683 // We're only interested in pointers and references to functions, as well 684 // as pointers to member functions. 685 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 686 NewType = R->getPointeeType(); 687 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 688 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 689 NewType = P->getPointeeType(); 690 OldType = OldType->getAs<PointerType>()->getPointeeType(); 691 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 692 NewType = M->getPointeeType(); 693 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 694 } 695 696 if (!NewType->isFunctionProtoType()) 697 return; 698 699 // There's lots of special cases for functions. For function pointers, system 700 // libraries are hopefully not as broken so that we don't need these 701 // workarounds. 702 if (CheckEquivalentExceptionSpec( 703 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 704 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 705 New->setInvalidDecl(); 706 } 707 } 708 709 /// CheckCXXDefaultArguments - Verify that the default arguments for a 710 /// function declaration are well-formed according to C++ 711 /// [dcl.fct.default]. 712 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 713 unsigned NumParams = FD->getNumParams(); 714 unsigned p; 715 716 // Find first parameter with a default argument 717 for (p = 0; p < NumParams; ++p) { 718 ParmVarDecl *Param = FD->getParamDecl(p); 719 if (Param->hasDefaultArg()) 720 break; 721 } 722 723 // C++11 [dcl.fct.default]p4: 724 // In a given function declaration, each parameter subsequent to a parameter 725 // with a default argument shall have a default argument supplied in this or 726 // a previous declaration or shall be a function parameter pack. A default 727 // argument shall not be redefined by a later declaration (not even to the 728 // same value). 729 unsigned LastMissingDefaultArg = 0; 730 for (; p < NumParams; ++p) { 731 ParmVarDecl *Param = FD->getParamDecl(p); 732 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 733 if (Param->isInvalidDecl()) 734 /* We already complained about this parameter. */; 735 else if (Param->getIdentifier()) 736 Diag(Param->getLocation(), 737 diag::err_param_default_argument_missing_name) 738 << Param->getIdentifier(); 739 else 740 Diag(Param->getLocation(), 741 diag::err_param_default_argument_missing); 742 743 LastMissingDefaultArg = p; 744 } 745 } 746 747 if (LastMissingDefaultArg > 0) { 748 // Some default arguments were missing. Clear out all of the 749 // default arguments up to (and including) the last missing 750 // default argument, so that we leave the function parameters 751 // in a semantically valid state. 752 for (p = 0; p <= LastMissingDefaultArg; ++p) { 753 ParmVarDecl *Param = FD->getParamDecl(p); 754 if (Param->hasDefaultArg()) { 755 Param->setDefaultArg(nullptr); 756 } 757 } 758 } 759 } 760 761 // CheckConstexprParameterTypes - Check whether a function's parameter types 762 // are all literal types. If so, return true. If not, produce a suitable 763 // diagnostic and return false. 764 static bool CheckConstexprParameterTypes(Sema &SemaRef, 765 const FunctionDecl *FD) { 766 unsigned ArgIndex = 0; 767 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 768 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 769 e = FT->param_type_end(); 770 i != e; ++i, ++ArgIndex) { 771 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 772 SourceLocation ParamLoc = PD->getLocation(); 773 if (!(*i)->isDependentType() && 774 SemaRef.RequireLiteralType(ParamLoc, *i, 775 diag::err_constexpr_non_literal_param, 776 ArgIndex+1, PD->getSourceRange(), 777 isa<CXXConstructorDecl>(FD))) 778 return false; 779 } 780 return true; 781 } 782 783 /// \brief Get diagnostic %select index for tag kind for 784 /// record diagnostic message. 785 /// WARNING: Indexes apply to particular diagnostics only! 786 /// 787 /// \returns diagnostic %select index. 788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 789 switch (Tag) { 790 case TTK_Struct: return 0; 791 case TTK_Interface: return 1; 792 case TTK_Class: return 2; 793 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 794 } 795 } 796 797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 798 // the requirements of a constexpr function definition or a constexpr 799 // constructor definition. If so, return true. If not, produce appropriate 800 // diagnostics and return false. 801 // 802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 803 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 804 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 805 if (MD && MD->isInstance()) { 806 // C++11 [dcl.constexpr]p4: 807 // The definition of a constexpr constructor shall satisfy the following 808 // constraints: 809 // - the class shall not have any virtual base classes; 810 const CXXRecordDecl *RD = MD->getParent(); 811 if (RD->getNumVBases()) { 812 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 813 << isa<CXXConstructorDecl>(NewFD) 814 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 815 for (const auto &I : RD->vbases()) 816 Diag(I.getLocStart(), 817 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 818 return false; 819 } 820 } 821 822 if (!isa<CXXConstructorDecl>(NewFD)) { 823 // C++11 [dcl.constexpr]p3: 824 // The definition of a constexpr function shall satisfy the following 825 // constraints: 826 // - it shall not be virtual; 827 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 828 if (Method && Method->isVirtual()) { 829 Method = Method->getCanonicalDecl(); 830 Diag(Method->getLocation(), diag::err_constexpr_virtual); 831 832 // If it's not obvious why this function is virtual, find an overridden 833 // function which uses the 'virtual' keyword. 834 const CXXMethodDecl *WrittenVirtual = Method; 835 while (!WrittenVirtual->isVirtualAsWritten()) 836 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 837 if (WrittenVirtual != Method) 838 Diag(WrittenVirtual->getLocation(), 839 diag::note_overridden_virtual_function); 840 return false; 841 } 842 843 // - its return type shall be a literal type; 844 QualType RT = NewFD->getReturnType(); 845 if (!RT->isDependentType() && 846 RequireLiteralType(NewFD->getLocation(), RT, 847 diag::err_constexpr_non_literal_return)) 848 return false; 849 } 850 851 // - each of its parameter types shall be a literal type; 852 if (!CheckConstexprParameterTypes(*this, NewFD)) 853 return false; 854 855 return true; 856 } 857 858 /// Check the given declaration statement is legal within a constexpr function 859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 860 /// 861 /// \return true if the body is OK (maybe only as an extension), false if we 862 /// have diagnosed a problem. 863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 864 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 865 // C++11 [dcl.constexpr]p3 and p4: 866 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 867 // contain only 868 for (const auto *DclIt : DS->decls()) { 869 switch (DclIt->getKind()) { 870 case Decl::StaticAssert: 871 case Decl::Using: 872 case Decl::UsingShadow: 873 case Decl::UsingDirective: 874 case Decl::UnresolvedUsingTypename: 875 case Decl::UnresolvedUsingValue: 876 // - static_assert-declarations 877 // - using-declarations, 878 // - using-directives, 879 continue; 880 881 case Decl::Typedef: 882 case Decl::TypeAlias: { 883 // - typedef declarations and alias-declarations that do not define 884 // classes or enumerations, 885 const auto *TN = cast<TypedefNameDecl>(DclIt); 886 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 887 // Don't allow variably-modified types in constexpr functions. 888 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 889 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 890 << TL.getSourceRange() << TL.getType() 891 << isa<CXXConstructorDecl>(Dcl); 892 return false; 893 } 894 continue; 895 } 896 897 case Decl::Enum: 898 case Decl::CXXRecord: 899 // C++1y allows types to be defined, not just declared. 900 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 901 SemaRef.Diag(DS->getLocStart(), 902 SemaRef.getLangOpts().CPlusPlus14 903 ? diag::warn_cxx11_compat_constexpr_type_definition 904 : diag::ext_constexpr_type_definition) 905 << isa<CXXConstructorDecl>(Dcl); 906 continue; 907 908 case Decl::EnumConstant: 909 case Decl::IndirectField: 910 case Decl::ParmVar: 911 // These can only appear with other declarations which are banned in 912 // C++11 and permitted in C++1y, so ignore them. 913 continue; 914 915 case Decl::Var: { 916 // C++1y [dcl.constexpr]p3 allows anything except: 917 // a definition of a variable of non-literal type or of static or 918 // thread storage duration or for which no initialization is performed. 919 const auto *VD = cast<VarDecl>(DclIt); 920 if (VD->isThisDeclarationADefinition()) { 921 if (VD->isStaticLocal()) { 922 SemaRef.Diag(VD->getLocation(), 923 diag::err_constexpr_local_var_static) 924 << isa<CXXConstructorDecl>(Dcl) 925 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 926 return false; 927 } 928 if (!VD->getType()->isDependentType() && 929 SemaRef.RequireLiteralType( 930 VD->getLocation(), VD->getType(), 931 diag::err_constexpr_local_var_non_literal_type, 932 isa<CXXConstructorDecl>(Dcl))) 933 return false; 934 if (!VD->getType()->isDependentType() && 935 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 936 SemaRef.Diag(VD->getLocation(), 937 diag::err_constexpr_local_var_no_init) 938 << isa<CXXConstructorDecl>(Dcl); 939 return false; 940 } 941 } 942 SemaRef.Diag(VD->getLocation(), 943 SemaRef.getLangOpts().CPlusPlus14 944 ? diag::warn_cxx11_compat_constexpr_local_var 945 : diag::ext_constexpr_local_var) 946 << isa<CXXConstructorDecl>(Dcl); 947 continue; 948 } 949 950 case Decl::NamespaceAlias: 951 case Decl::Function: 952 // These are disallowed in C++11 and permitted in C++1y. Allow them 953 // everywhere as an extension. 954 if (!Cxx1yLoc.isValid()) 955 Cxx1yLoc = DS->getLocStart(); 956 continue; 957 958 default: 959 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 960 << isa<CXXConstructorDecl>(Dcl); 961 return false; 962 } 963 } 964 965 return true; 966 } 967 968 /// Check that the given field is initialized within a constexpr constructor. 969 /// 970 /// \param Dcl The constexpr constructor being checked. 971 /// \param Field The field being checked. This may be a member of an anonymous 972 /// struct or union nested within the class being checked. 973 /// \param Inits All declarations, including anonymous struct/union members and 974 /// indirect members, for which any initialization was provided. 975 /// \param Diagnosed Set to true if an error is produced. 976 static void CheckConstexprCtorInitializer(Sema &SemaRef, 977 const FunctionDecl *Dcl, 978 FieldDecl *Field, 979 llvm::SmallSet<Decl*, 16> &Inits, 980 bool &Diagnosed) { 981 if (Field->isInvalidDecl()) 982 return; 983 984 if (Field->isUnnamedBitfield()) 985 return; 986 987 // Anonymous unions with no variant members and empty anonymous structs do not 988 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 989 // indirect fields don't need initializing. 990 if (Field->isAnonymousStructOrUnion() && 991 (Field->getType()->isUnionType() 992 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 993 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 994 return; 995 996 if (!Inits.count(Field)) { 997 if (!Diagnosed) { 998 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 999 Diagnosed = true; 1000 } 1001 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1002 } else if (Field->isAnonymousStructOrUnion()) { 1003 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1004 for (auto *I : RD->fields()) 1005 // If an anonymous union contains an anonymous struct of which any member 1006 // is initialized, all members must be initialized. 1007 if (!RD->isUnion() || Inits.count(I)) 1008 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1009 } 1010 } 1011 1012 /// Check the provided statement is allowed in a constexpr function 1013 /// definition. 1014 static bool 1015 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1016 SmallVectorImpl<SourceLocation> &ReturnStmts, 1017 SourceLocation &Cxx1yLoc) { 1018 // - its function-body shall be [...] a compound-statement that contains only 1019 switch (S->getStmtClass()) { 1020 case Stmt::NullStmtClass: 1021 // - null statements, 1022 return true; 1023 1024 case Stmt::DeclStmtClass: 1025 // - static_assert-declarations 1026 // - using-declarations, 1027 // - using-directives, 1028 // - typedef declarations and alias-declarations that do not define 1029 // classes or enumerations, 1030 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1031 return false; 1032 return true; 1033 1034 case Stmt::ReturnStmtClass: 1035 // - and exactly one return statement; 1036 if (isa<CXXConstructorDecl>(Dcl)) { 1037 // C++1y allows return statements in constexpr constructors. 1038 if (!Cxx1yLoc.isValid()) 1039 Cxx1yLoc = S->getLocStart(); 1040 return true; 1041 } 1042 1043 ReturnStmts.push_back(S->getLocStart()); 1044 return true; 1045 1046 case Stmt::CompoundStmtClass: { 1047 // C++1y allows compound-statements. 1048 if (!Cxx1yLoc.isValid()) 1049 Cxx1yLoc = S->getLocStart(); 1050 1051 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1052 for (auto *BodyIt : CompStmt->body()) { 1053 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1054 Cxx1yLoc)) 1055 return false; 1056 } 1057 return true; 1058 } 1059 1060 case Stmt::AttributedStmtClass: 1061 if (!Cxx1yLoc.isValid()) 1062 Cxx1yLoc = S->getLocStart(); 1063 return true; 1064 1065 case Stmt::IfStmtClass: { 1066 // C++1y allows if-statements. 1067 if (!Cxx1yLoc.isValid()) 1068 Cxx1yLoc = S->getLocStart(); 1069 1070 IfStmt *If = cast<IfStmt>(S); 1071 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1072 Cxx1yLoc)) 1073 return false; 1074 if (If->getElse() && 1075 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1076 Cxx1yLoc)) 1077 return false; 1078 return true; 1079 } 1080 1081 case Stmt::WhileStmtClass: 1082 case Stmt::DoStmtClass: 1083 case Stmt::ForStmtClass: 1084 case Stmt::CXXForRangeStmtClass: 1085 case Stmt::ContinueStmtClass: 1086 // C++1y allows all of these. We don't allow them as extensions in C++11, 1087 // because they don't make sense without variable mutation. 1088 if (!SemaRef.getLangOpts().CPlusPlus14) 1089 break; 1090 if (!Cxx1yLoc.isValid()) 1091 Cxx1yLoc = S->getLocStart(); 1092 for (Stmt *SubStmt : S->children()) 1093 if (SubStmt && 1094 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1095 Cxx1yLoc)) 1096 return false; 1097 return true; 1098 1099 case Stmt::SwitchStmtClass: 1100 case Stmt::CaseStmtClass: 1101 case Stmt::DefaultStmtClass: 1102 case Stmt::BreakStmtClass: 1103 // C++1y allows switch-statements, and since they don't need variable 1104 // mutation, we can reasonably allow them in C++11 as an extension. 1105 if (!Cxx1yLoc.isValid()) 1106 Cxx1yLoc = S->getLocStart(); 1107 for (Stmt *SubStmt : S->children()) 1108 if (SubStmt && 1109 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1110 Cxx1yLoc)) 1111 return false; 1112 return true; 1113 1114 default: 1115 if (!isa<Expr>(S)) 1116 break; 1117 1118 // C++1y allows expression-statements. 1119 if (!Cxx1yLoc.isValid()) 1120 Cxx1yLoc = S->getLocStart(); 1121 return true; 1122 } 1123 1124 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1125 << isa<CXXConstructorDecl>(Dcl); 1126 return false; 1127 } 1128 1129 /// Check the body for the given constexpr function declaration only contains 1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1131 /// 1132 /// \return true if the body is OK, false if we have diagnosed a problem. 1133 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1134 if (isa<CXXTryStmt>(Body)) { 1135 // C++11 [dcl.constexpr]p3: 1136 // The definition of a constexpr function shall satisfy the following 1137 // constraints: [...] 1138 // - its function-body shall be = delete, = default, or a 1139 // compound-statement 1140 // 1141 // C++11 [dcl.constexpr]p4: 1142 // In the definition of a constexpr constructor, [...] 1143 // - its function-body shall not be a function-try-block; 1144 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1145 << isa<CXXConstructorDecl>(Dcl); 1146 return false; 1147 } 1148 1149 SmallVector<SourceLocation, 4> ReturnStmts; 1150 1151 // - its function-body shall be [...] a compound-statement that contains only 1152 // [... list of cases ...] 1153 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1154 SourceLocation Cxx1yLoc; 1155 for (auto *BodyIt : CompBody->body()) { 1156 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1157 return false; 1158 } 1159 1160 if (Cxx1yLoc.isValid()) 1161 Diag(Cxx1yLoc, 1162 getLangOpts().CPlusPlus14 1163 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1164 : diag::ext_constexpr_body_invalid_stmt) 1165 << isa<CXXConstructorDecl>(Dcl); 1166 1167 if (const CXXConstructorDecl *Constructor 1168 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1169 const CXXRecordDecl *RD = Constructor->getParent(); 1170 // DR1359: 1171 // - every non-variant non-static data member and base class sub-object 1172 // shall be initialized; 1173 // DR1460: 1174 // - if the class is a union having variant members, exactly one of them 1175 // shall be initialized; 1176 if (RD->isUnion()) { 1177 if (Constructor->getNumCtorInitializers() == 0 && 1178 RD->hasVariantMembers()) { 1179 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1180 return false; 1181 } 1182 } else if (!Constructor->isDependentContext() && 1183 !Constructor->isDelegatingConstructor()) { 1184 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1185 1186 // Skip detailed checking if we have enough initializers, and we would 1187 // allow at most one initializer per member. 1188 bool AnyAnonStructUnionMembers = false; 1189 unsigned Fields = 0; 1190 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1191 E = RD->field_end(); I != E; ++I, ++Fields) { 1192 if (I->isAnonymousStructOrUnion()) { 1193 AnyAnonStructUnionMembers = true; 1194 break; 1195 } 1196 } 1197 // DR1460: 1198 // - if the class is a union-like class, but is not a union, for each of 1199 // its anonymous union members having variant members, exactly one of 1200 // them shall be initialized; 1201 if (AnyAnonStructUnionMembers || 1202 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1203 // Check initialization of non-static data members. Base classes are 1204 // always initialized so do not need to be checked. Dependent bases 1205 // might not have initializers in the member initializer list. 1206 llvm::SmallSet<Decl*, 16> Inits; 1207 for (const auto *I: Constructor->inits()) { 1208 if (FieldDecl *FD = I->getMember()) 1209 Inits.insert(FD); 1210 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1211 Inits.insert(ID->chain_begin(), ID->chain_end()); 1212 } 1213 1214 bool Diagnosed = false; 1215 for (auto *I : RD->fields()) 1216 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1217 if (Diagnosed) 1218 return false; 1219 } 1220 } 1221 } else { 1222 if (ReturnStmts.empty()) { 1223 // C++1y doesn't require constexpr functions to contain a 'return' 1224 // statement. We still do, unless the return type might be void, because 1225 // otherwise if there's no return statement, the function cannot 1226 // be used in a core constant expression. 1227 bool OK = getLangOpts().CPlusPlus14 && 1228 (Dcl->getReturnType()->isVoidType() || 1229 Dcl->getReturnType()->isDependentType()); 1230 Diag(Dcl->getLocation(), 1231 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1232 : diag::err_constexpr_body_no_return); 1233 if (!OK) 1234 return false; 1235 } else if (ReturnStmts.size() > 1) { 1236 Diag(ReturnStmts.back(), 1237 getLangOpts().CPlusPlus14 1238 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1239 : diag::ext_constexpr_body_multiple_return); 1240 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1241 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1242 } 1243 } 1244 1245 // C++11 [dcl.constexpr]p5: 1246 // if no function argument values exist such that the function invocation 1247 // substitution would produce a constant expression, the program is 1248 // ill-formed; no diagnostic required. 1249 // C++11 [dcl.constexpr]p3: 1250 // - every constructor call and implicit conversion used in initializing the 1251 // return value shall be one of those allowed in a constant expression. 1252 // C++11 [dcl.constexpr]p4: 1253 // - every constructor involved in initializing non-static data members and 1254 // base class sub-objects shall be a constexpr constructor. 1255 SmallVector<PartialDiagnosticAt, 8> Diags; 1256 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1257 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1258 << isa<CXXConstructorDecl>(Dcl); 1259 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1260 Diag(Diags[I].first, Diags[I].second); 1261 // Don't return false here: we allow this for compatibility in 1262 // system headers. 1263 } 1264 1265 return true; 1266 } 1267 1268 /// isCurrentClassName - Determine whether the identifier II is the 1269 /// name of the class type currently being defined. In the case of 1270 /// nested classes, this will only return true if II is the name of 1271 /// the innermost class. 1272 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1273 const CXXScopeSpec *SS) { 1274 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1275 1276 CXXRecordDecl *CurDecl; 1277 if (SS && SS->isSet() && !SS->isInvalid()) { 1278 DeclContext *DC = computeDeclContext(*SS, true); 1279 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1280 } else 1281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1282 1283 if (CurDecl && CurDecl->getIdentifier()) 1284 return &II == CurDecl->getIdentifier(); 1285 return false; 1286 } 1287 1288 /// \brief Determine whether the identifier II is a typo for the name of 1289 /// the class type currently being defined. If so, update it to the identifier 1290 /// that should have been used. 1291 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1292 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1293 1294 if (!getLangOpts().SpellChecking) 1295 return false; 1296 1297 CXXRecordDecl *CurDecl; 1298 if (SS && SS->isSet() && !SS->isInvalid()) { 1299 DeclContext *DC = computeDeclContext(*SS, true); 1300 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1301 } else 1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1303 1304 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1305 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1306 < II->getLength()) { 1307 II = CurDecl->getIdentifier(); 1308 return true; 1309 } 1310 1311 return false; 1312 } 1313 1314 /// \brief Determine whether the given class is a base class of the given 1315 /// class, including looking at dependent bases. 1316 static bool findCircularInheritance(const CXXRecordDecl *Class, 1317 const CXXRecordDecl *Current) { 1318 SmallVector<const CXXRecordDecl*, 8> Queue; 1319 1320 Class = Class->getCanonicalDecl(); 1321 while (true) { 1322 for (const auto &I : Current->bases()) { 1323 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1324 if (!Base) 1325 continue; 1326 1327 Base = Base->getDefinition(); 1328 if (!Base) 1329 continue; 1330 1331 if (Base->getCanonicalDecl() == Class) 1332 return true; 1333 1334 Queue.push_back(Base); 1335 } 1336 1337 if (Queue.empty()) 1338 return false; 1339 1340 Current = Queue.pop_back_val(); 1341 } 1342 1343 return false; 1344 } 1345 1346 /// \brief Check the validity of a C++ base class specifier. 1347 /// 1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1349 /// and returns NULL otherwise. 1350 CXXBaseSpecifier * 1351 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1352 SourceRange SpecifierRange, 1353 bool Virtual, AccessSpecifier Access, 1354 TypeSourceInfo *TInfo, 1355 SourceLocation EllipsisLoc) { 1356 QualType BaseType = TInfo->getType(); 1357 1358 // C++ [class.union]p1: 1359 // A union shall not have base classes. 1360 if (Class->isUnion()) { 1361 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1362 << SpecifierRange; 1363 return nullptr; 1364 } 1365 1366 if (EllipsisLoc.isValid() && 1367 !TInfo->getType()->containsUnexpandedParameterPack()) { 1368 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1369 << TInfo->getTypeLoc().getSourceRange(); 1370 EllipsisLoc = SourceLocation(); 1371 } 1372 1373 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1374 1375 if (BaseType->isDependentType()) { 1376 // Make sure that we don't have circular inheritance among our dependent 1377 // bases. For non-dependent bases, the check for completeness below handles 1378 // this. 1379 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1380 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1381 ((BaseDecl = BaseDecl->getDefinition()) && 1382 findCircularInheritance(Class, BaseDecl))) { 1383 Diag(BaseLoc, diag::err_circular_inheritance) 1384 << BaseType << Context.getTypeDeclType(Class); 1385 1386 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1387 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1388 << BaseType; 1389 1390 return nullptr; 1391 } 1392 } 1393 1394 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1395 Class->getTagKind() == TTK_Class, 1396 Access, TInfo, EllipsisLoc); 1397 } 1398 1399 // Base specifiers must be record types. 1400 if (!BaseType->isRecordType()) { 1401 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1402 return nullptr; 1403 } 1404 1405 // C++ [class.union]p1: 1406 // A union shall not be used as a base class. 1407 if (BaseType->isUnionType()) { 1408 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1409 return nullptr; 1410 } 1411 1412 // For the MS ABI, propagate DLL attributes to base class templates. 1413 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1414 if (Attr *ClassAttr = getDLLAttr(Class)) { 1415 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1416 BaseType->getAsCXXRecordDecl())) { 1417 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 1418 BaseLoc); 1419 } 1420 } 1421 } 1422 1423 // C++ [class.derived]p2: 1424 // The class-name in a base-specifier shall not be an incompletely 1425 // defined class. 1426 if (RequireCompleteType(BaseLoc, BaseType, 1427 diag::err_incomplete_base_class, SpecifierRange)) { 1428 Class->setInvalidDecl(); 1429 return nullptr; 1430 } 1431 1432 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1433 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1434 assert(BaseDecl && "Record type has no declaration"); 1435 BaseDecl = BaseDecl->getDefinition(); 1436 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1437 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1438 assert(CXXBaseDecl && "Base type is not a C++ type"); 1439 1440 // A class which contains a flexible array member is not suitable for use as a 1441 // base class: 1442 // - If the layout determines that a base comes before another base, 1443 // the flexible array member would index into the subsequent base. 1444 // - If the layout determines that base comes before the derived class, 1445 // the flexible array member would index into the derived class. 1446 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1447 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1448 << CXXBaseDecl->getDeclName(); 1449 return nullptr; 1450 } 1451 1452 // C++ [class]p3: 1453 // If a class is marked final and it appears as a base-type-specifier in 1454 // base-clause, the program is ill-formed. 1455 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1456 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1457 << CXXBaseDecl->getDeclName() 1458 << FA->isSpelledAsSealed(); 1459 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1460 << CXXBaseDecl->getDeclName() << FA->getRange(); 1461 return nullptr; 1462 } 1463 1464 if (BaseDecl->isInvalidDecl()) 1465 Class->setInvalidDecl(); 1466 1467 // Create the base specifier. 1468 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1469 Class->getTagKind() == TTK_Class, 1470 Access, TInfo, EllipsisLoc); 1471 } 1472 1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1474 /// one entry in the base class list of a class specifier, for 1475 /// example: 1476 /// class foo : public bar, virtual private baz { 1477 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1478 BaseResult 1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1480 ParsedAttributes &Attributes, 1481 bool Virtual, AccessSpecifier Access, 1482 ParsedType basetype, SourceLocation BaseLoc, 1483 SourceLocation EllipsisLoc) { 1484 if (!classdecl) 1485 return true; 1486 1487 AdjustDeclIfTemplate(classdecl); 1488 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1489 if (!Class) 1490 return true; 1491 1492 // We haven't yet attached the base specifiers. 1493 Class->setIsParsingBaseSpecifiers(); 1494 1495 // We do not support any C++11 attributes on base-specifiers yet. 1496 // Diagnose any attributes we see. 1497 if (!Attributes.empty()) { 1498 for (AttributeList *Attr = Attributes.getList(); Attr; 1499 Attr = Attr->getNext()) { 1500 if (Attr->isInvalid() || 1501 Attr->getKind() == AttributeList::IgnoredAttribute) 1502 continue; 1503 Diag(Attr->getLoc(), 1504 Attr->getKind() == AttributeList::UnknownAttribute 1505 ? diag::warn_unknown_attribute_ignored 1506 : diag::err_base_specifier_attribute) 1507 << Attr->getName(); 1508 } 1509 } 1510 1511 TypeSourceInfo *TInfo = nullptr; 1512 GetTypeFromParser(basetype, &TInfo); 1513 1514 if (EllipsisLoc.isInvalid() && 1515 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1516 UPPC_BaseType)) 1517 return true; 1518 1519 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1520 Virtual, Access, TInfo, 1521 EllipsisLoc)) 1522 return BaseSpec; 1523 else 1524 Class->setInvalidDecl(); 1525 1526 return true; 1527 } 1528 1529 /// Use small set to collect indirect bases. As this is only used 1530 /// locally, there's no need to abstract the small size parameter. 1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 1532 1533 /// \brief Recursively add the bases of Type. Don't add Type itself. 1534 static void 1535 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 1536 const QualType &Type) 1537 { 1538 // Even though the incoming type is a base, it might not be 1539 // a class -- it could be a template parm, for instance. 1540 if (auto Rec = Type->getAs<RecordType>()) { 1541 auto Decl = Rec->getAsCXXRecordDecl(); 1542 1543 // Iterate over its bases. 1544 for (const auto &BaseSpec : Decl->bases()) { 1545 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 1546 .getUnqualifiedType(); 1547 if (Set.insert(Base).second) 1548 // If we've not already seen it, recurse. 1549 NoteIndirectBases(Context, Set, Base); 1550 } 1551 } 1552 } 1553 1554 /// \brief Performs the actual work of attaching the given base class 1555 /// specifiers to a C++ class. 1556 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1557 unsigned NumBases) { 1558 if (NumBases == 0) 1559 return false; 1560 1561 // Used to keep track of which base types we have already seen, so 1562 // that we can properly diagnose redundant direct base types. Note 1563 // that the key is always the unqualified canonical type of the base 1564 // class. 1565 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1566 1567 // Used to track indirect bases so we can see if a direct base is 1568 // ambiguous. 1569 IndirectBaseSet IndirectBaseTypes; 1570 1571 // Copy non-redundant base specifiers into permanent storage. 1572 unsigned NumGoodBases = 0; 1573 bool Invalid = false; 1574 for (unsigned idx = 0; idx < NumBases; ++idx) { 1575 QualType NewBaseType 1576 = Context.getCanonicalType(Bases[idx]->getType()); 1577 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1578 1579 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1580 if (KnownBase) { 1581 // C++ [class.mi]p3: 1582 // A class shall not be specified as a direct base class of a 1583 // derived class more than once. 1584 Diag(Bases[idx]->getLocStart(), 1585 diag::err_duplicate_base_class) 1586 << KnownBase->getType() 1587 << Bases[idx]->getSourceRange(); 1588 1589 // Delete the duplicate base class specifier; we're going to 1590 // overwrite its pointer later. 1591 Context.Deallocate(Bases[idx]); 1592 1593 Invalid = true; 1594 } else { 1595 // Okay, add this new base class. 1596 KnownBase = Bases[idx]; 1597 Bases[NumGoodBases++] = Bases[idx]; 1598 1599 // Note this base's direct & indirect bases, if there could be ambiguity. 1600 if (NumBases > 1) 1601 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 1602 1603 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1604 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1605 if (Class->isInterface() && 1606 (!RD->isInterface() || 1607 KnownBase->getAccessSpecifier() != AS_public)) { 1608 // The Microsoft extension __interface does not permit bases that 1609 // are not themselves public interfaces. 1610 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1611 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1612 << RD->getSourceRange(); 1613 Invalid = true; 1614 } 1615 if (RD->hasAttr<WeakAttr>()) 1616 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1617 } 1618 } 1619 } 1620 1621 // Attach the remaining base class specifiers to the derived class. 1622 Class->setBases(Bases, NumGoodBases); 1623 1624 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 1625 // Check whether this direct base is inaccessible due to ambiguity. 1626 QualType BaseType = Bases[idx]->getType(); 1627 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 1628 .getUnqualifiedType(); 1629 1630 if (IndirectBaseTypes.count(CanonicalBase)) { 1631 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1632 /*DetectVirtual=*/true); 1633 bool found 1634 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 1635 assert(found); 1636 (void)found; 1637 1638 if (Paths.isAmbiguous(CanonicalBase)) 1639 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 1640 << BaseType << getAmbiguousPathsDisplayString(Paths) 1641 << Bases[idx]->getSourceRange(); 1642 else 1643 assert(Bases[idx]->isVirtual()); 1644 } 1645 1646 // Delete the base class specifier, since its data has been copied 1647 // into the CXXRecordDecl. 1648 Context.Deallocate(Bases[idx]); 1649 } 1650 1651 return Invalid; 1652 } 1653 1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1655 /// class, after checking whether there are any duplicate base 1656 /// classes. 1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1658 unsigned NumBases) { 1659 if (!ClassDecl || !Bases || !NumBases) 1660 return; 1661 1662 AdjustDeclIfTemplate(ClassDecl); 1663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1664 } 1665 1666 /// \brief Determine whether the type \p Derived is a C++ class that is 1667 /// derived from the type \p Base. 1668 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1669 if (!getLangOpts().CPlusPlus) 1670 return false; 1671 1672 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1673 if (!DerivedRD) 1674 return false; 1675 1676 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1677 if (!BaseRD) 1678 return false; 1679 1680 // If either the base or the derived type is invalid, don't try to 1681 // check whether one is derived from the other. 1682 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1683 return false; 1684 1685 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1686 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1687 } 1688 1689 /// \brief Determine whether the type \p Derived is a C++ class that is 1690 /// derived from the type \p Base. 1691 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1692 if (!getLangOpts().CPlusPlus) 1693 return false; 1694 1695 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1696 if (!DerivedRD) 1697 return false; 1698 1699 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1700 if (!BaseRD) 1701 return false; 1702 1703 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1704 } 1705 1706 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1707 CXXCastPath &BasePathArray) { 1708 assert(BasePathArray.empty() && "Base path array must be empty!"); 1709 assert(Paths.isRecordingPaths() && "Must record paths!"); 1710 1711 const CXXBasePath &Path = Paths.front(); 1712 1713 // We first go backward and check if we have a virtual base. 1714 // FIXME: It would be better if CXXBasePath had the base specifier for 1715 // the nearest virtual base. 1716 unsigned Start = 0; 1717 for (unsigned I = Path.size(); I != 0; --I) { 1718 if (Path[I - 1].Base->isVirtual()) { 1719 Start = I - 1; 1720 break; 1721 } 1722 } 1723 1724 // Now add all bases. 1725 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1726 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1727 } 1728 1729 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1730 /// conversion (where Derived and Base are class types) is 1731 /// well-formed, meaning that the conversion is unambiguous (and 1732 /// that all of the base classes are accessible). Returns true 1733 /// and emits a diagnostic if the code is ill-formed, returns false 1734 /// otherwise. Loc is the location where this routine should point to 1735 /// if there is an error, and Range is the source range to highlight 1736 /// if there is an error. 1737 bool 1738 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1739 unsigned InaccessibleBaseID, 1740 unsigned AmbigiousBaseConvID, 1741 SourceLocation Loc, SourceRange Range, 1742 DeclarationName Name, 1743 CXXCastPath *BasePath) { 1744 // First, determine whether the path from Derived to Base is 1745 // ambiguous. This is slightly more expensive than checking whether 1746 // the Derived to Base conversion exists, because here we need to 1747 // explore multiple paths to determine if there is an ambiguity. 1748 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1749 /*DetectVirtual=*/false); 1750 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1751 assert(DerivationOkay && 1752 "Can only be used with a derived-to-base conversion"); 1753 (void)DerivationOkay; 1754 1755 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1756 if (InaccessibleBaseID) { 1757 // Check that the base class can be accessed. 1758 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1759 InaccessibleBaseID)) { 1760 case AR_inaccessible: 1761 return true; 1762 case AR_accessible: 1763 case AR_dependent: 1764 case AR_delayed: 1765 break; 1766 } 1767 } 1768 1769 // Build a base path if necessary. 1770 if (BasePath) 1771 BuildBasePathArray(Paths, *BasePath); 1772 return false; 1773 } 1774 1775 if (AmbigiousBaseConvID) { 1776 // We know that the derived-to-base conversion is ambiguous, and 1777 // we're going to produce a diagnostic. Perform the derived-to-base 1778 // search just one more time to compute all of the possible paths so 1779 // that we can print them out. This is more expensive than any of 1780 // the previous derived-to-base checks we've done, but at this point 1781 // performance isn't as much of an issue. 1782 Paths.clear(); 1783 Paths.setRecordingPaths(true); 1784 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1785 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1786 (void)StillOkay; 1787 1788 // Build up a textual representation of the ambiguous paths, e.g., 1789 // D -> B -> A, that will be used to illustrate the ambiguous 1790 // conversions in the diagnostic. We only print one of the paths 1791 // to each base class subobject. 1792 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1793 1794 Diag(Loc, AmbigiousBaseConvID) 1795 << Derived << Base << PathDisplayStr << Range << Name; 1796 } 1797 return true; 1798 } 1799 1800 bool 1801 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1802 SourceLocation Loc, SourceRange Range, 1803 CXXCastPath *BasePath, 1804 bool IgnoreAccess) { 1805 return CheckDerivedToBaseConversion(Derived, Base, 1806 IgnoreAccess ? 0 1807 : diag::err_upcast_to_inaccessible_base, 1808 diag::err_ambiguous_derived_to_base_conv, 1809 Loc, Range, DeclarationName(), 1810 BasePath); 1811 } 1812 1813 1814 /// @brief Builds a string representing ambiguous paths from a 1815 /// specific derived class to different subobjects of the same base 1816 /// class. 1817 /// 1818 /// This function builds a string that can be used in error messages 1819 /// to show the different paths that one can take through the 1820 /// inheritance hierarchy to go from the derived class to different 1821 /// subobjects of a base class. The result looks something like this: 1822 /// @code 1823 /// struct D -> struct B -> struct A 1824 /// struct D -> struct C -> struct A 1825 /// @endcode 1826 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1827 std::string PathDisplayStr; 1828 std::set<unsigned> DisplayedPaths; 1829 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1830 Path != Paths.end(); ++Path) { 1831 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1832 // We haven't displayed a path to this particular base 1833 // class subobject yet. 1834 PathDisplayStr += "\n "; 1835 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1836 for (CXXBasePath::const_iterator Element = Path->begin(); 1837 Element != Path->end(); ++Element) 1838 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1839 } 1840 } 1841 1842 return PathDisplayStr; 1843 } 1844 1845 //===----------------------------------------------------------------------===// 1846 // C++ class member Handling 1847 //===----------------------------------------------------------------------===// 1848 1849 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1850 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1851 SourceLocation ASLoc, 1852 SourceLocation ColonLoc, 1853 AttributeList *Attrs) { 1854 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1855 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1856 ASLoc, ColonLoc); 1857 CurContext->addHiddenDecl(ASDecl); 1858 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1859 } 1860 1861 /// CheckOverrideControl - Check C++11 override control semantics. 1862 void Sema::CheckOverrideControl(NamedDecl *D) { 1863 if (D->isInvalidDecl()) 1864 return; 1865 1866 // We only care about "override" and "final" declarations. 1867 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1868 return; 1869 1870 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1871 1872 // We can't check dependent instance methods. 1873 if (MD && MD->isInstance() && 1874 (MD->getParent()->hasAnyDependentBases() || 1875 MD->getType()->isDependentType())) 1876 return; 1877 1878 if (MD && !MD->isVirtual()) { 1879 // If we have a non-virtual method, check if if hides a virtual method. 1880 // (In that case, it's most likely the method has the wrong type.) 1881 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1882 FindHiddenVirtualMethods(MD, OverloadedMethods); 1883 1884 if (!OverloadedMethods.empty()) { 1885 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1886 Diag(OA->getLocation(), 1887 diag::override_keyword_hides_virtual_member_function) 1888 << "override" << (OverloadedMethods.size() > 1); 1889 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1890 Diag(FA->getLocation(), 1891 diag::override_keyword_hides_virtual_member_function) 1892 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1893 << (OverloadedMethods.size() > 1); 1894 } 1895 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1896 MD->setInvalidDecl(); 1897 return; 1898 } 1899 // Fall through into the general case diagnostic. 1900 // FIXME: We might want to attempt typo correction here. 1901 } 1902 1903 if (!MD || !MD->isVirtual()) { 1904 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1905 Diag(OA->getLocation(), 1906 diag::override_keyword_only_allowed_on_virtual_member_functions) 1907 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1908 D->dropAttr<OverrideAttr>(); 1909 } 1910 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1911 Diag(FA->getLocation(), 1912 diag::override_keyword_only_allowed_on_virtual_member_functions) 1913 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1914 << FixItHint::CreateRemoval(FA->getLocation()); 1915 D->dropAttr<FinalAttr>(); 1916 } 1917 return; 1918 } 1919 1920 // C++11 [class.virtual]p5: 1921 // If a function is marked with the virt-specifier override and 1922 // does not override a member function of a base class, the program is 1923 // ill-formed. 1924 bool HasOverriddenMethods = 1925 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1926 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1927 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1928 << MD->getDeclName(); 1929 } 1930 1931 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1932 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1933 return; 1934 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1935 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1936 isa<CXXDestructorDecl>(MD)) 1937 return; 1938 1939 SourceLocation Loc = MD->getLocation(); 1940 SourceLocation SpellingLoc = Loc; 1941 if (getSourceManager().isMacroArgExpansion(Loc)) 1942 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1943 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1944 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1945 return; 1946 1947 if (MD->size_overridden_methods() > 0) { 1948 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1949 << MD->getDeclName(); 1950 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1951 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1952 } 1953 } 1954 1955 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1956 /// function overrides a virtual member function marked 'final', according to 1957 /// C++11 [class.virtual]p4. 1958 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1959 const CXXMethodDecl *Old) { 1960 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1961 if (!FA) 1962 return false; 1963 1964 Diag(New->getLocation(), diag::err_final_function_overridden) 1965 << New->getDeclName() 1966 << FA->isSpelledAsSealed(); 1967 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1968 return true; 1969 } 1970 1971 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1972 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1973 // FIXME: Destruction of ObjC lifetime types has side-effects. 1974 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1975 return !RD->isCompleteDefinition() || 1976 !RD->hasTrivialDefaultConstructor() || 1977 !RD->hasTrivialDestructor(); 1978 return false; 1979 } 1980 1981 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1982 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1983 if (it->isDeclspecPropertyAttribute()) 1984 return it; 1985 return nullptr; 1986 } 1987 1988 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1989 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1990 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1991 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1992 /// present (but parsing it has been deferred). 1993 NamedDecl * 1994 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1995 MultiTemplateParamsArg TemplateParameterLists, 1996 Expr *BW, const VirtSpecifiers &VS, 1997 InClassInitStyle InitStyle) { 1998 const DeclSpec &DS = D.getDeclSpec(); 1999 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2000 DeclarationName Name = NameInfo.getName(); 2001 SourceLocation Loc = NameInfo.getLoc(); 2002 2003 // For anonymous bitfields, the location should point to the type. 2004 if (Loc.isInvalid()) 2005 Loc = D.getLocStart(); 2006 2007 Expr *BitWidth = static_cast<Expr*>(BW); 2008 2009 assert(isa<CXXRecordDecl>(CurContext)); 2010 assert(!DS.isFriendSpecified()); 2011 2012 bool isFunc = D.isDeclarationOfFunction(); 2013 2014 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2015 // The Microsoft extension __interface only permits public member functions 2016 // and prohibits constructors, destructors, operators, non-public member 2017 // functions, static methods and data members. 2018 unsigned InvalidDecl; 2019 bool ShowDeclName = true; 2020 if (!isFunc) 2021 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2022 else if (AS != AS_public) 2023 InvalidDecl = 2; 2024 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2025 InvalidDecl = 3; 2026 else switch (Name.getNameKind()) { 2027 case DeclarationName::CXXConstructorName: 2028 InvalidDecl = 4; 2029 ShowDeclName = false; 2030 break; 2031 2032 case DeclarationName::CXXDestructorName: 2033 InvalidDecl = 5; 2034 ShowDeclName = false; 2035 break; 2036 2037 case DeclarationName::CXXOperatorName: 2038 case DeclarationName::CXXConversionFunctionName: 2039 InvalidDecl = 6; 2040 break; 2041 2042 default: 2043 InvalidDecl = 0; 2044 break; 2045 } 2046 2047 if (InvalidDecl) { 2048 if (ShowDeclName) 2049 Diag(Loc, diag::err_invalid_member_in_interface) 2050 << (InvalidDecl-1) << Name; 2051 else 2052 Diag(Loc, diag::err_invalid_member_in_interface) 2053 << (InvalidDecl-1) << ""; 2054 return nullptr; 2055 } 2056 } 2057 2058 // C++ 9.2p6: A member shall not be declared to have automatic storage 2059 // duration (auto, register) or with the extern storage-class-specifier. 2060 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2061 // data members and cannot be applied to names declared const or static, 2062 // and cannot be applied to reference members. 2063 switch (DS.getStorageClassSpec()) { 2064 case DeclSpec::SCS_unspecified: 2065 case DeclSpec::SCS_typedef: 2066 case DeclSpec::SCS_static: 2067 break; 2068 case DeclSpec::SCS_mutable: 2069 if (isFunc) { 2070 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2071 2072 // FIXME: It would be nicer if the keyword was ignored only for this 2073 // declarator. Otherwise we could get follow-up errors. 2074 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2075 } 2076 break; 2077 default: 2078 Diag(DS.getStorageClassSpecLoc(), 2079 diag::err_storageclass_invalid_for_member); 2080 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2081 break; 2082 } 2083 2084 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2085 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2086 !isFunc); 2087 2088 if (DS.isConstexprSpecified() && isInstField) { 2089 SemaDiagnosticBuilder B = 2090 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2091 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2092 if (InitStyle == ICIS_NoInit) { 2093 B << 0 << 0; 2094 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2095 B << FixItHint::CreateRemoval(ConstexprLoc); 2096 else { 2097 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2098 D.getMutableDeclSpec().ClearConstexprSpec(); 2099 const char *PrevSpec; 2100 unsigned DiagID; 2101 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2102 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2103 (void)Failed; 2104 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2105 } 2106 } else { 2107 B << 1; 2108 const char *PrevSpec; 2109 unsigned DiagID; 2110 if (D.getMutableDeclSpec().SetStorageClassSpec( 2111 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2112 Context.getPrintingPolicy())) { 2113 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2114 "This is the only DeclSpec that should fail to be applied"); 2115 B << 1; 2116 } else { 2117 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2118 isInstField = false; 2119 } 2120 } 2121 } 2122 2123 NamedDecl *Member; 2124 if (isInstField) { 2125 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2126 2127 // Data members must have identifiers for names. 2128 if (!Name.isIdentifier()) { 2129 Diag(Loc, diag::err_bad_variable_name) 2130 << Name; 2131 return nullptr; 2132 } 2133 2134 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2135 2136 // Member field could not be with "template" keyword. 2137 // So TemplateParameterLists should be empty in this case. 2138 if (TemplateParameterLists.size()) { 2139 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2140 if (TemplateParams->size()) { 2141 // There is no such thing as a member field template. 2142 Diag(D.getIdentifierLoc(), diag::err_template_member) 2143 << II 2144 << SourceRange(TemplateParams->getTemplateLoc(), 2145 TemplateParams->getRAngleLoc()); 2146 } else { 2147 // There is an extraneous 'template<>' for this member. 2148 Diag(TemplateParams->getTemplateLoc(), 2149 diag::err_template_member_noparams) 2150 << II 2151 << SourceRange(TemplateParams->getTemplateLoc(), 2152 TemplateParams->getRAngleLoc()); 2153 } 2154 return nullptr; 2155 } 2156 2157 if (SS.isSet() && !SS.isInvalid()) { 2158 // The user provided a superfluous scope specifier inside a class 2159 // definition: 2160 // 2161 // class X { 2162 // int X::member; 2163 // }; 2164 if (DeclContext *DC = computeDeclContext(SS, false)) 2165 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2166 else 2167 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2168 << Name << SS.getRange(); 2169 2170 SS.clear(); 2171 } 2172 2173 AttributeList *MSPropertyAttr = 2174 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2175 if (MSPropertyAttr) { 2176 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2177 BitWidth, InitStyle, AS, MSPropertyAttr); 2178 if (!Member) 2179 return nullptr; 2180 isInstField = false; 2181 } else { 2182 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2183 BitWidth, InitStyle, AS); 2184 assert(Member && "HandleField never returns null"); 2185 } 2186 } else { 2187 Member = HandleDeclarator(S, D, TemplateParameterLists); 2188 if (!Member) 2189 return nullptr; 2190 2191 // Non-instance-fields can't have a bitfield. 2192 if (BitWidth) { 2193 if (Member->isInvalidDecl()) { 2194 // don't emit another diagnostic. 2195 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2196 // C++ 9.6p3: A bit-field shall not be a static member. 2197 // "static member 'A' cannot be a bit-field" 2198 Diag(Loc, diag::err_static_not_bitfield) 2199 << Name << BitWidth->getSourceRange(); 2200 } else if (isa<TypedefDecl>(Member)) { 2201 // "typedef member 'x' cannot be a bit-field" 2202 Diag(Loc, diag::err_typedef_not_bitfield) 2203 << Name << BitWidth->getSourceRange(); 2204 } else { 2205 // A function typedef ("typedef int f(); f a;"). 2206 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2207 Diag(Loc, diag::err_not_integral_type_bitfield) 2208 << Name << cast<ValueDecl>(Member)->getType() 2209 << BitWidth->getSourceRange(); 2210 } 2211 2212 BitWidth = nullptr; 2213 Member->setInvalidDecl(); 2214 } 2215 2216 Member->setAccess(AS); 2217 2218 // If we have declared a member function template or static data member 2219 // template, set the access of the templated declaration as well. 2220 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2221 FunTmpl->getTemplatedDecl()->setAccess(AS); 2222 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2223 VarTmpl->getTemplatedDecl()->setAccess(AS); 2224 } 2225 2226 if (VS.isOverrideSpecified()) 2227 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2228 if (VS.isFinalSpecified()) 2229 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2230 VS.isFinalSpelledSealed())); 2231 2232 if (VS.getLastLocation().isValid()) { 2233 // Update the end location of a method that has a virt-specifiers. 2234 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2235 MD->setRangeEnd(VS.getLastLocation()); 2236 } 2237 2238 CheckOverrideControl(Member); 2239 2240 assert((Name || isInstField) && "No identifier for non-field ?"); 2241 2242 if (isInstField) { 2243 FieldDecl *FD = cast<FieldDecl>(Member); 2244 FieldCollector->Add(FD); 2245 2246 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2247 // Remember all explicit private FieldDecls that have a name, no side 2248 // effects and are not part of a dependent type declaration. 2249 if (!FD->isImplicit() && FD->getDeclName() && 2250 FD->getAccess() == AS_private && 2251 !FD->hasAttr<UnusedAttr>() && 2252 !FD->getParent()->isDependentContext() && 2253 !InitializationHasSideEffects(*FD)) 2254 UnusedPrivateFields.insert(FD); 2255 } 2256 } 2257 2258 return Member; 2259 } 2260 2261 namespace { 2262 class UninitializedFieldVisitor 2263 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2264 Sema &S; 2265 // List of Decls to generate a warning on. Also remove Decls that become 2266 // initialized. 2267 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2268 // List of base classes of the record. Classes are removed after their 2269 // initializers. 2270 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2271 // Vector of decls to be removed from the Decl set prior to visiting the 2272 // nodes. These Decls may have been initialized in the prior initializer. 2273 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2274 // If non-null, add a note to the warning pointing back to the constructor. 2275 const CXXConstructorDecl *Constructor; 2276 // Variables to hold state when processing an initializer list. When 2277 // InitList is true, special case initialization of FieldDecls matching 2278 // InitListFieldDecl. 2279 bool InitList; 2280 FieldDecl *InitListFieldDecl; 2281 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2282 2283 public: 2284 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2285 UninitializedFieldVisitor(Sema &S, 2286 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2287 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2288 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2289 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2290 2291 // Returns true if the use of ME is not an uninitialized use. 2292 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2293 bool CheckReferenceOnly) { 2294 llvm::SmallVector<FieldDecl*, 4> Fields; 2295 bool ReferenceField = false; 2296 while (ME) { 2297 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2298 if (!FD) 2299 return false; 2300 Fields.push_back(FD); 2301 if (FD->getType()->isReferenceType()) 2302 ReferenceField = true; 2303 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2304 } 2305 2306 // Binding a reference to an unintialized field is not an 2307 // uninitialized use. 2308 if (CheckReferenceOnly && !ReferenceField) 2309 return true; 2310 2311 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2312 // Discard the first field since it is the field decl that is being 2313 // initialized. 2314 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2315 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2316 } 2317 2318 for (auto UsedIter = UsedFieldIndex.begin(), 2319 UsedEnd = UsedFieldIndex.end(), 2320 OrigIter = InitFieldIndex.begin(), 2321 OrigEnd = InitFieldIndex.end(); 2322 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2323 if (*UsedIter < *OrigIter) 2324 return true; 2325 if (*UsedIter > *OrigIter) 2326 break; 2327 } 2328 2329 return false; 2330 } 2331 2332 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2333 bool AddressOf) { 2334 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2335 return; 2336 2337 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2338 // or union. 2339 MemberExpr *FieldME = ME; 2340 2341 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2342 2343 Expr *Base = ME; 2344 while (MemberExpr *SubME = 2345 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2346 2347 if (isa<VarDecl>(SubME->getMemberDecl())) 2348 return; 2349 2350 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2351 if (!FD->isAnonymousStructOrUnion()) 2352 FieldME = SubME; 2353 2354 if (!FieldME->getType().isPODType(S.Context)) 2355 AllPODFields = false; 2356 2357 Base = SubME->getBase(); 2358 } 2359 2360 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2361 return; 2362 2363 if (AddressOf && AllPODFields) 2364 return; 2365 2366 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2367 2368 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2369 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2370 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2371 } 2372 2373 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2374 QualType T = BaseCast->getType(); 2375 if (T->isPointerType() && 2376 BaseClasses.count(T->getPointeeType())) { 2377 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2378 << T->getPointeeType() << FoundVD; 2379 } 2380 } 2381 } 2382 2383 if (!Decls.count(FoundVD)) 2384 return; 2385 2386 const bool IsReference = FoundVD->getType()->isReferenceType(); 2387 2388 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2389 // Special checking for initializer lists. 2390 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2391 return; 2392 } 2393 } else { 2394 // Prevent double warnings on use of unbounded references. 2395 if (CheckReferenceOnly && !IsReference) 2396 return; 2397 } 2398 2399 unsigned diag = IsReference 2400 ? diag::warn_reference_field_is_uninit 2401 : diag::warn_field_is_uninit; 2402 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2403 if (Constructor) 2404 S.Diag(Constructor->getLocation(), 2405 diag::note_uninit_in_this_constructor) 2406 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2407 2408 } 2409 2410 void HandleValue(Expr *E, bool AddressOf) { 2411 E = E->IgnoreParens(); 2412 2413 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2414 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2415 AddressOf /*AddressOf*/); 2416 return; 2417 } 2418 2419 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2420 Visit(CO->getCond()); 2421 HandleValue(CO->getTrueExpr(), AddressOf); 2422 HandleValue(CO->getFalseExpr(), AddressOf); 2423 return; 2424 } 2425 2426 if (BinaryConditionalOperator *BCO = 2427 dyn_cast<BinaryConditionalOperator>(E)) { 2428 Visit(BCO->getCond()); 2429 HandleValue(BCO->getFalseExpr(), AddressOf); 2430 return; 2431 } 2432 2433 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2434 HandleValue(OVE->getSourceExpr(), AddressOf); 2435 return; 2436 } 2437 2438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2439 switch (BO->getOpcode()) { 2440 default: 2441 break; 2442 case(BO_PtrMemD): 2443 case(BO_PtrMemI): 2444 HandleValue(BO->getLHS(), AddressOf); 2445 Visit(BO->getRHS()); 2446 return; 2447 case(BO_Comma): 2448 Visit(BO->getLHS()); 2449 HandleValue(BO->getRHS(), AddressOf); 2450 return; 2451 } 2452 } 2453 2454 Visit(E); 2455 } 2456 2457 void CheckInitListExpr(InitListExpr *ILE) { 2458 InitFieldIndex.push_back(0); 2459 for (auto Child : ILE->children()) { 2460 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2461 CheckInitListExpr(SubList); 2462 } else { 2463 Visit(Child); 2464 } 2465 ++InitFieldIndex.back(); 2466 } 2467 InitFieldIndex.pop_back(); 2468 } 2469 2470 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2471 FieldDecl *Field, const Type *BaseClass) { 2472 // Remove Decls that may have been initialized in the previous 2473 // initializer. 2474 for (ValueDecl* VD : DeclsToRemove) 2475 Decls.erase(VD); 2476 DeclsToRemove.clear(); 2477 2478 Constructor = FieldConstructor; 2479 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2480 2481 if (ILE && Field) { 2482 InitList = true; 2483 InitListFieldDecl = Field; 2484 InitFieldIndex.clear(); 2485 CheckInitListExpr(ILE); 2486 } else { 2487 InitList = false; 2488 Visit(E); 2489 } 2490 2491 if (Field) 2492 Decls.erase(Field); 2493 if (BaseClass) 2494 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2495 } 2496 2497 void VisitMemberExpr(MemberExpr *ME) { 2498 // All uses of unbounded reference fields will warn. 2499 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2500 } 2501 2502 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2503 if (E->getCastKind() == CK_LValueToRValue) { 2504 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2505 return; 2506 } 2507 2508 Inherited::VisitImplicitCastExpr(E); 2509 } 2510 2511 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2512 if (E->getConstructor()->isCopyConstructor()) { 2513 Expr *ArgExpr = E->getArg(0); 2514 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2515 if (ILE->getNumInits() == 1) 2516 ArgExpr = ILE->getInit(0); 2517 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2518 if (ICE->getCastKind() == CK_NoOp) 2519 ArgExpr = ICE->getSubExpr(); 2520 HandleValue(ArgExpr, false /*AddressOf*/); 2521 return; 2522 } 2523 Inherited::VisitCXXConstructExpr(E); 2524 } 2525 2526 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2527 Expr *Callee = E->getCallee(); 2528 if (isa<MemberExpr>(Callee)) { 2529 HandleValue(Callee, false /*AddressOf*/); 2530 for (auto Arg : E->arguments()) 2531 Visit(Arg); 2532 return; 2533 } 2534 2535 Inherited::VisitCXXMemberCallExpr(E); 2536 } 2537 2538 void VisitCallExpr(CallExpr *E) { 2539 // Treat std::move as a use. 2540 if (E->getNumArgs() == 1) { 2541 if (FunctionDecl *FD = E->getDirectCallee()) { 2542 if (FD->isInStdNamespace() && FD->getIdentifier() && 2543 FD->getIdentifier()->isStr("move")) { 2544 HandleValue(E->getArg(0), false /*AddressOf*/); 2545 return; 2546 } 2547 } 2548 } 2549 2550 Inherited::VisitCallExpr(E); 2551 } 2552 2553 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2554 Expr *Callee = E->getCallee(); 2555 2556 if (isa<UnresolvedLookupExpr>(Callee)) 2557 return Inherited::VisitCXXOperatorCallExpr(E); 2558 2559 Visit(Callee); 2560 for (auto Arg : E->arguments()) 2561 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2562 } 2563 2564 void VisitBinaryOperator(BinaryOperator *E) { 2565 // If a field assignment is detected, remove the field from the 2566 // uninitiailized field set. 2567 if (E->getOpcode() == BO_Assign) 2568 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2569 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2570 if (!FD->getType()->isReferenceType()) 2571 DeclsToRemove.push_back(FD); 2572 2573 if (E->isCompoundAssignmentOp()) { 2574 HandleValue(E->getLHS(), false /*AddressOf*/); 2575 Visit(E->getRHS()); 2576 return; 2577 } 2578 2579 Inherited::VisitBinaryOperator(E); 2580 } 2581 2582 void VisitUnaryOperator(UnaryOperator *E) { 2583 if (E->isIncrementDecrementOp()) { 2584 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2585 return; 2586 } 2587 if (E->getOpcode() == UO_AddrOf) { 2588 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2589 HandleValue(ME->getBase(), true /*AddressOf*/); 2590 return; 2591 } 2592 } 2593 2594 Inherited::VisitUnaryOperator(E); 2595 } 2596 }; 2597 2598 // Diagnose value-uses of fields to initialize themselves, e.g. 2599 // foo(foo) 2600 // where foo is not also a parameter to the constructor. 2601 // Also diagnose across field uninitialized use such as 2602 // x(y), y(x) 2603 // TODO: implement -Wuninitialized and fold this into that framework. 2604 static void DiagnoseUninitializedFields( 2605 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2606 2607 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2608 Constructor->getLocation())) { 2609 return; 2610 } 2611 2612 if (Constructor->isInvalidDecl()) 2613 return; 2614 2615 const CXXRecordDecl *RD = Constructor->getParent(); 2616 2617 if (RD->getDescribedClassTemplate()) 2618 return; 2619 2620 // Holds fields that are uninitialized. 2621 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2622 2623 // At the beginning, all fields are uninitialized. 2624 for (auto *I : RD->decls()) { 2625 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2626 UninitializedFields.insert(FD); 2627 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2628 UninitializedFields.insert(IFD->getAnonField()); 2629 } 2630 } 2631 2632 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2633 for (auto I : RD->bases()) 2634 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2635 2636 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2637 return; 2638 2639 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2640 UninitializedFields, 2641 UninitializedBaseClasses); 2642 2643 for (const auto *FieldInit : Constructor->inits()) { 2644 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2645 break; 2646 2647 Expr *InitExpr = FieldInit->getInit(); 2648 if (!InitExpr) 2649 continue; 2650 2651 if (CXXDefaultInitExpr *Default = 2652 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2653 InitExpr = Default->getExpr(); 2654 if (!InitExpr) 2655 continue; 2656 // In class initializers will point to the constructor. 2657 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2658 FieldInit->getAnyMember(), 2659 FieldInit->getBaseClass()); 2660 } else { 2661 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2662 FieldInit->getAnyMember(), 2663 FieldInit->getBaseClass()); 2664 } 2665 } 2666 } 2667 } // namespace 2668 2669 /// \brief Enter a new C++ default initializer scope. After calling this, the 2670 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2671 /// parsing or instantiating the initializer failed. 2672 void Sema::ActOnStartCXXInClassMemberInitializer() { 2673 // Create a synthetic function scope to represent the call to the constructor 2674 // that notionally surrounds a use of this initializer. 2675 PushFunctionScope(); 2676 } 2677 2678 /// \brief This is invoked after parsing an in-class initializer for a 2679 /// non-static C++ class member, and after instantiating an in-class initializer 2680 /// in a class template. Such actions are deferred until the class is complete. 2681 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2682 SourceLocation InitLoc, 2683 Expr *InitExpr) { 2684 // Pop the notional constructor scope we created earlier. 2685 PopFunctionScopeInfo(nullptr, D); 2686 2687 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2688 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 2689 "must set init style when field is created"); 2690 2691 if (!InitExpr) { 2692 D->setInvalidDecl(); 2693 if (FD) 2694 FD->removeInClassInitializer(); 2695 return; 2696 } 2697 2698 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2699 FD->setInvalidDecl(); 2700 FD->removeInClassInitializer(); 2701 return; 2702 } 2703 2704 ExprResult Init = InitExpr; 2705 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2706 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2707 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2708 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2709 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2710 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2711 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2712 if (Init.isInvalid()) { 2713 FD->setInvalidDecl(); 2714 return; 2715 } 2716 } 2717 2718 // C++11 [class.base.init]p7: 2719 // The initialization of each base and member constitutes a 2720 // full-expression. 2721 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2722 if (Init.isInvalid()) { 2723 FD->setInvalidDecl(); 2724 return; 2725 } 2726 2727 InitExpr = Init.get(); 2728 2729 FD->setInClassInitializer(InitExpr); 2730 } 2731 2732 /// \brief Find the direct and/or virtual base specifiers that 2733 /// correspond to the given base type, for use in base initialization 2734 /// within a constructor. 2735 static bool FindBaseInitializer(Sema &SemaRef, 2736 CXXRecordDecl *ClassDecl, 2737 QualType BaseType, 2738 const CXXBaseSpecifier *&DirectBaseSpec, 2739 const CXXBaseSpecifier *&VirtualBaseSpec) { 2740 // First, check for a direct base class. 2741 DirectBaseSpec = nullptr; 2742 for (const auto &Base : ClassDecl->bases()) { 2743 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2744 // We found a direct base of this type. That's what we're 2745 // initializing. 2746 DirectBaseSpec = &Base; 2747 break; 2748 } 2749 } 2750 2751 // Check for a virtual base class. 2752 // FIXME: We might be able to short-circuit this if we know in advance that 2753 // there are no virtual bases. 2754 VirtualBaseSpec = nullptr; 2755 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2756 // We haven't found a base yet; search the class hierarchy for a 2757 // virtual base class. 2758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2759 /*DetectVirtual=*/false); 2760 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2761 BaseType, Paths)) { 2762 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2763 Path != Paths.end(); ++Path) { 2764 if (Path->back().Base->isVirtual()) { 2765 VirtualBaseSpec = Path->back().Base; 2766 break; 2767 } 2768 } 2769 } 2770 } 2771 2772 return DirectBaseSpec || VirtualBaseSpec; 2773 } 2774 2775 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2776 MemInitResult 2777 Sema::ActOnMemInitializer(Decl *ConstructorD, 2778 Scope *S, 2779 CXXScopeSpec &SS, 2780 IdentifierInfo *MemberOrBase, 2781 ParsedType TemplateTypeTy, 2782 const DeclSpec &DS, 2783 SourceLocation IdLoc, 2784 Expr *InitList, 2785 SourceLocation EllipsisLoc) { 2786 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2787 DS, IdLoc, InitList, 2788 EllipsisLoc); 2789 } 2790 2791 /// \brief Handle a C++ member initializer using parentheses syntax. 2792 MemInitResult 2793 Sema::ActOnMemInitializer(Decl *ConstructorD, 2794 Scope *S, 2795 CXXScopeSpec &SS, 2796 IdentifierInfo *MemberOrBase, 2797 ParsedType TemplateTypeTy, 2798 const DeclSpec &DS, 2799 SourceLocation IdLoc, 2800 SourceLocation LParenLoc, 2801 ArrayRef<Expr *> Args, 2802 SourceLocation RParenLoc, 2803 SourceLocation EllipsisLoc) { 2804 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2805 Args, RParenLoc); 2806 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2807 DS, IdLoc, List, EllipsisLoc); 2808 } 2809 2810 namespace { 2811 2812 // Callback to only accept typo corrections that can be a valid C++ member 2813 // intializer: either a non-static field member or a base class. 2814 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2815 public: 2816 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2817 : ClassDecl(ClassDecl) {} 2818 2819 bool ValidateCandidate(const TypoCorrection &candidate) override { 2820 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2821 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2822 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2823 return isa<TypeDecl>(ND); 2824 } 2825 return false; 2826 } 2827 2828 private: 2829 CXXRecordDecl *ClassDecl; 2830 }; 2831 2832 } 2833 2834 /// \brief Handle a C++ member initializer. 2835 MemInitResult 2836 Sema::BuildMemInitializer(Decl *ConstructorD, 2837 Scope *S, 2838 CXXScopeSpec &SS, 2839 IdentifierInfo *MemberOrBase, 2840 ParsedType TemplateTypeTy, 2841 const DeclSpec &DS, 2842 SourceLocation IdLoc, 2843 Expr *Init, 2844 SourceLocation EllipsisLoc) { 2845 ExprResult Res = CorrectDelayedTyposInExpr(Init); 2846 if (!Res.isUsable()) 2847 return true; 2848 Init = Res.get(); 2849 2850 if (!ConstructorD) 2851 return true; 2852 2853 AdjustDeclIfTemplate(ConstructorD); 2854 2855 CXXConstructorDecl *Constructor 2856 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2857 if (!Constructor) { 2858 // The user wrote a constructor initializer on a function that is 2859 // not a C++ constructor. Ignore the error for now, because we may 2860 // have more member initializers coming; we'll diagnose it just 2861 // once in ActOnMemInitializers. 2862 return true; 2863 } 2864 2865 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2866 2867 // C++ [class.base.init]p2: 2868 // Names in a mem-initializer-id are looked up in the scope of the 2869 // constructor's class and, if not found in that scope, are looked 2870 // up in the scope containing the constructor's definition. 2871 // [Note: if the constructor's class contains a member with the 2872 // same name as a direct or virtual base class of the class, a 2873 // mem-initializer-id naming the member or base class and composed 2874 // of a single identifier refers to the class member. A 2875 // mem-initializer-id for the hidden base class may be specified 2876 // using a qualified name. ] 2877 if (!SS.getScopeRep() && !TemplateTypeTy) { 2878 // Look for a member, first. 2879 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2880 if (!Result.empty()) { 2881 ValueDecl *Member; 2882 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2883 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2884 if (EllipsisLoc.isValid()) 2885 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2886 << MemberOrBase 2887 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2888 2889 return BuildMemberInitializer(Member, Init, IdLoc); 2890 } 2891 } 2892 } 2893 // It didn't name a member, so see if it names a class. 2894 QualType BaseType; 2895 TypeSourceInfo *TInfo = nullptr; 2896 2897 if (TemplateTypeTy) { 2898 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2899 } else if (DS.getTypeSpecType() == TST_decltype) { 2900 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2901 } else { 2902 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2903 LookupParsedName(R, S, &SS); 2904 2905 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2906 if (!TyD) { 2907 if (R.isAmbiguous()) return true; 2908 2909 // We don't want access-control diagnostics here. 2910 R.suppressDiagnostics(); 2911 2912 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2913 bool NotUnknownSpecialization = false; 2914 DeclContext *DC = computeDeclContext(SS, false); 2915 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2916 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2917 2918 if (!NotUnknownSpecialization) { 2919 // When the scope specifier can refer to a member of an unknown 2920 // specialization, we take it as a type name. 2921 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2922 SS.getWithLocInContext(Context), 2923 *MemberOrBase, IdLoc); 2924 if (BaseType.isNull()) 2925 return true; 2926 2927 R.clear(); 2928 R.setLookupName(MemberOrBase); 2929 } 2930 } 2931 2932 // If no results were found, try to correct typos. 2933 TypoCorrection Corr; 2934 if (R.empty() && BaseType.isNull() && 2935 (Corr = CorrectTypo( 2936 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2937 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2938 CTK_ErrorRecovery, ClassDecl))) { 2939 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2940 // We have found a non-static data member with a similar 2941 // name to what was typed; complain and initialize that 2942 // member. 2943 diagnoseTypo(Corr, 2944 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2945 << MemberOrBase << true); 2946 return BuildMemberInitializer(Member, Init, IdLoc); 2947 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2948 const CXXBaseSpecifier *DirectBaseSpec; 2949 const CXXBaseSpecifier *VirtualBaseSpec; 2950 if (FindBaseInitializer(*this, ClassDecl, 2951 Context.getTypeDeclType(Type), 2952 DirectBaseSpec, VirtualBaseSpec)) { 2953 // We have found a direct or virtual base class with a 2954 // similar name to what was typed; complain and initialize 2955 // that base class. 2956 diagnoseTypo(Corr, 2957 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2958 << MemberOrBase << false, 2959 PDiag() /*Suppress note, we provide our own.*/); 2960 2961 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2962 : VirtualBaseSpec; 2963 Diag(BaseSpec->getLocStart(), 2964 diag::note_base_class_specified_here) 2965 << BaseSpec->getType() 2966 << BaseSpec->getSourceRange(); 2967 2968 TyD = Type; 2969 } 2970 } 2971 } 2972 2973 if (!TyD && BaseType.isNull()) { 2974 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2975 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2976 return true; 2977 } 2978 } 2979 2980 if (BaseType.isNull()) { 2981 BaseType = Context.getTypeDeclType(TyD); 2982 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 2983 if (SS.isSet()) 2984 // FIXME: preserve source range information 2985 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2986 BaseType); 2987 } 2988 } 2989 2990 if (!TInfo) 2991 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2992 2993 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2994 } 2995 2996 /// Checks a member initializer expression for cases where reference (or 2997 /// pointer) members are bound to by-value parameters (or their addresses). 2998 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2999 Expr *Init, 3000 SourceLocation IdLoc) { 3001 QualType MemberTy = Member->getType(); 3002 3003 // We only handle pointers and references currently. 3004 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3005 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3006 return; 3007 3008 const bool IsPointer = MemberTy->isPointerType(); 3009 if (IsPointer) { 3010 if (const UnaryOperator *Op 3011 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3012 // The only case we're worried about with pointers requires taking the 3013 // address. 3014 if (Op->getOpcode() != UO_AddrOf) 3015 return; 3016 3017 Init = Op->getSubExpr(); 3018 } else { 3019 // We only handle address-of expression initializers for pointers. 3020 return; 3021 } 3022 } 3023 3024 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3025 // We only warn when referring to a non-reference parameter declaration. 3026 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3027 if (!Parameter || Parameter->getType()->isReferenceType()) 3028 return; 3029 3030 S.Diag(Init->getExprLoc(), 3031 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3032 : diag::warn_bind_ref_member_to_parameter) 3033 << Member << Parameter << Init->getSourceRange(); 3034 } else { 3035 // Other initializers are fine. 3036 return; 3037 } 3038 3039 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3040 << (unsigned)IsPointer; 3041 } 3042 3043 MemInitResult 3044 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3045 SourceLocation IdLoc) { 3046 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3047 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3048 assert((DirectMember || IndirectMember) && 3049 "Member must be a FieldDecl or IndirectFieldDecl"); 3050 3051 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3052 return true; 3053 3054 if (Member->isInvalidDecl()) 3055 return true; 3056 3057 MultiExprArg Args; 3058 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3059 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3060 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3061 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3062 } else { 3063 // Template instantiation doesn't reconstruct ParenListExprs for us. 3064 Args = Init; 3065 } 3066 3067 SourceRange InitRange = Init->getSourceRange(); 3068 3069 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3070 // Can't check initialization for a member of dependent type or when 3071 // any of the arguments are type-dependent expressions. 3072 DiscardCleanupsInEvaluationContext(); 3073 } else { 3074 bool InitList = false; 3075 if (isa<InitListExpr>(Init)) { 3076 InitList = true; 3077 Args = Init; 3078 } 3079 3080 // Initialize the member. 3081 InitializedEntity MemberEntity = 3082 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3083 : InitializedEntity::InitializeMember(IndirectMember, 3084 nullptr); 3085 InitializationKind Kind = 3086 InitList ? InitializationKind::CreateDirectList(IdLoc) 3087 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3088 InitRange.getEnd()); 3089 3090 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3091 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3092 nullptr); 3093 if (MemberInit.isInvalid()) 3094 return true; 3095 3096 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3097 3098 // C++11 [class.base.init]p7: 3099 // The initialization of each base and member constitutes a 3100 // full-expression. 3101 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3102 if (MemberInit.isInvalid()) 3103 return true; 3104 3105 Init = MemberInit.get(); 3106 } 3107 3108 if (DirectMember) { 3109 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3110 InitRange.getBegin(), Init, 3111 InitRange.getEnd()); 3112 } else { 3113 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3114 InitRange.getBegin(), Init, 3115 InitRange.getEnd()); 3116 } 3117 } 3118 3119 MemInitResult 3120 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3121 CXXRecordDecl *ClassDecl) { 3122 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3123 if (!LangOpts.CPlusPlus11) 3124 return Diag(NameLoc, diag::err_delegating_ctor) 3125 << TInfo->getTypeLoc().getLocalSourceRange(); 3126 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3127 3128 bool InitList = true; 3129 MultiExprArg Args = Init; 3130 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3131 InitList = false; 3132 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3133 } 3134 3135 SourceRange InitRange = Init->getSourceRange(); 3136 // Initialize the object. 3137 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3138 QualType(ClassDecl->getTypeForDecl(), 0)); 3139 InitializationKind Kind = 3140 InitList ? InitializationKind::CreateDirectList(NameLoc) 3141 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3142 InitRange.getEnd()); 3143 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3144 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3145 Args, nullptr); 3146 if (DelegationInit.isInvalid()) 3147 return true; 3148 3149 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3150 "Delegating constructor with no target?"); 3151 3152 // C++11 [class.base.init]p7: 3153 // The initialization of each base and member constitutes a 3154 // full-expression. 3155 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3156 InitRange.getBegin()); 3157 if (DelegationInit.isInvalid()) 3158 return true; 3159 3160 // If we are in a dependent context, template instantiation will 3161 // perform this type-checking again. Just save the arguments that we 3162 // received in a ParenListExpr. 3163 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3164 // of the information that we have about the base 3165 // initializer. However, deconstructing the ASTs is a dicey process, 3166 // and this approach is far more likely to get the corner cases right. 3167 if (CurContext->isDependentContext()) 3168 DelegationInit = Init; 3169 3170 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3171 DelegationInit.getAs<Expr>(), 3172 InitRange.getEnd()); 3173 } 3174 3175 MemInitResult 3176 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3177 Expr *Init, CXXRecordDecl *ClassDecl, 3178 SourceLocation EllipsisLoc) { 3179 SourceLocation BaseLoc 3180 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3181 3182 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3183 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3184 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3185 3186 // C++ [class.base.init]p2: 3187 // [...] Unless the mem-initializer-id names a nonstatic data 3188 // member of the constructor's class or a direct or virtual base 3189 // of that class, the mem-initializer is ill-formed. A 3190 // mem-initializer-list can initialize a base class using any 3191 // name that denotes that base class type. 3192 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3193 3194 SourceRange InitRange = Init->getSourceRange(); 3195 if (EllipsisLoc.isValid()) { 3196 // This is a pack expansion. 3197 if (!BaseType->containsUnexpandedParameterPack()) { 3198 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3199 << SourceRange(BaseLoc, InitRange.getEnd()); 3200 3201 EllipsisLoc = SourceLocation(); 3202 } 3203 } else { 3204 // Check for any unexpanded parameter packs. 3205 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3206 return true; 3207 3208 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3209 return true; 3210 } 3211 3212 // Check for direct and virtual base classes. 3213 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3214 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3215 if (!Dependent) { 3216 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3217 BaseType)) 3218 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3219 3220 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3221 VirtualBaseSpec); 3222 3223 // C++ [base.class.init]p2: 3224 // Unless the mem-initializer-id names a nonstatic data member of the 3225 // constructor's class or a direct or virtual base of that class, the 3226 // mem-initializer is ill-formed. 3227 if (!DirectBaseSpec && !VirtualBaseSpec) { 3228 // If the class has any dependent bases, then it's possible that 3229 // one of those types will resolve to the same type as 3230 // BaseType. Therefore, just treat this as a dependent base 3231 // class initialization. FIXME: Should we try to check the 3232 // initialization anyway? It seems odd. 3233 if (ClassDecl->hasAnyDependentBases()) 3234 Dependent = true; 3235 else 3236 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3237 << BaseType << Context.getTypeDeclType(ClassDecl) 3238 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3239 } 3240 } 3241 3242 if (Dependent) { 3243 DiscardCleanupsInEvaluationContext(); 3244 3245 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3246 /*IsVirtual=*/false, 3247 InitRange.getBegin(), Init, 3248 InitRange.getEnd(), EllipsisLoc); 3249 } 3250 3251 // C++ [base.class.init]p2: 3252 // If a mem-initializer-id is ambiguous because it designates both 3253 // a direct non-virtual base class and an inherited virtual base 3254 // class, the mem-initializer is ill-formed. 3255 if (DirectBaseSpec && VirtualBaseSpec) 3256 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3257 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3258 3259 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3260 if (!BaseSpec) 3261 BaseSpec = VirtualBaseSpec; 3262 3263 // Initialize the base. 3264 bool InitList = true; 3265 MultiExprArg Args = Init; 3266 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3267 InitList = false; 3268 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3269 } 3270 3271 InitializedEntity BaseEntity = 3272 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3273 InitializationKind Kind = 3274 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3275 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3276 InitRange.getEnd()); 3277 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3278 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3279 if (BaseInit.isInvalid()) 3280 return true; 3281 3282 // C++11 [class.base.init]p7: 3283 // The initialization of each base and member constitutes a 3284 // full-expression. 3285 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3286 if (BaseInit.isInvalid()) 3287 return true; 3288 3289 // If we are in a dependent context, template instantiation will 3290 // perform this type-checking again. Just save the arguments that we 3291 // received in a ParenListExpr. 3292 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3293 // of the information that we have about the base 3294 // initializer. However, deconstructing the ASTs is a dicey process, 3295 // and this approach is far more likely to get the corner cases right. 3296 if (CurContext->isDependentContext()) 3297 BaseInit = Init; 3298 3299 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3300 BaseSpec->isVirtual(), 3301 InitRange.getBegin(), 3302 BaseInit.getAs<Expr>(), 3303 InitRange.getEnd(), EllipsisLoc); 3304 } 3305 3306 // Create a static_cast\<T&&>(expr). 3307 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3308 if (T.isNull()) T = E->getType(); 3309 QualType TargetType = SemaRef.BuildReferenceType( 3310 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3311 SourceLocation ExprLoc = E->getLocStart(); 3312 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3313 TargetType, ExprLoc); 3314 3315 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3316 SourceRange(ExprLoc, ExprLoc), 3317 E->getSourceRange()).get(); 3318 } 3319 3320 /// ImplicitInitializerKind - How an implicit base or member initializer should 3321 /// initialize its base or member. 3322 enum ImplicitInitializerKind { 3323 IIK_Default, 3324 IIK_Copy, 3325 IIK_Move, 3326 IIK_Inherit 3327 }; 3328 3329 static bool 3330 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3331 ImplicitInitializerKind ImplicitInitKind, 3332 CXXBaseSpecifier *BaseSpec, 3333 bool IsInheritedVirtualBase, 3334 CXXCtorInitializer *&CXXBaseInit) { 3335 InitializedEntity InitEntity 3336 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3337 IsInheritedVirtualBase); 3338 3339 ExprResult BaseInit; 3340 3341 switch (ImplicitInitKind) { 3342 case IIK_Inherit: { 3343 const CXXRecordDecl *Inherited = 3344 Constructor->getInheritedConstructor()->getParent(); 3345 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3346 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3347 // C++11 [class.inhctor]p8: 3348 // Each expression in the expression-list is of the form 3349 // static_cast<T&&>(p), where p is the name of the corresponding 3350 // constructor parameter and T is the declared type of p. 3351 SmallVector<Expr*, 16> Args; 3352 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3353 ParmVarDecl *PD = Constructor->getParamDecl(I); 3354 ExprResult ArgExpr = 3355 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3356 VK_LValue, SourceLocation()); 3357 if (ArgExpr.isInvalid()) 3358 return true; 3359 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3360 } 3361 3362 InitializationKind InitKind = InitializationKind::CreateDirect( 3363 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3364 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3365 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3366 break; 3367 } 3368 } 3369 // Fall through. 3370 case IIK_Default: { 3371 InitializationKind InitKind 3372 = InitializationKind::CreateDefault(Constructor->getLocation()); 3373 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3374 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3375 break; 3376 } 3377 3378 case IIK_Move: 3379 case IIK_Copy: { 3380 bool Moving = ImplicitInitKind == IIK_Move; 3381 ParmVarDecl *Param = Constructor->getParamDecl(0); 3382 QualType ParamType = Param->getType().getNonReferenceType(); 3383 3384 Expr *CopyCtorArg = 3385 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3386 SourceLocation(), Param, false, 3387 Constructor->getLocation(), ParamType, 3388 VK_LValue, nullptr); 3389 3390 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3391 3392 // Cast to the base class to avoid ambiguities. 3393 QualType ArgTy = 3394 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3395 ParamType.getQualifiers()); 3396 3397 if (Moving) { 3398 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3399 } 3400 3401 CXXCastPath BasePath; 3402 BasePath.push_back(BaseSpec); 3403 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3404 CK_UncheckedDerivedToBase, 3405 Moving ? VK_XValue : VK_LValue, 3406 &BasePath).get(); 3407 3408 InitializationKind InitKind 3409 = InitializationKind::CreateDirect(Constructor->getLocation(), 3410 SourceLocation(), SourceLocation()); 3411 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3412 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3413 break; 3414 } 3415 } 3416 3417 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3418 if (BaseInit.isInvalid()) 3419 return true; 3420 3421 CXXBaseInit = 3422 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3423 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3424 SourceLocation()), 3425 BaseSpec->isVirtual(), 3426 SourceLocation(), 3427 BaseInit.getAs<Expr>(), 3428 SourceLocation(), 3429 SourceLocation()); 3430 3431 return false; 3432 } 3433 3434 static bool RefersToRValueRef(Expr *MemRef) { 3435 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3436 return Referenced->getType()->isRValueReferenceType(); 3437 } 3438 3439 static bool 3440 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3441 ImplicitInitializerKind ImplicitInitKind, 3442 FieldDecl *Field, IndirectFieldDecl *Indirect, 3443 CXXCtorInitializer *&CXXMemberInit) { 3444 if (Field->isInvalidDecl()) 3445 return true; 3446 3447 SourceLocation Loc = Constructor->getLocation(); 3448 3449 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3450 bool Moving = ImplicitInitKind == IIK_Move; 3451 ParmVarDecl *Param = Constructor->getParamDecl(0); 3452 QualType ParamType = Param->getType().getNonReferenceType(); 3453 3454 // Suppress copying zero-width bitfields. 3455 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3456 return false; 3457 3458 Expr *MemberExprBase = 3459 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3460 SourceLocation(), Param, false, 3461 Loc, ParamType, VK_LValue, nullptr); 3462 3463 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3464 3465 if (Moving) { 3466 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3467 } 3468 3469 // Build a reference to this field within the parameter. 3470 CXXScopeSpec SS; 3471 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3472 Sema::LookupMemberName); 3473 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3474 : cast<ValueDecl>(Field), AS_public); 3475 MemberLookup.resolveKind(); 3476 ExprResult CtorArg 3477 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3478 ParamType, Loc, 3479 /*IsArrow=*/false, 3480 SS, 3481 /*TemplateKWLoc=*/SourceLocation(), 3482 /*FirstQualifierInScope=*/nullptr, 3483 MemberLookup, 3484 /*TemplateArgs=*/nullptr, 3485 /*S*/nullptr); 3486 if (CtorArg.isInvalid()) 3487 return true; 3488 3489 // C++11 [class.copy]p15: 3490 // - if a member m has rvalue reference type T&&, it is direct-initialized 3491 // with static_cast<T&&>(x.m); 3492 if (RefersToRValueRef(CtorArg.get())) { 3493 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3494 } 3495 3496 // When the field we are copying is an array, create index variables for 3497 // each dimension of the array. We use these index variables to subscript 3498 // the source array, and other clients (e.g., CodeGen) will perform the 3499 // necessary iteration with these index variables. 3500 SmallVector<VarDecl *, 4> IndexVariables; 3501 QualType BaseType = Field->getType(); 3502 QualType SizeType = SemaRef.Context.getSizeType(); 3503 bool InitializingArray = false; 3504 while (const ConstantArrayType *Array 3505 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3506 InitializingArray = true; 3507 // Create the iteration variable for this array index. 3508 IdentifierInfo *IterationVarName = nullptr; 3509 { 3510 SmallString<8> Str; 3511 llvm::raw_svector_ostream OS(Str); 3512 OS << "__i" << IndexVariables.size(); 3513 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3514 } 3515 VarDecl *IterationVar 3516 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3517 IterationVarName, SizeType, 3518 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3519 SC_None); 3520 IndexVariables.push_back(IterationVar); 3521 3522 // Create a reference to the iteration variable. 3523 ExprResult IterationVarRef 3524 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3525 assert(!IterationVarRef.isInvalid() && 3526 "Reference to invented variable cannot fail!"); 3527 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3528 assert(!IterationVarRef.isInvalid() && 3529 "Conversion of invented variable cannot fail!"); 3530 3531 // Subscript the array with this iteration variable. 3532 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3533 IterationVarRef.get(), 3534 Loc); 3535 if (CtorArg.isInvalid()) 3536 return true; 3537 3538 BaseType = Array->getElementType(); 3539 } 3540 3541 // The array subscript expression is an lvalue, which is wrong for moving. 3542 if (Moving && InitializingArray) 3543 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3544 3545 // Construct the entity that we will be initializing. For an array, this 3546 // will be first element in the array, which may require several levels 3547 // of array-subscript entities. 3548 SmallVector<InitializedEntity, 4> Entities; 3549 Entities.reserve(1 + IndexVariables.size()); 3550 if (Indirect) 3551 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3552 else 3553 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3554 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3555 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3556 0, 3557 Entities.back())); 3558 3559 // Direct-initialize to use the copy constructor. 3560 InitializationKind InitKind = 3561 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3562 3563 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3564 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 3565 CtorArgE); 3566 3567 ExprResult MemberInit 3568 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3569 MultiExprArg(&CtorArgE, 1)); 3570 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3571 if (MemberInit.isInvalid()) 3572 return true; 3573 3574 if (Indirect) { 3575 assert(IndexVariables.size() == 0 && 3576 "Indirect field improperly initialized"); 3577 CXXMemberInit 3578 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3579 Loc, Loc, 3580 MemberInit.getAs<Expr>(), 3581 Loc); 3582 } else 3583 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3584 Loc, MemberInit.getAs<Expr>(), 3585 Loc, 3586 IndexVariables.data(), 3587 IndexVariables.size()); 3588 return false; 3589 } 3590 3591 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3592 "Unhandled implicit init kind!"); 3593 3594 QualType FieldBaseElementType = 3595 SemaRef.Context.getBaseElementType(Field->getType()); 3596 3597 if (FieldBaseElementType->isRecordType()) { 3598 InitializedEntity InitEntity 3599 = Indirect? InitializedEntity::InitializeMember(Indirect) 3600 : InitializedEntity::InitializeMember(Field); 3601 InitializationKind InitKind = 3602 InitializationKind::CreateDefault(Loc); 3603 3604 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3605 ExprResult MemberInit = 3606 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3607 3608 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3609 if (MemberInit.isInvalid()) 3610 return true; 3611 3612 if (Indirect) 3613 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3614 Indirect, Loc, 3615 Loc, 3616 MemberInit.get(), 3617 Loc); 3618 else 3619 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3620 Field, Loc, Loc, 3621 MemberInit.get(), 3622 Loc); 3623 return false; 3624 } 3625 3626 if (!Field->getParent()->isUnion()) { 3627 if (FieldBaseElementType->isReferenceType()) { 3628 SemaRef.Diag(Constructor->getLocation(), 3629 diag::err_uninitialized_member_in_ctor) 3630 << (int)Constructor->isImplicit() 3631 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3632 << 0 << Field->getDeclName(); 3633 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3634 return true; 3635 } 3636 3637 if (FieldBaseElementType.isConstQualified()) { 3638 SemaRef.Diag(Constructor->getLocation(), 3639 diag::err_uninitialized_member_in_ctor) 3640 << (int)Constructor->isImplicit() 3641 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3642 << 1 << Field->getDeclName(); 3643 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3644 return true; 3645 } 3646 } 3647 3648 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3649 FieldBaseElementType->isObjCRetainableType() && 3650 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3651 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3652 // ARC: 3653 // Default-initialize Objective-C pointers to NULL. 3654 CXXMemberInit 3655 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3656 Loc, Loc, 3657 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3658 Loc); 3659 return false; 3660 } 3661 3662 // Nothing to initialize. 3663 CXXMemberInit = nullptr; 3664 return false; 3665 } 3666 3667 namespace { 3668 struct BaseAndFieldInfo { 3669 Sema &S; 3670 CXXConstructorDecl *Ctor; 3671 bool AnyErrorsInInits; 3672 ImplicitInitializerKind IIK; 3673 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3674 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3675 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3676 3677 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3678 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3679 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3680 if (Generated && Ctor->isCopyConstructor()) 3681 IIK = IIK_Copy; 3682 else if (Generated && Ctor->isMoveConstructor()) 3683 IIK = IIK_Move; 3684 else if (Ctor->getInheritedConstructor()) 3685 IIK = IIK_Inherit; 3686 else 3687 IIK = IIK_Default; 3688 } 3689 3690 bool isImplicitCopyOrMove() const { 3691 switch (IIK) { 3692 case IIK_Copy: 3693 case IIK_Move: 3694 return true; 3695 3696 case IIK_Default: 3697 case IIK_Inherit: 3698 return false; 3699 } 3700 3701 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3702 } 3703 3704 bool addFieldInitializer(CXXCtorInitializer *Init) { 3705 AllToInit.push_back(Init); 3706 3707 // Check whether this initializer makes the field "used". 3708 if (Init->getInit()->HasSideEffects(S.Context)) 3709 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3710 3711 return false; 3712 } 3713 3714 bool isInactiveUnionMember(FieldDecl *Field) { 3715 RecordDecl *Record = Field->getParent(); 3716 if (!Record->isUnion()) 3717 return false; 3718 3719 if (FieldDecl *Active = 3720 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3721 return Active != Field->getCanonicalDecl(); 3722 3723 // In an implicit copy or move constructor, ignore any in-class initializer. 3724 if (isImplicitCopyOrMove()) 3725 return true; 3726 3727 // If there's no explicit initialization, the field is active only if it 3728 // has an in-class initializer... 3729 if (Field->hasInClassInitializer()) 3730 return false; 3731 // ... or it's an anonymous struct or union whose class has an in-class 3732 // initializer. 3733 if (!Field->isAnonymousStructOrUnion()) 3734 return true; 3735 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3736 return !FieldRD->hasInClassInitializer(); 3737 } 3738 3739 /// \brief Determine whether the given field is, or is within, a union member 3740 /// that is inactive (because there was an initializer given for a different 3741 /// member of the union, or because the union was not initialized at all). 3742 bool isWithinInactiveUnionMember(FieldDecl *Field, 3743 IndirectFieldDecl *Indirect) { 3744 if (!Indirect) 3745 return isInactiveUnionMember(Field); 3746 3747 for (auto *C : Indirect->chain()) { 3748 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3749 if (Field && isInactiveUnionMember(Field)) 3750 return true; 3751 } 3752 return false; 3753 } 3754 }; 3755 } 3756 3757 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3758 /// array type. 3759 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3760 if (T->isIncompleteArrayType()) 3761 return true; 3762 3763 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3764 if (!ArrayT->getSize()) 3765 return true; 3766 3767 T = ArrayT->getElementType(); 3768 } 3769 3770 return false; 3771 } 3772 3773 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3774 FieldDecl *Field, 3775 IndirectFieldDecl *Indirect = nullptr) { 3776 if (Field->isInvalidDecl()) 3777 return false; 3778 3779 // Overwhelmingly common case: we have a direct initializer for this field. 3780 if (CXXCtorInitializer *Init = 3781 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3782 return Info.addFieldInitializer(Init); 3783 3784 // C++11 [class.base.init]p8: 3785 // if the entity is a non-static data member that has a 3786 // brace-or-equal-initializer and either 3787 // -- the constructor's class is a union and no other variant member of that 3788 // union is designated by a mem-initializer-id or 3789 // -- the constructor's class is not a union, and, if the entity is a member 3790 // of an anonymous union, no other member of that union is designated by 3791 // a mem-initializer-id, 3792 // the entity is initialized as specified in [dcl.init]. 3793 // 3794 // We also apply the same rules to handle anonymous structs within anonymous 3795 // unions. 3796 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3797 return false; 3798 3799 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3800 ExprResult DIE = 3801 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3802 if (DIE.isInvalid()) 3803 return true; 3804 CXXCtorInitializer *Init; 3805 if (Indirect) 3806 Init = new (SemaRef.Context) 3807 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3808 SourceLocation(), DIE.get(), SourceLocation()); 3809 else 3810 Init = new (SemaRef.Context) 3811 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3812 SourceLocation(), DIE.get(), SourceLocation()); 3813 return Info.addFieldInitializer(Init); 3814 } 3815 3816 // Don't initialize incomplete or zero-length arrays. 3817 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3818 return false; 3819 3820 // Don't try to build an implicit initializer if there were semantic 3821 // errors in any of the initializers (and therefore we might be 3822 // missing some that the user actually wrote). 3823 if (Info.AnyErrorsInInits) 3824 return false; 3825 3826 CXXCtorInitializer *Init = nullptr; 3827 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3828 Indirect, Init)) 3829 return true; 3830 3831 if (!Init) 3832 return false; 3833 3834 return Info.addFieldInitializer(Init); 3835 } 3836 3837 bool 3838 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3839 CXXCtorInitializer *Initializer) { 3840 assert(Initializer->isDelegatingInitializer()); 3841 Constructor->setNumCtorInitializers(1); 3842 CXXCtorInitializer **initializer = 3843 new (Context) CXXCtorInitializer*[1]; 3844 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3845 Constructor->setCtorInitializers(initializer); 3846 3847 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3848 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3849 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3850 } 3851 3852 DelegatingCtorDecls.push_back(Constructor); 3853 3854 DiagnoseUninitializedFields(*this, Constructor); 3855 3856 return false; 3857 } 3858 3859 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3860 ArrayRef<CXXCtorInitializer *> Initializers) { 3861 if (Constructor->isDependentContext()) { 3862 // Just store the initializers as written, they will be checked during 3863 // instantiation. 3864 if (!Initializers.empty()) { 3865 Constructor->setNumCtorInitializers(Initializers.size()); 3866 CXXCtorInitializer **baseOrMemberInitializers = 3867 new (Context) CXXCtorInitializer*[Initializers.size()]; 3868 memcpy(baseOrMemberInitializers, Initializers.data(), 3869 Initializers.size() * sizeof(CXXCtorInitializer*)); 3870 Constructor->setCtorInitializers(baseOrMemberInitializers); 3871 } 3872 3873 // Let template instantiation know whether we had errors. 3874 if (AnyErrors) 3875 Constructor->setInvalidDecl(); 3876 3877 return false; 3878 } 3879 3880 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3881 3882 // We need to build the initializer AST according to order of construction 3883 // and not what user specified in the Initializers list. 3884 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3885 if (!ClassDecl) 3886 return true; 3887 3888 bool HadError = false; 3889 3890 for (unsigned i = 0; i < Initializers.size(); i++) { 3891 CXXCtorInitializer *Member = Initializers[i]; 3892 3893 if (Member->isBaseInitializer()) 3894 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3895 else { 3896 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3897 3898 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3899 for (auto *C : F->chain()) { 3900 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3901 if (FD && FD->getParent()->isUnion()) 3902 Info.ActiveUnionMember.insert(std::make_pair( 3903 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3904 } 3905 } else if (FieldDecl *FD = Member->getMember()) { 3906 if (FD->getParent()->isUnion()) 3907 Info.ActiveUnionMember.insert(std::make_pair( 3908 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3909 } 3910 } 3911 } 3912 3913 // Keep track of the direct virtual bases. 3914 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3915 for (auto &I : ClassDecl->bases()) { 3916 if (I.isVirtual()) 3917 DirectVBases.insert(&I); 3918 } 3919 3920 // Push virtual bases before others. 3921 for (auto &VBase : ClassDecl->vbases()) { 3922 if (CXXCtorInitializer *Value 3923 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3924 // [class.base.init]p7, per DR257: 3925 // A mem-initializer where the mem-initializer-id names a virtual base 3926 // class is ignored during execution of a constructor of any class that 3927 // is not the most derived class. 3928 if (ClassDecl->isAbstract()) { 3929 // FIXME: Provide a fixit to remove the base specifier. This requires 3930 // tracking the location of the associated comma for a base specifier. 3931 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3932 << VBase.getType() << ClassDecl; 3933 DiagnoseAbstractType(ClassDecl); 3934 } 3935 3936 Info.AllToInit.push_back(Value); 3937 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3938 // [class.base.init]p8, per DR257: 3939 // If a given [...] base class is not named by a mem-initializer-id 3940 // [...] and the entity is not a virtual base class of an abstract 3941 // class, then [...] the entity is default-initialized. 3942 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3943 CXXCtorInitializer *CXXBaseInit; 3944 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3945 &VBase, IsInheritedVirtualBase, 3946 CXXBaseInit)) { 3947 HadError = true; 3948 continue; 3949 } 3950 3951 Info.AllToInit.push_back(CXXBaseInit); 3952 } 3953 } 3954 3955 // Non-virtual bases. 3956 for (auto &Base : ClassDecl->bases()) { 3957 // Virtuals are in the virtual base list and already constructed. 3958 if (Base.isVirtual()) 3959 continue; 3960 3961 if (CXXCtorInitializer *Value 3962 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3963 Info.AllToInit.push_back(Value); 3964 } else if (!AnyErrors) { 3965 CXXCtorInitializer *CXXBaseInit; 3966 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3967 &Base, /*IsInheritedVirtualBase=*/false, 3968 CXXBaseInit)) { 3969 HadError = true; 3970 continue; 3971 } 3972 3973 Info.AllToInit.push_back(CXXBaseInit); 3974 } 3975 } 3976 3977 // Fields. 3978 for (auto *Mem : ClassDecl->decls()) { 3979 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3980 // C++ [class.bit]p2: 3981 // A declaration for a bit-field that omits the identifier declares an 3982 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3983 // initialized. 3984 if (F->isUnnamedBitfield()) 3985 continue; 3986 3987 // If we're not generating the implicit copy/move constructor, then we'll 3988 // handle anonymous struct/union fields based on their individual 3989 // indirect fields. 3990 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3991 continue; 3992 3993 if (CollectFieldInitializer(*this, Info, F)) 3994 HadError = true; 3995 continue; 3996 } 3997 3998 // Beyond this point, we only consider default initialization. 3999 if (Info.isImplicitCopyOrMove()) 4000 continue; 4001 4002 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4003 if (F->getType()->isIncompleteArrayType()) { 4004 assert(ClassDecl->hasFlexibleArrayMember() && 4005 "Incomplete array type is not valid"); 4006 continue; 4007 } 4008 4009 // Initialize each field of an anonymous struct individually. 4010 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4011 HadError = true; 4012 4013 continue; 4014 } 4015 } 4016 4017 unsigned NumInitializers = Info.AllToInit.size(); 4018 if (NumInitializers > 0) { 4019 Constructor->setNumCtorInitializers(NumInitializers); 4020 CXXCtorInitializer **baseOrMemberInitializers = 4021 new (Context) CXXCtorInitializer*[NumInitializers]; 4022 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4023 NumInitializers * sizeof(CXXCtorInitializer*)); 4024 Constructor->setCtorInitializers(baseOrMemberInitializers); 4025 4026 // Constructors implicitly reference the base and member 4027 // destructors. 4028 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4029 Constructor->getParent()); 4030 } 4031 4032 return HadError; 4033 } 4034 4035 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4036 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4037 const RecordDecl *RD = RT->getDecl(); 4038 if (RD->isAnonymousStructOrUnion()) { 4039 for (auto *Field : RD->fields()) 4040 PopulateKeysForFields(Field, IdealInits); 4041 return; 4042 } 4043 } 4044 IdealInits.push_back(Field->getCanonicalDecl()); 4045 } 4046 4047 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4048 return Context.getCanonicalType(BaseType).getTypePtr(); 4049 } 4050 4051 static const void *GetKeyForMember(ASTContext &Context, 4052 CXXCtorInitializer *Member) { 4053 if (!Member->isAnyMemberInitializer()) 4054 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4055 4056 return Member->getAnyMember()->getCanonicalDecl(); 4057 } 4058 4059 static void DiagnoseBaseOrMemInitializerOrder( 4060 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4061 ArrayRef<CXXCtorInitializer *> Inits) { 4062 if (Constructor->getDeclContext()->isDependentContext()) 4063 return; 4064 4065 // Don't check initializers order unless the warning is enabled at the 4066 // location of at least one initializer. 4067 bool ShouldCheckOrder = false; 4068 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4069 CXXCtorInitializer *Init = Inits[InitIndex]; 4070 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4071 Init->getSourceLocation())) { 4072 ShouldCheckOrder = true; 4073 break; 4074 } 4075 } 4076 if (!ShouldCheckOrder) 4077 return; 4078 4079 // Build the list of bases and members in the order that they'll 4080 // actually be initialized. The explicit initializers should be in 4081 // this same order but may be missing things. 4082 SmallVector<const void*, 32> IdealInitKeys; 4083 4084 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4085 4086 // 1. Virtual bases. 4087 for (const auto &VBase : ClassDecl->vbases()) 4088 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4089 4090 // 2. Non-virtual bases. 4091 for (const auto &Base : ClassDecl->bases()) { 4092 if (Base.isVirtual()) 4093 continue; 4094 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4095 } 4096 4097 // 3. Direct fields. 4098 for (auto *Field : ClassDecl->fields()) { 4099 if (Field->isUnnamedBitfield()) 4100 continue; 4101 4102 PopulateKeysForFields(Field, IdealInitKeys); 4103 } 4104 4105 unsigned NumIdealInits = IdealInitKeys.size(); 4106 unsigned IdealIndex = 0; 4107 4108 CXXCtorInitializer *PrevInit = nullptr; 4109 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4110 CXXCtorInitializer *Init = Inits[InitIndex]; 4111 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4112 4113 // Scan forward to try to find this initializer in the idealized 4114 // initializers list. 4115 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4116 if (InitKey == IdealInitKeys[IdealIndex]) 4117 break; 4118 4119 // If we didn't find this initializer, it must be because we 4120 // scanned past it on a previous iteration. That can only 4121 // happen if we're out of order; emit a warning. 4122 if (IdealIndex == NumIdealInits && PrevInit) { 4123 Sema::SemaDiagnosticBuilder D = 4124 SemaRef.Diag(PrevInit->getSourceLocation(), 4125 diag::warn_initializer_out_of_order); 4126 4127 if (PrevInit->isAnyMemberInitializer()) 4128 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4129 else 4130 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4131 4132 if (Init->isAnyMemberInitializer()) 4133 D << 0 << Init->getAnyMember()->getDeclName(); 4134 else 4135 D << 1 << Init->getTypeSourceInfo()->getType(); 4136 4137 // Move back to the initializer's location in the ideal list. 4138 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4139 if (InitKey == IdealInitKeys[IdealIndex]) 4140 break; 4141 4142 assert(IdealIndex < NumIdealInits && 4143 "initializer not found in initializer list"); 4144 } 4145 4146 PrevInit = Init; 4147 } 4148 } 4149 4150 namespace { 4151 bool CheckRedundantInit(Sema &S, 4152 CXXCtorInitializer *Init, 4153 CXXCtorInitializer *&PrevInit) { 4154 if (!PrevInit) { 4155 PrevInit = Init; 4156 return false; 4157 } 4158 4159 if (FieldDecl *Field = Init->getAnyMember()) 4160 S.Diag(Init->getSourceLocation(), 4161 diag::err_multiple_mem_initialization) 4162 << Field->getDeclName() 4163 << Init->getSourceRange(); 4164 else { 4165 const Type *BaseClass = Init->getBaseClass(); 4166 assert(BaseClass && "neither field nor base"); 4167 S.Diag(Init->getSourceLocation(), 4168 diag::err_multiple_base_initialization) 4169 << QualType(BaseClass, 0) 4170 << Init->getSourceRange(); 4171 } 4172 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4173 << 0 << PrevInit->getSourceRange(); 4174 4175 return true; 4176 } 4177 4178 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4179 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4180 4181 bool CheckRedundantUnionInit(Sema &S, 4182 CXXCtorInitializer *Init, 4183 RedundantUnionMap &Unions) { 4184 FieldDecl *Field = Init->getAnyMember(); 4185 RecordDecl *Parent = Field->getParent(); 4186 NamedDecl *Child = Field; 4187 4188 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4189 if (Parent->isUnion()) { 4190 UnionEntry &En = Unions[Parent]; 4191 if (En.first && En.first != Child) { 4192 S.Diag(Init->getSourceLocation(), 4193 diag::err_multiple_mem_union_initialization) 4194 << Field->getDeclName() 4195 << Init->getSourceRange(); 4196 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4197 << 0 << En.second->getSourceRange(); 4198 return true; 4199 } 4200 if (!En.first) { 4201 En.first = Child; 4202 En.second = Init; 4203 } 4204 if (!Parent->isAnonymousStructOrUnion()) 4205 return false; 4206 } 4207 4208 Child = Parent; 4209 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4210 } 4211 4212 return false; 4213 } 4214 } 4215 4216 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4217 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4218 SourceLocation ColonLoc, 4219 ArrayRef<CXXCtorInitializer*> MemInits, 4220 bool AnyErrors) { 4221 if (!ConstructorDecl) 4222 return; 4223 4224 AdjustDeclIfTemplate(ConstructorDecl); 4225 4226 CXXConstructorDecl *Constructor 4227 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4228 4229 if (!Constructor) { 4230 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4231 return; 4232 } 4233 4234 // Mapping for the duplicate initializers check. 4235 // For member initializers, this is keyed with a FieldDecl*. 4236 // For base initializers, this is keyed with a Type*. 4237 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4238 4239 // Mapping for the inconsistent anonymous-union initializers check. 4240 RedundantUnionMap MemberUnions; 4241 4242 bool HadError = false; 4243 for (unsigned i = 0; i < MemInits.size(); i++) { 4244 CXXCtorInitializer *Init = MemInits[i]; 4245 4246 // Set the source order index. 4247 Init->setSourceOrder(i); 4248 4249 if (Init->isAnyMemberInitializer()) { 4250 const void *Key = GetKeyForMember(Context, Init); 4251 if (CheckRedundantInit(*this, Init, Members[Key]) || 4252 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4253 HadError = true; 4254 } else if (Init->isBaseInitializer()) { 4255 const void *Key = GetKeyForMember(Context, Init); 4256 if (CheckRedundantInit(*this, Init, Members[Key])) 4257 HadError = true; 4258 } else { 4259 assert(Init->isDelegatingInitializer()); 4260 // This must be the only initializer 4261 if (MemInits.size() != 1) { 4262 Diag(Init->getSourceLocation(), 4263 diag::err_delegating_initializer_alone) 4264 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4265 // We will treat this as being the only initializer. 4266 } 4267 SetDelegatingInitializer(Constructor, MemInits[i]); 4268 // Return immediately as the initializer is set. 4269 return; 4270 } 4271 } 4272 4273 if (HadError) 4274 return; 4275 4276 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4277 4278 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4279 4280 DiagnoseUninitializedFields(*this, Constructor); 4281 } 4282 4283 void 4284 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4285 CXXRecordDecl *ClassDecl) { 4286 // Ignore dependent contexts. Also ignore unions, since their members never 4287 // have destructors implicitly called. 4288 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4289 return; 4290 4291 // FIXME: all the access-control diagnostics are positioned on the 4292 // field/base declaration. That's probably good; that said, the 4293 // user might reasonably want to know why the destructor is being 4294 // emitted, and we currently don't say. 4295 4296 // Non-static data members. 4297 for (auto *Field : ClassDecl->fields()) { 4298 if (Field->isInvalidDecl()) 4299 continue; 4300 4301 // Don't destroy incomplete or zero-length arrays. 4302 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4303 continue; 4304 4305 QualType FieldType = Context.getBaseElementType(Field->getType()); 4306 4307 const RecordType* RT = FieldType->getAs<RecordType>(); 4308 if (!RT) 4309 continue; 4310 4311 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4312 if (FieldClassDecl->isInvalidDecl()) 4313 continue; 4314 if (FieldClassDecl->hasIrrelevantDestructor()) 4315 continue; 4316 // The destructor for an implicit anonymous union member is never invoked. 4317 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4318 continue; 4319 4320 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4321 assert(Dtor && "No dtor found for FieldClassDecl!"); 4322 CheckDestructorAccess(Field->getLocation(), Dtor, 4323 PDiag(diag::err_access_dtor_field) 4324 << Field->getDeclName() 4325 << FieldType); 4326 4327 MarkFunctionReferenced(Location, Dtor); 4328 DiagnoseUseOfDecl(Dtor, Location); 4329 } 4330 4331 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4332 4333 // Bases. 4334 for (const auto &Base : ClassDecl->bases()) { 4335 // Bases are always records in a well-formed non-dependent class. 4336 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4337 4338 // Remember direct virtual bases. 4339 if (Base.isVirtual()) 4340 DirectVirtualBases.insert(RT); 4341 4342 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4343 // If our base class is invalid, we probably can't get its dtor anyway. 4344 if (BaseClassDecl->isInvalidDecl()) 4345 continue; 4346 if (BaseClassDecl->hasIrrelevantDestructor()) 4347 continue; 4348 4349 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4350 assert(Dtor && "No dtor found for BaseClassDecl!"); 4351 4352 // FIXME: caret should be on the start of the class name 4353 CheckDestructorAccess(Base.getLocStart(), Dtor, 4354 PDiag(diag::err_access_dtor_base) 4355 << Base.getType() 4356 << Base.getSourceRange(), 4357 Context.getTypeDeclType(ClassDecl)); 4358 4359 MarkFunctionReferenced(Location, Dtor); 4360 DiagnoseUseOfDecl(Dtor, Location); 4361 } 4362 4363 // Virtual bases. 4364 for (const auto &VBase : ClassDecl->vbases()) { 4365 // Bases are always records in a well-formed non-dependent class. 4366 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4367 4368 // Ignore direct virtual bases. 4369 if (DirectVirtualBases.count(RT)) 4370 continue; 4371 4372 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4373 // If our base class is invalid, we probably can't get its dtor anyway. 4374 if (BaseClassDecl->isInvalidDecl()) 4375 continue; 4376 if (BaseClassDecl->hasIrrelevantDestructor()) 4377 continue; 4378 4379 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4380 assert(Dtor && "No dtor found for BaseClassDecl!"); 4381 if (CheckDestructorAccess( 4382 ClassDecl->getLocation(), Dtor, 4383 PDiag(diag::err_access_dtor_vbase) 4384 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4385 Context.getTypeDeclType(ClassDecl)) == 4386 AR_accessible) { 4387 CheckDerivedToBaseConversion( 4388 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4389 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4390 SourceRange(), DeclarationName(), nullptr); 4391 } 4392 4393 MarkFunctionReferenced(Location, Dtor); 4394 DiagnoseUseOfDecl(Dtor, Location); 4395 } 4396 } 4397 4398 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4399 if (!CDtorDecl) 4400 return; 4401 4402 if (CXXConstructorDecl *Constructor 4403 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4404 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4405 DiagnoseUninitializedFields(*this, Constructor); 4406 } 4407 } 4408 4409 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4410 unsigned DiagID, AbstractDiagSelID SelID) { 4411 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4412 unsigned DiagID; 4413 AbstractDiagSelID SelID; 4414 4415 public: 4416 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4417 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4418 4419 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4420 if (Suppressed) return; 4421 if (SelID == -1) 4422 S.Diag(Loc, DiagID) << T; 4423 else 4424 S.Diag(Loc, DiagID) << SelID << T; 4425 } 4426 } Diagnoser(DiagID, SelID); 4427 4428 return RequireNonAbstractType(Loc, T, Diagnoser); 4429 } 4430 4431 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4432 TypeDiagnoser &Diagnoser) { 4433 if (!getLangOpts().CPlusPlus) 4434 return false; 4435 4436 if (const ArrayType *AT = Context.getAsArrayType(T)) 4437 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4438 4439 if (const PointerType *PT = T->getAs<PointerType>()) { 4440 // Find the innermost pointer type. 4441 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4442 PT = T; 4443 4444 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4445 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4446 } 4447 4448 const RecordType *RT = T->getAs<RecordType>(); 4449 if (!RT) 4450 return false; 4451 4452 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4453 4454 // We can't answer whether something is abstract until it has a 4455 // definition. If it's currently being defined, we'll walk back 4456 // over all the declarations when we have a full definition. 4457 const CXXRecordDecl *Def = RD->getDefinition(); 4458 if (!Def || Def->isBeingDefined()) 4459 return false; 4460 4461 if (!RD->isAbstract()) 4462 return false; 4463 4464 Diagnoser.diagnose(*this, Loc, T); 4465 DiagnoseAbstractType(RD); 4466 4467 return true; 4468 } 4469 4470 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4471 // Check if we've already emitted the list of pure virtual functions 4472 // for this class. 4473 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4474 return; 4475 4476 // If the diagnostic is suppressed, don't emit the notes. We're only 4477 // going to emit them once, so try to attach them to a diagnostic we're 4478 // actually going to show. 4479 if (Diags.isLastDiagnosticIgnored()) 4480 return; 4481 4482 CXXFinalOverriderMap FinalOverriders; 4483 RD->getFinalOverriders(FinalOverriders); 4484 4485 // Keep a set of seen pure methods so we won't diagnose the same method 4486 // more than once. 4487 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4488 4489 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4490 MEnd = FinalOverriders.end(); 4491 M != MEnd; 4492 ++M) { 4493 for (OverridingMethods::iterator SO = M->second.begin(), 4494 SOEnd = M->second.end(); 4495 SO != SOEnd; ++SO) { 4496 // C++ [class.abstract]p4: 4497 // A class is abstract if it contains or inherits at least one 4498 // pure virtual function for which the final overrider is pure 4499 // virtual. 4500 4501 // 4502 if (SO->second.size() != 1) 4503 continue; 4504 4505 if (!SO->second.front().Method->isPure()) 4506 continue; 4507 4508 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4509 continue; 4510 4511 Diag(SO->second.front().Method->getLocation(), 4512 diag::note_pure_virtual_function) 4513 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4514 } 4515 } 4516 4517 if (!PureVirtualClassDiagSet) 4518 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4519 PureVirtualClassDiagSet->insert(RD); 4520 } 4521 4522 namespace { 4523 struct AbstractUsageInfo { 4524 Sema &S; 4525 CXXRecordDecl *Record; 4526 CanQualType AbstractType; 4527 bool Invalid; 4528 4529 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4530 : S(S), Record(Record), 4531 AbstractType(S.Context.getCanonicalType( 4532 S.Context.getTypeDeclType(Record))), 4533 Invalid(false) {} 4534 4535 void DiagnoseAbstractType() { 4536 if (Invalid) return; 4537 S.DiagnoseAbstractType(Record); 4538 Invalid = true; 4539 } 4540 4541 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4542 }; 4543 4544 struct CheckAbstractUsage { 4545 AbstractUsageInfo &Info; 4546 const NamedDecl *Ctx; 4547 4548 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4549 : Info(Info), Ctx(Ctx) {} 4550 4551 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4552 switch (TL.getTypeLocClass()) { 4553 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4554 #define TYPELOC(CLASS, PARENT) \ 4555 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4556 #include "clang/AST/TypeLocNodes.def" 4557 } 4558 } 4559 4560 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4561 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4562 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4563 if (!TL.getParam(I)) 4564 continue; 4565 4566 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4567 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4568 } 4569 } 4570 4571 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4572 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4573 } 4574 4575 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4576 // Visit the type parameters from a permissive context. 4577 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4578 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4579 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4580 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4581 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4582 // TODO: other template argument types? 4583 } 4584 } 4585 4586 // Visit pointee types from a permissive context. 4587 #define CheckPolymorphic(Type) \ 4588 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4589 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4590 } 4591 CheckPolymorphic(PointerTypeLoc) 4592 CheckPolymorphic(ReferenceTypeLoc) 4593 CheckPolymorphic(MemberPointerTypeLoc) 4594 CheckPolymorphic(BlockPointerTypeLoc) 4595 CheckPolymorphic(AtomicTypeLoc) 4596 4597 /// Handle all the types we haven't given a more specific 4598 /// implementation for above. 4599 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4600 // Every other kind of type that we haven't called out already 4601 // that has an inner type is either (1) sugar or (2) contains that 4602 // inner type in some way as a subobject. 4603 if (TypeLoc Next = TL.getNextTypeLoc()) 4604 return Visit(Next, Sel); 4605 4606 // If there's no inner type and we're in a permissive context, 4607 // don't diagnose. 4608 if (Sel == Sema::AbstractNone) return; 4609 4610 // Check whether the type matches the abstract type. 4611 QualType T = TL.getType(); 4612 if (T->isArrayType()) { 4613 Sel = Sema::AbstractArrayType; 4614 T = Info.S.Context.getBaseElementType(T); 4615 } 4616 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4617 if (CT != Info.AbstractType) return; 4618 4619 // It matched; do some magic. 4620 if (Sel == Sema::AbstractArrayType) { 4621 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4622 << T << TL.getSourceRange(); 4623 } else { 4624 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4625 << Sel << T << TL.getSourceRange(); 4626 } 4627 Info.DiagnoseAbstractType(); 4628 } 4629 }; 4630 4631 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4632 Sema::AbstractDiagSelID Sel) { 4633 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4634 } 4635 4636 } 4637 4638 /// Check for invalid uses of an abstract type in a method declaration. 4639 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4640 CXXMethodDecl *MD) { 4641 // No need to do the check on definitions, which require that 4642 // the return/param types be complete. 4643 if (MD->doesThisDeclarationHaveABody()) 4644 return; 4645 4646 // For safety's sake, just ignore it if we don't have type source 4647 // information. This should never happen for non-implicit methods, 4648 // but... 4649 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4650 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4651 } 4652 4653 /// Check for invalid uses of an abstract type within a class definition. 4654 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4655 CXXRecordDecl *RD) { 4656 for (auto *D : RD->decls()) { 4657 if (D->isImplicit()) continue; 4658 4659 // Methods and method templates. 4660 if (isa<CXXMethodDecl>(D)) { 4661 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4662 } else if (isa<FunctionTemplateDecl>(D)) { 4663 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4664 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4665 4666 // Fields and static variables. 4667 } else if (isa<FieldDecl>(D)) { 4668 FieldDecl *FD = cast<FieldDecl>(D); 4669 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4670 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4671 } else if (isa<VarDecl>(D)) { 4672 VarDecl *VD = cast<VarDecl>(D); 4673 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4674 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4675 4676 // Nested classes and class templates. 4677 } else if (isa<CXXRecordDecl>(D)) { 4678 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4679 } else if (isa<ClassTemplateDecl>(D)) { 4680 CheckAbstractClassUsage(Info, 4681 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4682 } 4683 } 4684 } 4685 4686 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 4687 Attr *ClassAttr = getDLLAttr(Class); 4688 if (!ClassAttr) 4689 return; 4690 4691 assert(ClassAttr->getKind() == attr::DLLExport); 4692 4693 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4694 4695 if (TSK == TSK_ExplicitInstantiationDeclaration) 4696 // Don't go any further if this is just an explicit instantiation 4697 // declaration. 4698 return; 4699 4700 for (Decl *Member : Class->decls()) { 4701 auto *MD = dyn_cast<CXXMethodDecl>(Member); 4702 if (!MD) 4703 continue; 4704 4705 if (Member->getAttr<DLLExportAttr>()) { 4706 if (MD->isUserProvided()) { 4707 // Instantiate non-default class member functions ... 4708 4709 // .. except for certain kinds of template specializations. 4710 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4711 continue; 4712 4713 S.MarkFunctionReferenced(Class->getLocation(), MD); 4714 4715 // The function will be passed to the consumer when its definition is 4716 // encountered. 4717 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4718 MD->isCopyAssignmentOperator() || 4719 MD->isMoveAssignmentOperator()) { 4720 // Synthesize and instantiate non-trivial implicit methods, explicitly 4721 // defaulted methods, and the copy and move assignment operators. The 4722 // latter are exported even if they are trivial, because the address of 4723 // an operator can be taken and should compare equal accross libraries. 4724 DiagnosticErrorTrap Trap(S.Diags); 4725 S.MarkFunctionReferenced(Class->getLocation(), MD); 4726 if (Trap.hasErrorOccurred()) { 4727 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 4728 << Class->getName() << !S.getLangOpts().CPlusPlus11; 4729 break; 4730 } 4731 4732 // There is no later point when we will see the definition of this 4733 // function, so pass it to the consumer now. 4734 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 4735 } 4736 } 4737 } 4738 } 4739 4740 /// \brief Check class-level dllimport/dllexport attribute. 4741 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 4742 Attr *ClassAttr = getDLLAttr(Class); 4743 4744 // MSVC inherits DLL attributes to partial class template specializations. 4745 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4746 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4747 if (Attr *TemplateAttr = 4748 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4749 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 4750 A->setInherited(true); 4751 ClassAttr = A; 4752 } 4753 } 4754 } 4755 4756 if (!ClassAttr) 4757 return; 4758 4759 if (!Class->isExternallyVisible()) { 4760 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4761 << Class << ClassAttr; 4762 return; 4763 } 4764 4765 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 4766 !ClassAttr->isInherited()) { 4767 // Diagnose dll attributes on members of class with dll attribute. 4768 for (Decl *Member : Class->decls()) { 4769 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4770 continue; 4771 InheritableAttr *MemberAttr = getDLLAttr(Member); 4772 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4773 continue; 4774 4775 Diag(MemberAttr->getLocation(), 4776 diag::err_attribute_dll_member_of_dll_class) 4777 << MemberAttr << ClassAttr; 4778 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4779 Member->setInvalidDecl(); 4780 } 4781 } 4782 4783 if (Class->getDescribedClassTemplate()) 4784 // Don't inherit dll attribute until the template is instantiated. 4785 return; 4786 4787 // The class is either imported or exported. 4788 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4789 const bool ClassImported = !ClassExported; 4790 4791 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4792 4793 // Ignore explicit dllexport on explicit class template instantiation declarations. 4794 if (ClassExported && !ClassAttr->isInherited() && 4795 TSK == TSK_ExplicitInstantiationDeclaration) { 4796 Class->dropAttr<DLLExportAttr>(); 4797 return; 4798 } 4799 4800 // Force declaration of implicit members so they can inherit the attribute. 4801 ForceDeclarationOfImplicitMembers(Class); 4802 4803 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4804 // seem to be true in practice? 4805 4806 for (Decl *Member : Class->decls()) { 4807 VarDecl *VD = dyn_cast<VarDecl>(Member); 4808 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4809 4810 // Only methods and static fields inherit the attributes. 4811 if (!VD && !MD) 4812 continue; 4813 4814 if (MD) { 4815 // Don't process deleted methods. 4816 if (MD->isDeleted()) 4817 continue; 4818 4819 if (MD->isInlined()) { 4820 // MinGW does not import or export inline methods. 4821 if (!Context.getTargetInfo().getCXXABI().isMicrosoft()) 4822 continue; 4823 4824 // MSVC versions before 2015 don't export the move assignment operators, 4825 // so don't attempt to import them if we have a definition. 4826 if (ClassImported && MD->isMoveAssignmentOperator() && 4827 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 4828 continue; 4829 } 4830 } 4831 4832 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 4833 continue; 4834 4835 if (!getDLLAttr(Member)) { 4836 auto *NewAttr = 4837 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 4838 NewAttr->setInherited(true); 4839 Member->addAttr(NewAttr); 4840 } 4841 } 4842 4843 if (ClassExported) 4844 DelayedDllExportClasses.push_back(Class); 4845 } 4846 4847 /// \brief Perform propagation of DLL attributes from a derived class to a 4848 /// templated base class for MS compatibility. 4849 void Sema::propagateDLLAttrToBaseClassTemplate( 4850 CXXRecordDecl *Class, Attr *ClassAttr, 4851 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 4852 if (getDLLAttr( 4853 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 4854 // If the base class template has a DLL attribute, don't try to change it. 4855 return; 4856 } 4857 4858 auto TSK = BaseTemplateSpec->getSpecializationKind(); 4859 if (!getDLLAttr(BaseTemplateSpec) && 4860 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 4861 TSK == TSK_ImplicitInstantiation)) { 4862 // The template hasn't been instantiated yet (or it has, but only as an 4863 // explicit instantiation declaration or implicit instantiation, which means 4864 // we haven't codegenned any members yet), so propagate the attribute. 4865 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 4866 NewAttr->setInherited(true); 4867 BaseTemplateSpec->addAttr(NewAttr); 4868 4869 // If the template is already instantiated, checkDLLAttributeRedeclaration() 4870 // needs to be run again to work see the new attribute. Otherwise this will 4871 // get run whenever the template is instantiated. 4872 if (TSK != TSK_Undeclared) 4873 checkClassLevelDLLAttribute(BaseTemplateSpec); 4874 4875 return; 4876 } 4877 4878 if (getDLLAttr(BaseTemplateSpec)) { 4879 // The template has already been specialized or instantiated with an 4880 // attribute, explicitly or through propagation. We should not try to change 4881 // it. 4882 return; 4883 } 4884 4885 // The template was previously instantiated or explicitly specialized without 4886 // a dll attribute, It's too late for us to add an attribute, so warn that 4887 // this is unsupported. 4888 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 4889 << BaseTemplateSpec->isExplicitSpecialization(); 4890 Diag(ClassAttr->getLocation(), diag::note_attribute); 4891 if (BaseTemplateSpec->isExplicitSpecialization()) { 4892 Diag(BaseTemplateSpec->getLocation(), 4893 diag::note_template_class_explicit_specialization_was_here) 4894 << BaseTemplateSpec; 4895 } else { 4896 Diag(BaseTemplateSpec->getPointOfInstantiation(), 4897 diag::note_template_class_instantiation_was_here) 4898 << BaseTemplateSpec; 4899 } 4900 } 4901 4902 /// \brief Perform semantic checks on a class definition that has been 4903 /// completing, introducing implicitly-declared members, checking for 4904 /// abstract types, etc. 4905 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4906 if (!Record) 4907 return; 4908 4909 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4910 AbstractUsageInfo Info(*this, Record); 4911 CheckAbstractClassUsage(Info, Record); 4912 } 4913 4914 // If this is not an aggregate type and has no user-declared constructor, 4915 // complain about any non-static data members of reference or const scalar 4916 // type, since they will never get initializers. 4917 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4918 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4919 !Record->isLambda()) { 4920 bool Complained = false; 4921 for (const auto *F : Record->fields()) { 4922 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4923 continue; 4924 4925 if (F->getType()->isReferenceType() || 4926 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4927 if (!Complained) { 4928 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4929 << Record->getTagKind() << Record; 4930 Complained = true; 4931 } 4932 4933 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4934 << F->getType()->isReferenceType() 4935 << F->getDeclName(); 4936 } 4937 } 4938 } 4939 4940 if (Record->getIdentifier()) { 4941 // C++ [class.mem]p13: 4942 // If T is the name of a class, then each of the following shall have a 4943 // name different from T: 4944 // - every member of every anonymous union that is a member of class T. 4945 // 4946 // C++ [class.mem]p14: 4947 // In addition, if class T has a user-declared constructor (12.1), every 4948 // non-static data member of class T shall have a name different from T. 4949 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4950 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4951 ++I) { 4952 NamedDecl *D = *I; 4953 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4954 isa<IndirectFieldDecl>(D)) { 4955 Diag(D->getLocation(), diag::err_member_name_of_class) 4956 << D->getDeclName(); 4957 break; 4958 } 4959 } 4960 } 4961 4962 // Warn if the class has virtual methods but non-virtual public destructor. 4963 if (Record->isPolymorphic() && !Record->isDependentType()) { 4964 CXXDestructorDecl *dtor = Record->getDestructor(); 4965 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4966 !Record->hasAttr<FinalAttr>()) 4967 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4968 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4969 } 4970 4971 if (Record->isAbstract()) { 4972 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4973 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4974 << FA->isSpelledAsSealed(); 4975 DiagnoseAbstractType(Record); 4976 } 4977 } 4978 4979 bool HasMethodWithOverrideControl = false, 4980 HasOverridingMethodWithoutOverrideControl = false; 4981 if (!Record->isDependentType()) { 4982 for (auto *M : Record->methods()) { 4983 // See if a method overloads virtual methods in a base 4984 // class without overriding any. 4985 if (!M->isStatic()) 4986 DiagnoseHiddenVirtualMethods(M); 4987 if (M->hasAttr<OverrideAttr>()) 4988 HasMethodWithOverrideControl = true; 4989 else if (M->size_overridden_methods() > 0) 4990 HasOverridingMethodWithoutOverrideControl = true; 4991 // Check whether the explicitly-defaulted special members are valid. 4992 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4993 CheckExplicitlyDefaultedSpecialMember(M); 4994 4995 // For an explicitly defaulted or deleted special member, we defer 4996 // determining triviality until the class is complete. That time is now! 4997 if (!M->isImplicit() && !M->isUserProvided()) { 4998 CXXSpecialMember CSM = getSpecialMember(M); 4999 if (CSM != CXXInvalid) { 5000 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5001 5002 // Inform the class that we've finished declaring this member. 5003 Record->finishedDefaultedOrDeletedMember(M); 5004 } 5005 } 5006 } 5007 } 5008 5009 if (HasMethodWithOverrideControl && 5010 HasOverridingMethodWithoutOverrideControl) { 5011 // At least one method has the 'override' control declared. 5012 // Diagnose all other overridden methods which do not have 'override' specified on them. 5013 for (auto *M : Record->methods()) 5014 DiagnoseAbsenceOfOverrideControl(M); 5015 } 5016 5017 // ms_struct is a request to use the same ABI rules as MSVC. Check 5018 // whether this class uses any C++ features that are implemented 5019 // completely differently in MSVC, and if so, emit a diagnostic. 5020 // That diagnostic defaults to an error, but we allow projects to 5021 // map it down to a warning (or ignore it). It's a fairly common 5022 // practice among users of the ms_struct pragma to mass-annotate 5023 // headers, sweeping up a bunch of types that the project doesn't 5024 // really rely on MSVC-compatible layout for. We must therefore 5025 // support "ms_struct except for C++ stuff" as a secondary ABI. 5026 if (Record->isMsStruct(Context) && 5027 (Record->isPolymorphic() || Record->getNumBases())) { 5028 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5029 } 5030 5031 // Declare inheriting constructors. We do this eagerly here because: 5032 // - The standard requires an eager diagnostic for conflicting inheriting 5033 // constructors from different classes. 5034 // - The lazy declaration of the other implicit constructors is so as to not 5035 // waste space and performance on classes that are not meant to be 5036 // instantiated (e.g. meta-functions). This doesn't apply to classes that 5037 // have inheriting constructors. 5038 DeclareInheritingConstructors(Record); 5039 5040 checkClassLevelDLLAttribute(Record); 5041 } 5042 5043 /// Look up the special member function that would be called by a special 5044 /// member function for a subobject of class type. 5045 /// 5046 /// \param Class The class type of the subobject. 5047 /// \param CSM The kind of special member function. 5048 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5049 /// \param ConstRHS True if this is a copy operation with a const object 5050 /// on its RHS, that is, if the argument to the outer special member 5051 /// function is 'const' and this is not a field marked 'mutable'. 5052 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 5053 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5054 unsigned FieldQuals, bool ConstRHS) { 5055 unsigned LHSQuals = 0; 5056 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5057 LHSQuals = FieldQuals; 5058 5059 unsigned RHSQuals = FieldQuals; 5060 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5061 RHSQuals = 0; 5062 else if (ConstRHS) 5063 RHSQuals |= Qualifiers::Const; 5064 5065 return S.LookupSpecialMember(Class, CSM, 5066 RHSQuals & Qualifiers::Const, 5067 RHSQuals & Qualifiers::Volatile, 5068 false, 5069 LHSQuals & Qualifiers::Const, 5070 LHSQuals & Qualifiers::Volatile); 5071 } 5072 5073 /// Is the special member function which would be selected to perform the 5074 /// specified operation on the specified class type a constexpr constructor? 5075 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5076 Sema::CXXSpecialMember CSM, 5077 unsigned Quals, bool ConstRHS) { 5078 Sema::SpecialMemberOverloadResult *SMOR = 5079 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5080 if (!SMOR || !SMOR->getMethod()) 5081 // A constructor we wouldn't select can't be "involved in initializing" 5082 // anything. 5083 return true; 5084 return SMOR->getMethod()->isConstexpr(); 5085 } 5086 5087 /// Determine whether the specified special member function would be constexpr 5088 /// if it were implicitly defined. 5089 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5090 Sema::CXXSpecialMember CSM, 5091 bool ConstArg) { 5092 if (!S.getLangOpts().CPlusPlus11) 5093 return false; 5094 5095 // C++11 [dcl.constexpr]p4: 5096 // In the definition of a constexpr constructor [...] 5097 bool Ctor = true; 5098 switch (CSM) { 5099 case Sema::CXXDefaultConstructor: 5100 // Since default constructor lookup is essentially trivial (and cannot 5101 // involve, for instance, template instantiation), we compute whether a 5102 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5103 // 5104 // This is important for performance; we need to know whether the default 5105 // constructor is constexpr to determine whether the type is a literal type. 5106 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5107 5108 case Sema::CXXCopyConstructor: 5109 case Sema::CXXMoveConstructor: 5110 // For copy or move constructors, we need to perform overload resolution. 5111 break; 5112 5113 case Sema::CXXCopyAssignment: 5114 case Sema::CXXMoveAssignment: 5115 if (!S.getLangOpts().CPlusPlus14) 5116 return false; 5117 // In C++1y, we need to perform overload resolution. 5118 Ctor = false; 5119 break; 5120 5121 case Sema::CXXDestructor: 5122 case Sema::CXXInvalid: 5123 return false; 5124 } 5125 5126 // -- if the class is a non-empty union, or for each non-empty anonymous 5127 // union member of a non-union class, exactly one non-static data member 5128 // shall be initialized; [DR1359] 5129 // 5130 // If we squint, this is guaranteed, since exactly one non-static data member 5131 // will be initialized (if the constructor isn't deleted), we just don't know 5132 // which one. 5133 if (Ctor && ClassDecl->isUnion()) 5134 return true; 5135 5136 // -- the class shall not have any virtual base classes; 5137 if (Ctor && ClassDecl->getNumVBases()) 5138 return false; 5139 5140 // C++1y [class.copy]p26: 5141 // -- [the class] is a literal type, and 5142 if (!Ctor && !ClassDecl->isLiteral()) 5143 return false; 5144 5145 // -- every constructor involved in initializing [...] base class 5146 // sub-objects shall be a constexpr constructor; 5147 // -- the assignment operator selected to copy/move each direct base 5148 // class is a constexpr function, and 5149 for (const auto &B : ClassDecl->bases()) { 5150 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5151 if (!BaseType) continue; 5152 5153 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5154 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5155 return false; 5156 } 5157 5158 // -- every constructor involved in initializing non-static data members 5159 // [...] shall be a constexpr constructor; 5160 // -- every non-static data member and base class sub-object shall be 5161 // initialized 5162 // -- for each non-static data member of X that is of class type (or array 5163 // thereof), the assignment operator selected to copy/move that member is 5164 // a constexpr function 5165 for (const auto *F : ClassDecl->fields()) { 5166 if (F->isInvalidDecl()) 5167 continue; 5168 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5169 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5170 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5171 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5172 BaseType.getCVRQualifiers(), 5173 ConstArg && !F->isMutable())) 5174 return false; 5175 } 5176 } 5177 5178 // All OK, it's constexpr! 5179 return true; 5180 } 5181 5182 static Sema::ImplicitExceptionSpecification 5183 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5184 switch (S.getSpecialMember(MD)) { 5185 case Sema::CXXDefaultConstructor: 5186 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5187 case Sema::CXXCopyConstructor: 5188 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5189 case Sema::CXXCopyAssignment: 5190 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5191 case Sema::CXXMoveConstructor: 5192 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5193 case Sema::CXXMoveAssignment: 5194 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5195 case Sema::CXXDestructor: 5196 return S.ComputeDefaultedDtorExceptionSpec(MD); 5197 case Sema::CXXInvalid: 5198 break; 5199 } 5200 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5201 "only special members have implicit exception specs"); 5202 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5203 } 5204 5205 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5206 CXXMethodDecl *MD) { 5207 FunctionProtoType::ExtProtoInfo EPI; 5208 5209 // Build an exception specification pointing back at this member. 5210 EPI.ExceptionSpec.Type = EST_Unevaluated; 5211 EPI.ExceptionSpec.SourceDecl = MD; 5212 5213 // Set the calling convention to the default for C++ instance methods. 5214 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5215 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5216 /*IsCXXMethod=*/true)); 5217 return EPI; 5218 } 5219 5220 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5221 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5222 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5223 return; 5224 5225 // Evaluate the exception specification. 5226 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5227 5228 // Update the type of the special member to use it. 5229 UpdateExceptionSpec(MD, ESI); 5230 5231 // A user-provided destructor can be defined outside the class. When that 5232 // happens, be sure to update the exception specification on both 5233 // declarations. 5234 const FunctionProtoType *CanonicalFPT = 5235 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5236 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5237 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5238 } 5239 5240 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5241 CXXRecordDecl *RD = MD->getParent(); 5242 CXXSpecialMember CSM = getSpecialMember(MD); 5243 5244 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5245 "not an explicitly-defaulted special member"); 5246 5247 // Whether this was the first-declared instance of the constructor. 5248 // This affects whether we implicitly add an exception spec and constexpr. 5249 bool First = MD == MD->getCanonicalDecl(); 5250 5251 bool HadError = false; 5252 5253 // C++11 [dcl.fct.def.default]p1: 5254 // A function that is explicitly defaulted shall 5255 // -- be a special member function (checked elsewhere), 5256 // -- have the same type (except for ref-qualifiers, and except that a 5257 // copy operation can take a non-const reference) as an implicit 5258 // declaration, and 5259 // -- not have default arguments. 5260 unsigned ExpectedParams = 1; 5261 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5262 ExpectedParams = 0; 5263 if (MD->getNumParams() != ExpectedParams) { 5264 // This also checks for default arguments: a copy or move constructor with a 5265 // default argument is classified as a default constructor, and assignment 5266 // operations and destructors can't have default arguments. 5267 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5268 << CSM << MD->getSourceRange(); 5269 HadError = true; 5270 } else if (MD->isVariadic()) { 5271 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5272 << CSM << MD->getSourceRange(); 5273 HadError = true; 5274 } 5275 5276 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5277 5278 bool CanHaveConstParam = false; 5279 if (CSM == CXXCopyConstructor) 5280 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5281 else if (CSM == CXXCopyAssignment) 5282 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5283 5284 QualType ReturnType = Context.VoidTy; 5285 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5286 // Check for return type matching. 5287 ReturnType = Type->getReturnType(); 5288 QualType ExpectedReturnType = 5289 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5290 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5291 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5292 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5293 HadError = true; 5294 } 5295 5296 // A defaulted special member cannot have cv-qualifiers. 5297 if (Type->getTypeQuals()) { 5298 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5299 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5300 HadError = true; 5301 } 5302 } 5303 5304 // Check for parameter type matching. 5305 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5306 bool HasConstParam = false; 5307 if (ExpectedParams && ArgType->isReferenceType()) { 5308 // Argument must be reference to possibly-const T. 5309 QualType ReferentType = ArgType->getPointeeType(); 5310 HasConstParam = ReferentType.isConstQualified(); 5311 5312 if (ReferentType.isVolatileQualified()) { 5313 Diag(MD->getLocation(), 5314 diag::err_defaulted_special_member_volatile_param) << CSM; 5315 HadError = true; 5316 } 5317 5318 if (HasConstParam && !CanHaveConstParam) { 5319 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5320 Diag(MD->getLocation(), 5321 diag::err_defaulted_special_member_copy_const_param) 5322 << (CSM == CXXCopyAssignment); 5323 // FIXME: Explain why this special member can't be const. 5324 } else { 5325 Diag(MD->getLocation(), 5326 diag::err_defaulted_special_member_move_const_param) 5327 << (CSM == CXXMoveAssignment); 5328 } 5329 HadError = true; 5330 } 5331 } else if (ExpectedParams) { 5332 // A copy assignment operator can take its argument by value, but a 5333 // defaulted one cannot. 5334 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5335 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5336 HadError = true; 5337 } 5338 5339 // C++11 [dcl.fct.def.default]p2: 5340 // An explicitly-defaulted function may be declared constexpr only if it 5341 // would have been implicitly declared as constexpr, 5342 // Do not apply this rule to members of class templates, since core issue 1358 5343 // makes such functions always instantiate to constexpr functions. For 5344 // functions which cannot be constexpr (for non-constructors in C++11 and for 5345 // destructors in C++1y), this is checked elsewhere. 5346 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5347 HasConstParam); 5348 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5349 : isa<CXXConstructorDecl>(MD)) && 5350 MD->isConstexpr() && !Constexpr && 5351 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5352 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5353 // FIXME: Explain why the special member can't be constexpr. 5354 HadError = true; 5355 } 5356 5357 // and may have an explicit exception-specification only if it is compatible 5358 // with the exception-specification on the implicit declaration. 5359 if (Type->hasExceptionSpec()) { 5360 // Delay the check if this is the first declaration of the special member, 5361 // since we may not have parsed some necessary in-class initializers yet. 5362 if (First) { 5363 // If the exception specification needs to be instantiated, do so now, 5364 // before we clobber it with an EST_Unevaluated specification below. 5365 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5366 InstantiateExceptionSpec(MD->getLocStart(), MD); 5367 Type = MD->getType()->getAs<FunctionProtoType>(); 5368 } 5369 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5370 } else 5371 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5372 } 5373 5374 // If a function is explicitly defaulted on its first declaration, 5375 if (First) { 5376 // -- it is implicitly considered to be constexpr if the implicit 5377 // definition would be, 5378 MD->setConstexpr(Constexpr); 5379 5380 // -- it is implicitly considered to have the same exception-specification 5381 // as if it had been implicitly declared, 5382 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5383 EPI.ExceptionSpec.Type = EST_Unevaluated; 5384 EPI.ExceptionSpec.SourceDecl = MD; 5385 MD->setType(Context.getFunctionType(ReturnType, 5386 llvm::makeArrayRef(&ArgType, 5387 ExpectedParams), 5388 EPI)); 5389 } 5390 5391 if (ShouldDeleteSpecialMember(MD, CSM)) { 5392 if (First) { 5393 SetDeclDeleted(MD, MD->getLocation()); 5394 } else { 5395 // C++11 [dcl.fct.def.default]p4: 5396 // [For a] user-provided explicitly-defaulted function [...] if such a 5397 // function is implicitly defined as deleted, the program is ill-formed. 5398 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5399 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5400 HadError = true; 5401 } 5402 } 5403 5404 if (HadError) 5405 MD->setInvalidDecl(); 5406 } 5407 5408 /// Check whether the exception specification provided for an 5409 /// explicitly-defaulted special member matches the exception specification 5410 /// that would have been generated for an implicit special member, per 5411 /// C++11 [dcl.fct.def.default]p2. 5412 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5413 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5414 // If the exception specification was explicitly specified but hadn't been 5415 // parsed when the method was defaulted, grab it now. 5416 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5417 SpecifiedType = 5418 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5419 5420 // Compute the implicit exception specification. 5421 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5422 /*IsCXXMethod=*/true); 5423 FunctionProtoType::ExtProtoInfo EPI(CC); 5424 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5425 .getExceptionSpec(); 5426 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5427 Context.getFunctionType(Context.VoidTy, None, EPI)); 5428 5429 // Ensure that it matches. 5430 CheckEquivalentExceptionSpec( 5431 PDiag(diag::err_incorrect_defaulted_exception_spec) 5432 << getSpecialMember(MD), PDiag(), 5433 ImplicitType, SourceLocation(), 5434 SpecifiedType, MD->getLocation()); 5435 } 5436 5437 void Sema::CheckDelayedMemberExceptionSpecs() { 5438 decltype(DelayedExceptionSpecChecks) Checks; 5439 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5440 5441 std::swap(Checks, DelayedExceptionSpecChecks); 5442 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5443 5444 // Perform any deferred checking of exception specifications for virtual 5445 // destructors. 5446 for (auto &Check : Checks) 5447 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5448 5449 // Check that any explicitly-defaulted methods have exception specifications 5450 // compatible with their implicit exception specifications. 5451 for (auto &Spec : Specs) 5452 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5453 } 5454 5455 namespace { 5456 struct SpecialMemberDeletionInfo { 5457 Sema &S; 5458 CXXMethodDecl *MD; 5459 Sema::CXXSpecialMember CSM; 5460 bool Diagnose; 5461 5462 // Properties of the special member, computed for convenience. 5463 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5464 SourceLocation Loc; 5465 5466 bool AllFieldsAreConst; 5467 5468 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5469 Sema::CXXSpecialMember CSM, bool Diagnose) 5470 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5471 IsConstructor(false), IsAssignment(false), IsMove(false), 5472 ConstArg(false), Loc(MD->getLocation()), 5473 AllFieldsAreConst(true) { 5474 switch (CSM) { 5475 case Sema::CXXDefaultConstructor: 5476 case Sema::CXXCopyConstructor: 5477 IsConstructor = true; 5478 break; 5479 case Sema::CXXMoveConstructor: 5480 IsConstructor = true; 5481 IsMove = true; 5482 break; 5483 case Sema::CXXCopyAssignment: 5484 IsAssignment = true; 5485 break; 5486 case Sema::CXXMoveAssignment: 5487 IsAssignment = true; 5488 IsMove = true; 5489 break; 5490 case Sema::CXXDestructor: 5491 break; 5492 case Sema::CXXInvalid: 5493 llvm_unreachable("invalid special member kind"); 5494 } 5495 5496 if (MD->getNumParams()) { 5497 if (const ReferenceType *RT = 5498 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5499 ConstArg = RT->getPointeeType().isConstQualified(); 5500 } 5501 } 5502 5503 bool inUnion() const { return MD->getParent()->isUnion(); } 5504 5505 /// Look up the corresponding special member in the given class. 5506 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5507 unsigned Quals, bool IsMutable) { 5508 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5509 ConstArg && !IsMutable); 5510 } 5511 5512 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5513 5514 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5515 bool shouldDeleteForField(FieldDecl *FD); 5516 bool shouldDeleteForAllConstMembers(); 5517 5518 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5519 unsigned Quals); 5520 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5521 Sema::SpecialMemberOverloadResult *SMOR, 5522 bool IsDtorCallInCtor); 5523 5524 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5525 }; 5526 } 5527 5528 /// Is the given special member inaccessible when used on the given 5529 /// sub-object. 5530 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5531 CXXMethodDecl *target) { 5532 /// If we're operating on a base class, the object type is the 5533 /// type of this special member. 5534 QualType objectTy; 5535 AccessSpecifier access = target->getAccess(); 5536 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5537 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5538 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5539 5540 // If we're operating on a field, the object type is the type of the field. 5541 } else { 5542 objectTy = S.Context.getTypeDeclType(target->getParent()); 5543 } 5544 5545 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5546 } 5547 5548 /// Check whether we should delete a special member due to the implicit 5549 /// definition containing a call to a special member of a subobject. 5550 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5551 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5552 bool IsDtorCallInCtor) { 5553 CXXMethodDecl *Decl = SMOR->getMethod(); 5554 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5555 5556 int DiagKind = -1; 5557 5558 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5559 DiagKind = !Decl ? 0 : 1; 5560 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5561 DiagKind = 2; 5562 else if (!isAccessible(Subobj, Decl)) 5563 DiagKind = 3; 5564 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5565 !Decl->isTrivial()) { 5566 // A member of a union must have a trivial corresponding special member. 5567 // As a weird special case, a destructor call from a union's constructor 5568 // must be accessible and non-deleted, but need not be trivial. Such a 5569 // destructor is never actually called, but is semantically checked as 5570 // if it were. 5571 DiagKind = 4; 5572 } 5573 5574 if (DiagKind == -1) 5575 return false; 5576 5577 if (Diagnose) { 5578 if (Field) { 5579 S.Diag(Field->getLocation(), 5580 diag::note_deleted_special_member_class_subobject) 5581 << CSM << MD->getParent() << /*IsField*/true 5582 << Field << DiagKind << IsDtorCallInCtor; 5583 } else { 5584 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5585 S.Diag(Base->getLocStart(), 5586 diag::note_deleted_special_member_class_subobject) 5587 << CSM << MD->getParent() << /*IsField*/false 5588 << Base->getType() << DiagKind << IsDtorCallInCtor; 5589 } 5590 5591 if (DiagKind == 1) 5592 S.NoteDeletedFunction(Decl); 5593 // FIXME: Explain inaccessibility if DiagKind == 3. 5594 } 5595 5596 return true; 5597 } 5598 5599 /// Check whether we should delete a special member function due to having a 5600 /// direct or virtual base class or non-static data member of class type M. 5601 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5602 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5603 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5604 bool IsMutable = Field && Field->isMutable(); 5605 5606 // C++11 [class.ctor]p5: 5607 // -- any direct or virtual base class, or non-static data member with no 5608 // brace-or-equal-initializer, has class type M (or array thereof) and 5609 // either M has no default constructor or overload resolution as applied 5610 // to M's default constructor results in an ambiguity or in a function 5611 // that is deleted or inaccessible 5612 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5613 // -- a direct or virtual base class B that cannot be copied/moved because 5614 // overload resolution, as applied to B's corresponding special member, 5615 // results in an ambiguity or a function that is deleted or inaccessible 5616 // from the defaulted special member 5617 // C++11 [class.dtor]p5: 5618 // -- any direct or virtual base class [...] has a type with a destructor 5619 // that is deleted or inaccessible 5620 if (!(CSM == Sema::CXXDefaultConstructor && 5621 Field && Field->hasInClassInitializer()) && 5622 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5623 false)) 5624 return true; 5625 5626 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5627 // -- any direct or virtual base class or non-static data member has a 5628 // type with a destructor that is deleted or inaccessible 5629 if (IsConstructor) { 5630 Sema::SpecialMemberOverloadResult *SMOR = 5631 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5632 false, false, false, false, false); 5633 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5634 return true; 5635 } 5636 5637 return false; 5638 } 5639 5640 /// Check whether we should delete a special member function due to the class 5641 /// having a particular direct or virtual base class. 5642 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5643 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5644 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5645 } 5646 5647 /// Check whether we should delete a special member function due to the class 5648 /// having a particular non-static data member. 5649 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5650 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5651 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5652 5653 if (CSM == Sema::CXXDefaultConstructor) { 5654 // For a default constructor, all references must be initialized in-class 5655 // and, if a union, it must have a non-const member. 5656 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5657 if (Diagnose) 5658 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5659 << MD->getParent() << FD << FieldType << /*Reference*/0; 5660 return true; 5661 } 5662 // C++11 [class.ctor]p5: any non-variant non-static data member of 5663 // const-qualified type (or array thereof) with no 5664 // brace-or-equal-initializer does not have a user-provided default 5665 // constructor. 5666 if (!inUnion() && FieldType.isConstQualified() && 5667 !FD->hasInClassInitializer() && 5668 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5669 if (Diagnose) 5670 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5671 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5672 return true; 5673 } 5674 5675 if (inUnion() && !FieldType.isConstQualified()) 5676 AllFieldsAreConst = false; 5677 } else if (CSM == Sema::CXXCopyConstructor) { 5678 // For a copy constructor, data members must not be of rvalue reference 5679 // type. 5680 if (FieldType->isRValueReferenceType()) { 5681 if (Diagnose) 5682 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5683 << MD->getParent() << FD << FieldType; 5684 return true; 5685 } 5686 } else if (IsAssignment) { 5687 // For an assignment operator, data members must not be of reference type. 5688 if (FieldType->isReferenceType()) { 5689 if (Diagnose) 5690 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5691 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5692 return true; 5693 } 5694 if (!FieldRecord && FieldType.isConstQualified()) { 5695 // C++11 [class.copy]p23: 5696 // -- a non-static data member of const non-class type (or array thereof) 5697 if (Diagnose) 5698 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5699 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5700 return true; 5701 } 5702 } 5703 5704 if (FieldRecord) { 5705 // Some additional restrictions exist on the variant members. 5706 if (!inUnion() && FieldRecord->isUnion() && 5707 FieldRecord->isAnonymousStructOrUnion()) { 5708 bool AllVariantFieldsAreConst = true; 5709 5710 // FIXME: Handle anonymous unions declared within anonymous unions. 5711 for (auto *UI : FieldRecord->fields()) { 5712 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5713 5714 if (!UnionFieldType.isConstQualified()) 5715 AllVariantFieldsAreConst = false; 5716 5717 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5718 if (UnionFieldRecord && 5719 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5720 UnionFieldType.getCVRQualifiers())) 5721 return true; 5722 } 5723 5724 // At least one member in each anonymous union must be non-const 5725 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5726 !FieldRecord->field_empty()) { 5727 if (Diagnose) 5728 S.Diag(FieldRecord->getLocation(), 5729 diag::note_deleted_default_ctor_all_const) 5730 << MD->getParent() << /*anonymous union*/1; 5731 return true; 5732 } 5733 5734 // Don't check the implicit member of the anonymous union type. 5735 // This is technically non-conformant, but sanity demands it. 5736 return false; 5737 } 5738 5739 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5740 FieldType.getCVRQualifiers())) 5741 return true; 5742 } 5743 5744 return false; 5745 } 5746 5747 /// C++11 [class.ctor] p5: 5748 /// A defaulted default constructor for a class X is defined as deleted if 5749 /// X is a union and all of its variant members are of const-qualified type. 5750 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5751 // This is a silly definition, because it gives an empty union a deleted 5752 // default constructor. Don't do that. 5753 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5754 !MD->getParent()->field_empty()) { 5755 if (Diagnose) 5756 S.Diag(MD->getParent()->getLocation(), 5757 diag::note_deleted_default_ctor_all_const) 5758 << MD->getParent() << /*not anonymous union*/0; 5759 return true; 5760 } 5761 return false; 5762 } 5763 5764 /// Determine whether a defaulted special member function should be defined as 5765 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5766 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5767 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5768 bool Diagnose) { 5769 if (MD->isInvalidDecl()) 5770 return false; 5771 CXXRecordDecl *RD = MD->getParent(); 5772 assert(!RD->isDependentType() && "do deletion after instantiation"); 5773 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5774 return false; 5775 5776 // C++11 [expr.lambda.prim]p19: 5777 // The closure type associated with a lambda-expression has a 5778 // deleted (8.4.3) default constructor and a deleted copy 5779 // assignment operator. 5780 if (RD->isLambda() && 5781 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5782 if (Diagnose) 5783 Diag(RD->getLocation(), diag::note_lambda_decl); 5784 return true; 5785 } 5786 5787 // For an anonymous struct or union, the copy and assignment special members 5788 // will never be used, so skip the check. For an anonymous union declared at 5789 // namespace scope, the constructor and destructor are used. 5790 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5791 RD->isAnonymousStructOrUnion()) 5792 return false; 5793 5794 // C++11 [class.copy]p7, p18: 5795 // If the class definition declares a move constructor or move assignment 5796 // operator, an implicitly declared copy constructor or copy assignment 5797 // operator is defined as deleted. 5798 if (MD->isImplicit() && 5799 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5800 CXXMethodDecl *UserDeclaredMove = nullptr; 5801 5802 // In Microsoft mode, a user-declared move only causes the deletion of the 5803 // corresponding copy operation, not both copy operations. 5804 if (RD->hasUserDeclaredMoveConstructor() && 5805 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5806 if (!Diagnose) return true; 5807 5808 // Find any user-declared move constructor. 5809 for (auto *I : RD->ctors()) { 5810 if (I->isMoveConstructor()) { 5811 UserDeclaredMove = I; 5812 break; 5813 } 5814 } 5815 assert(UserDeclaredMove); 5816 } else if (RD->hasUserDeclaredMoveAssignment() && 5817 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5818 if (!Diagnose) return true; 5819 5820 // Find any user-declared move assignment operator. 5821 for (auto *I : RD->methods()) { 5822 if (I->isMoveAssignmentOperator()) { 5823 UserDeclaredMove = I; 5824 break; 5825 } 5826 } 5827 assert(UserDeclaredMove); 5828 } 5829 5830 if (UserDeclaredMove) { 5831 Diag(UserDeclaredMove->getLocation(), 5832 diag::note_deleted_copy_user_declared_move) 5833 << (CSM == CXXCopyAssignment) << RD 5834 << UserDeclaredMove->isMoveAssignmentOperator(); 5835 return true; 5836 } 5837 } 5838 5839 // Do access control from the special member function 5840 ContextRAII MethodContext(*this, MD); 5841 5842 // C++11 [class.dtor]p5: 5843 // -- for a virtual destructor, lookup of the non-array deallocation function 5844 // results in an ambiguity or in a function that is deleted or inaccessible 5845 if (CSM == CXXDestructor && MD->isVirtual()) { 5846 FunctionDecl *OperatorDelete = nullptr; 5847 DeclarationName Name = 5848 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5849 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5850 OperatorDelete, false)) { 5851 if (Diagnose) 5852 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5853 return true; 5854 } 5855 } 5856 5857 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5858 5859 for (auto &BI : RD->bases()) 5860 if (!BI.isVirtual() && 5861 SMI.shouldDeleteForBase(&BI)) 5862 return true; 5863 5864 // Per DR1611, do not consider virtual bases of constructors of abstract 5865 // classes, since we are not going to construct them. 5866 if (!RD->isAbstract() || !SMI.IsConstructor) { 5867 for (auto &BI : RD->vbases()) 5868 if (SMI.shouldDeleteForBase(&BI)) 5869 return true; 5870 } 5871 5872 for (auto *FI : RD->fields()) 5873 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5874 SMI.shouldDeleteForField(FI)) 5875 return true; 5876 5877 if (SMI.shouldDeleteForAllConstMembers()) 5878 return true; 5879 5880 if (getLangOpts().CUDA) { 5881 // We should delete the special member in CUDA mode if target inference 5882 // failed. 5883 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5884 Diagnose); 5885 } 5886 5887 return false; 5888 } 5889 5890 /// Perform lookup for a special member of the specified kind, and determine 5891 /// whether it is trivial. If the triviality can be determined without the 5892 /// lookup, skip it. This is intended for use when determining whether a 5893 /// special member of a containing object is trivial, and thus does not ever 5894 /// perform overload resolution for default constructors. 5895 /// 5896 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5897 /// member that was most likely to be intended to be trivial, if any. 5898 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5899 Sema::CXXSpecialMember CSM, unsigned Quals, 5900 bool ConstRHS, CXXMethodDecl **Selected) { 5901 if (Selected) 5902 *Selected = nullptr; 5903 5904 switch (CSM) { 5905 case Sema::CXXInvalid: 5906 llvm_unreachable("not a special member"); 5907 5908 case Sema::CXXDefaultConstructor: 5909 // C++11 [class.ctor]p5: 5910 // A default constructor is trivial if: 5911 // - all the [direct subobjects] have trivial default constructors 5912 // 5913 // Note, no overload resolution is performed in this case. 5914 if (RD->hasTrivialDefaultConstructor()) 5915 return true; 5916 5917 if (Selected) { 5918 // If there's a default constructor which could have been trivial, dig it 5919 // out. Otherwise, if there's any user-provided default constructor, point 5920 // to that as an example of why there's not a trivial one. 5921 CXXConstructorDecl *DefCtor = nullptr; 5922 if (RD->needsImplicitDefaultConstructor()) 5923 S.DeclareImplicitDefaultConstructor(RD); 5924 for (auto *CI : RD->ctors()) { 5925 if (!CI->isDefaultConstructor()) 5926 continue; 5927 DefCtor = CI; 5928 if (!DefCtor->isUserProvided()) 5929 break; 5930 } 5931 5932 *Selected = DefCtor; 5933 } 5934 5935 return false; 5936 5937 case Sema::CXXDestructor: 5938 // C++11 [class.dtor]p5: 5939 // A destructor is trivial if: 5940 // - all the direct [subobjects] have trivial destructors 5941 if (RD->hasTrivialDestructor()) 5942 return true; 5943 5944 if (Selected) { 5945 if (RD->needsImplicitDestructor()) 5946 S.DeclareImplicitDestructor(RD); 5947 *Selected = RD->getDestructor(); 5948 } 5949 5950 return false; 5951 5952 case Sema::CXXCopyConstructor: 5953 // C++11 [class.copy]p12: 5954 // A copy constructor is trivial if: 5955 // - the constructor selected to copy each direct [subobject] is trivial 5956 if (RD->hasTrivialCopyConstructor()) { 5957 if (Quals == Qualifiers::Const) 5958 // We must either select the trivial copy constructor or reach an 5959 // ambiguity; no need to actually perform overload resolution. 5960 return true; 5961 } else if (!Selected) { 5962 return false; 5963 } 5964 // In C++98, we are not supposed to perform overload resolution here, but we 5965 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5966 // cases like B as having a non-trivial copy constructor: 5967 // struct A { template<typename T> A(T&); }; 5968 // struct B { mutable A a; }; 5969 goto NeedOverloadResolution; 5970 5971 case Sema::CXXCopyAssignment: 5972 // C++11 [class.copy]p25: 5973 // A copy assignment operator is trivial if: 5974 // - the assignment operator selected to copy each direct [subobject] is 5975 // trivial 5976 if (RD->hasTrivialCopyAssignment()) { 5977 if (Quals == Qualifiers::Const) 5978 return true; 5979 } else if (!Selected) { 5980 return false; 5981 } 5982 // In C++98, we are not supposed to perform overload resolution here, but we 5983 // treat that as a language defect. 5984 goto NeedOverloadResolution; 5985 5986 case Sema::CXXMoveConstructor: 5987 case Sema::CXXMoveAssignment: 5988 NeedOverloadResolution: 5989 Sema::SpecialMemberOverloadResult *SMOR = 5990 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5991 5992 // The standard doesn't describe how to behave if the lookup is ambiguous. 5993 // We treat it as not making the member non-trivial, just like the standard 5994 // mandates for the default constructor. This should rarely matter, because 5995 // the member will also be deleted. 5996 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5997 return true; 5998 5999 if (!SMOR->getMethod()) { 6000 assert(SMOR->getKind() == 6001 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 6002 return false; 6003 } 6004 6005 // We deliberately don't check if we found a deleted special member. We're 6006 // not supposed to! 6007 if (Selected) 6008 *Selected = SMOR->getMethod(); 6009 return SMOR->getMethod()->isTrivial(); 6010 } 6011 6012 llvm_unreachable("unknown special method kind"); 6013 } 6014 6015 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 6016 for (auto *CI : RD->ctors()) 6017 if (!CI->isImplicit()) 6018 return CI; 6019 6020 // Look for constructor templates. 6021 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 6022 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 6023 if (CXXConstructorDecl *CD = 6024 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 6025 return CD; 6026 } 6027 6028 return nullptr; 6029 } 6030 6031 /// The kind of subobject we are checking for triviality. The values of this 6032 /// enumeration are used in diagnostics. 6033 enum TrivialSubobjectKind { 6034 /// The subobject is a base class. 6035 TSK_BaseClass, 6036 /// The subobject is a non-static data member. 6037 TSK_Field, 6038 /// The object is actually the complete object. 6039 TSK_CompleteObject 6040 }; 6041 6042 /// Check whether the special member selected for a given type would be trivial. 6043 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 6044 QualType SubType, bool ConstRHS, 6045 Sema::CXXSpecialMember CSM, 6046 TrivialSubobjectKind Kind, 6047 bool Diagnose) { 6048 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 6049 if (!SubRD) 6050 return true; 6051 6052 CXXMethodDecl *Selected; 6053 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 6054 ConstRHS, Diagnose ? &Selected : nullptr)) 6055 return true; 6056 6057 if (Diagnose) { 6058 if (ConstRHS) 6059 SubType.addConst(); 6060 6061 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6062 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6063 << Kind << SubType.getUnqualifiedType(); 6064 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6065 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6066 } else if (!Selected) 6067 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6068 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6069 else if (Selected->isUserProvided()) { 6070 if (Kind == TSK_CompleteObject) 6071 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6072 << Kind << SubType.getUnqualifiedType() << CSM; 6073 else { 6074 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6075 << Kind << SubType.getUnqualifiedType() << CSM; 6076 S.Diag(Selected->getLocation(), diag::note_declared_at); 6077 } 6078 } else { 6079 if (Kind != TSK_CompleteObject) 6080 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6081 << Kind << SubType.getUnqualifiedType() << CSM; 6082 6083 // Explain why the defaulted or deleted special member isn't trivial. 6084 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6085 } 6086 } 6087 6088 return false; 6089 } 6090 6091 /// Check whether the members of a class type allow a special member to be 6092 /// trivial. 6093 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 6094 Sema::CXXSpecialMember CSM, 6095 bool ConstArg, bool Diagnose) { 6096 for (const auto *FI : RD->fields()) { 6097 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 6098 continue; 6099 6100 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 6101 6102 // Pretend anonymous struct or union members are members of this class. 6103 if (FI->isAnonymousStructOrUnion()) { 6104 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 6105 CSM, ConstArg, Diagnose)) 6106 return false; 6107 continue; 6108 } 6109 6110 // C++11 [class.ctor]p5: 6111 // A default constructor is trivial if [...] 6112 // -- no non-static data member of its class has a 6113 // brace-or-equal-initializer 6114 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 6115 if (Diagnose) 6116 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 6117 return false; 6118 } 6119 6120 // Objective C ARC 4.3.5: 6121 // [...] nontrivally ownership-qualified types are [...] not trivially 6122 // default constructible, copy constructible, move constructible, copy 6123 // assignable, move assignable, or destructible [...] 6124 if (S.getLangOpts().ObjCAutoRefCount && 6125 FieldType.hasNonTrivialObjCLifetime()) { 6126 if (Diagnose) 6127 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6128 << RD << FieldType.getObjCLifetime(); 6129 return false; 6130 } 6131 6132 bool ConstRHS = ConstArg && !FI->isMutable(); 6133 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6134 CSM, TSK_Field, Diagnose)) 6135 return false; 6136 } 6137 6138 return true; 6139 } 6140 6141 /// Diagnose why the specified class does not have a trivial special member of 6142 /// the given kind. 6143 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6144 QualType Ty = Context.getRecordType(RD); 6145 6146 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6147 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6148 TSK_CompleteObject, /*Diagnose*/true); 6149 } 6150 6151 /// Determine whether a defaulted or deleted special member function is trivial, 6152 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6153 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6154 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6155 bool Diagnose) { 6156 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6157 6158 CXXRecordDecl *RD = MD->getParent(); 6159 6160 bool ConstArg = false; 6161 6162 // C++11 [class.copy]p12, p25: [DR1593] 6163 // A [special member] is trivial if [...] its parameter-type-list is 6164 // equivalent to the parameter-type-list of an implicit declaration [...] 6165 switch (CSM) { 6166 case CXXDefaultConstructor: 6167 case CXXDestructor: 6168 // Trivial default constructors and destructors cannot have parameters. 6169 break; 6170 6171 case CXXCopyConstructor: 6172 case CXXCopyAssignment: { 6173 // Trivial copy operations always have const, non-volatile parameter types. 6174 ConstArg = true; 6175 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6176 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6177 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6178 if (Diagnose) 6179 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6180 << Param0->getSourceRange() << Param0->getType() 6181 << Context.getLValueReferenceType( 6182 Context.getRecordType(RD).withConst()); 6183 return false; 6184 } 6185 break; 6186 } 6187 6188 case CXXMoveConstructor: 6189 case CXXMoveAssignment: { 6190 // Trivial move operations always have non-cv-qualified parameters. 6191 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6192 const RValueReferenceType *RT = 6193 Param0->getType()->getAs<RValueReferenceType>(); 6194 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6195 if (Diagnose) 6196 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6197 << Param0->getSourceRange() << Param0->getType() 6198 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6199 return false; 6200 } 6201 break; 6202 } 6203 6204 case CXXInvalid: 6205 llvm_unreachable("not a special member"); 6206 } 6207 6208 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6209 if (Diagnose) 6210 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6211 diag::note_nontrivial_default_arg) 6212 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6213 return false; 6214 } 6215 if (MD->isVariadic()) { 6216 if (Diagnose) 6217 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6218 return false; 6219 } 6220 6221 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6222 // A copy/move [constructor or assignment operator] is trivial if 6223 // -- the [member] selected to copy/move each direct base class subobject 6224 // is trivial 6225 // 6226 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6227 // A [default constructor or destructor] is trivial if 6228 // -- all the direct base classes have trivial [default constructors or 6229 // destructors] 6230 for (const auto &BI : RD->bases()) 6231 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6232 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6233 return false; 6234 6235 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6236 // A copy/move [constructor or assignment operator] for a class X is 6237 // trivial if 6238 // -- for each non-static data member of X that is of class type (or array 6239 // thereof), the constructor selected to copy/move that member is 6240 // trivial 6241 // 6242 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6243 // A [default constructor or destructor] is trivial if 6244 // -- for all of the non-static data members of its class that are of class 6245 // type (or array thereof), each such class has a trivial [default 6246 // constructor or destructor] 6247 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6248 return false; 6249 6250 // C++11 [class.dtor]p5: 6251 // A destructor is trivial if [...] 6252 // -- the destructor is not virtual 6253 if (CSM == CXXDestructor && MD->isVirtual()) { 6254 if (Diagnose) 6255 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6256 return false; 6257 } 6258 6259 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6260 // A [special member] for class X is trivial if [...] 6261 // -- class X has no virtual functions and no virtual base classes 6262 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6263 if (!Diagnose) 6264 return false; 6265 6266 if (RD->getNumVBases()) { 6267 // Check for virtual bases. We already know that the corresponding 6268 // member in all bases is trivial, so vbases must all be direct. 6269 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6270 assert(BS.isVirtual()); 6271 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6272 return false; 6273 } 6274 6275 // Must have a virtual method. 6276 for (const auto *MI : RD->methods()) { 6277 if (MI->isVirtual()) { 6278 SourceLocation MLoc = MI->getLocStart(); 6279 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6280 return false; 6281 } 6282 } 6283 6284 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6285 } 6286 6287 // Looks like it's trivial! 6288 return true; 6289 } 6290 6291 namespace { 6292 struct FindHiddenVirtualMethod { 6293 Sema *S; 6294 CXXMethodDecl *Method; 6295 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6296 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6297 6298 private: 6299 /// Check whether any most overriden method from MD in Methods 6300 static bool CheckMostOverridenMethods( 6301 const CXXMethodDecl *MD, 6302 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 6303 if (MD->size_overridden_methods() == 0) 6304 return Methods.count(MD->getCanonicalDecl()); 6305 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6306 E = MD->end_overridden_methods(); 6307 I != E; ++I) 6308 if (CheckMostOverridenMethods(*I, Methods)) 6309 return true; 6310 return false; 6311 } 6312 6313 public: 6314 /// Member lookup function that determines whether a given C++ 6315 /// method overloads virtual methods in a base class without overriding any, 6316 /// to be used with CXXRecordDecl::lookupInBases(). 6317 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 6318 RecordDecl *BaseRecord = 6319 Specifier->getType()->getAs<RecordType>()->getDecl(); 6320 6321 DeclarationName Name = Method->getDeclName(); 6322 assert(Name.getNameKind() == DeclarationName::Identifier); 6323 6324 bool foundSameNameMethod = false; 6325 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6326 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 6327 Path.Decls = Path.Decls.slice(1)) { 6328 NamedDecl *D = Path.Decls.front(); 6329 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6330 MD = MD->getCanonicalDecl(); 6331 foundSameNameMethod = true; 6332 // Interested only in hidden virtual methods. 6333 if (!MD->isVirtual()) 6334 continue; 6335 // If the method we are checking overrides a method from its base 6336 // don't warn about the other overloaded methods. Clang deviates from 6337 // GCC by only diagnosing overloads of inherited virtual functions that 6338 // do not override any other virtual functions in the base. GCC's 6339 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6340 // function from a base class. These cases may be better served by a 6341 // warning (not specific to virtual functions) on call sites when the 6342 // call would select a different function from the base class, were it 6343 // visible. 6344 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6345 if (!S->IsOverload(Method, MD, false)) 6346 return true; 6347 // Collect the overload only if its hidden. 6348 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 6349 overloadedMethods.push_back(MD); 6350 } 6351 } 6352 6353 if (foundSameNameMethod) 6354 OverloadedMethods.append(overloadedMethods.begin(), 6355 overloadedMethods.end()); 6356 return foundSameNameMethod; 6357 } 6358 }; 6359 } // end anonymous namespace 6360 6361 /// \brief Add the most overriden methods from MD to Methods 6362 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6363 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6364 if (MD->size_overridden_methods() == 0) 6365 Methods.insert(MD->getCanonicalDecl()); 6366 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6367 E = MD->end_overridden_methods(); 6368 I != E; ++I) 6369 AddMostOverridenMethods(*I, Methods); 6370 } 6371 6372 /// \brief Check if a method overloads virtual methods in a base class without 6373 /// overriding any. 6374 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6375 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6376 if (!MD->getDeclName().isIdentifier()) 6377 return; 6378 6379 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6380 /*bool RecordPaths=*/false, 6381 /*bool DetectVirtual=*/false); 6382 FindHiddenVirtualMethod FHVM; 6383 FHVM.Method = MD; 6384 FHVM.S = this; 6385 6386 // Keep the base methods that were overriden or introduced in the subclass 6387 // by 'using' in a set. A base method not in this set is hidden. 6388 CXXRecordDecl *DC = MD->getParent(); 6389 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6390 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6391 NamedDecl *ND = *I; 6392 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6393 ND = shad->getTargetDecl(); 6394 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6395 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 6396 } 6397 6398 if (DC->lookupInBases(FHVM, Paths)) 6399 OverloadedMethods = FHVM.OverloadedMethods; 6400 } 6401 6402 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6403 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6404 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6405 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6406 PartialDiagnostic PD = PDiag( 6407 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6408 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6409 Diag(overloadedMD->getLocation(), PD); 6410 } 6411 } 6412 6413 /// \brief Diagnose methods which overload virtual methods in a base class 6414 /// without overriding any. 6415 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6416 if (MD->isInvalidDecl()) 6417 return; 6418 6419 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6420 return; 6421 6422 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6423 FindHiddenVirtualMethods(MD, OverloadedMethods); 6424 if (!OverloadedMethods.empty()) { 6425 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6426 << MD << (OverloadedMethods.size() > 1); 6427 6428 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6429 } 6430 } 6431 6432 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6433 Decl *TagDecl, 6434 SourceLocation LBrac, 6435 SourceLocation RBrac, 6436 AttributeList *AttrList) { 6437 if (!TagDecl) 6438 return; 6439 6440 AdjustDeclIfTemplate(TagDecl); 6441 6442 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6443 if (l->getKind() != AttributeList::AT_Visibility) 6444 continue; 6445 l->setInvalid(); 6446 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6447 l->getName(); 6448 } 6449 6450 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6451 // strict aliasing violation! 6452 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6453 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6454 6455 CheckCompletedCXXClass( 6456 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6457 } 6458 6459 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6460 /// special functions, such as the default constructor, copy 6461 /// constructor, or destructor, to the given C++ class (C++ 6462 /// [special]p1). This routine can only be executed just before the 6463 /// definition of the class is complete. 6464 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6465 if (!ClassDecl->hasUserDeclaredConstructor()) 6466 ++ASTContext::NumImplicitDefaultConstructors; 6467 6468 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6469 ++ASTContext::NumImplicitCopyConstructors; 6470 6471 // If the properties or semantics of the copy constructor couldn't be 6472 // determined while the class was being declared, force a declaration 6473 // of it now. 6474 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6475 DeclareImplicitCopyConstructor(ClassDecl); 6476 } 6477 6478 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6479 ++ASTContext::NumImplicitMoveConstructors; 6480 6481 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6482 DeclareImplicitMoveConstructor(ClassDecl); 6483 } 6484 6485 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6486 ++ASTContext::NumImplicitCopyAssignmentOperators; 6487 6488 // If we have a dynamic class, then the copy assignment operator may be 6489 // virtual, so we have to declare it immediately. This ensures that, e.g., 6490 // it shows up in the right place in the vtable and that we diagnose 6491 // problems with the implicit exception specification. 6492 if (ClassDecl->isDynamicClass() || 6493 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6494 DeclareImplicitCopyAssignment(ClassDecl); 6495 } 6496 6497 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6498 ++ASTContext::NumImplicitMoveAssignmentOperators; 6499 6500 // Likewise for the move assignment operator. 6501 if (ClassDecl->isDynamicClass() || 6502 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6503 DeclareImplicitMoveAssignment(ClassDecl); 6504 } 6505 6506 if (!ClassDecl->hasUserDeclaredDestructor()) { 6507 ++ASTContext::NumImplicitDestructors; 6508 6509 // If we have a dynamic class, then the destructor may be virtual, so we 6510 // have to declare the destructor immediately. This ensures that, e.g., it 6511 // shows up in the right place in the vtable and that we diagnose problems 6512 // with the implicit exception specification. 6513 if (ClassDecl->isDynamicClass() || 6514 ClassDecl->needsOverloadResolutionForDestructor()) 6515 DeclareImplicitDestructor(ClassDecl); 6516 } 6517 } 6518 6519 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6520 if (!D) 6521 return 0; 6522 6523 // The order of template parameters is not important here. All names 6524 // get added to the same scope. 6525 SmallVector<TemplateParameterList *, 4> ParameterLists; 6526 6527 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6528 D = TD->getTemplatedDecl(); 6529 6530 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6531 ParameterLists.push_back(PSD->getTemplateParameters()); 6532 6533 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6534 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6535 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6536 6537 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6538 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6539 ParameterLists.push_back(FTD->getTemplateParameters()); 6540 } 6541 } 6542 6543 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6544 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6545 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6546 6547 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6548 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6549 ParameterLists.push_back(CTD->getTemplateParameters()); 6550 } 6551 } 6552 6553 unsigned Count = 0; 6554 for (TemplateParameterList *Params : ParameterLists) { 6555 if (Params->size() > 0) 6556 // Ignore explicit specializations; they don't contribute to the template 6557 // depth. 6558 ++Count; 6559 for (NamedDecl *Param : *Params) { 6560 if (Param->getDeclName()) { 6561 S->AddDecl(Param); 6562 IdResolver.AddDecl(Param); 6563 } 6564 } 6565 } 6566 6567 return Count; 6568 } 6569 6570 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6571 if (!RecordD) return; 6572 AdjustDeclIfTemplate(RecordD); 6573 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6574 PushDeclContext(S, Record); 6575 } 6576 6577 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6578 if (!RecordD) return; 6579 PopDeclContext(); 6580 } 6581 6582 /// This is used to implement the constant expression evaluation part of the 6583 /// attribute enable_if extension. There is nothing in standard C++ which would 6584 /// require reentering parameters. 6585 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6586 if (!Param) 6587 return; 6588 6589 S->AddDecl(Param); 6590 if (Param->getDeclName()) 6591 IdResolver.AddDecl(Param); 6592 } 6593 6594 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6595 /// parsing a top-level (non-nested) C++ class, and we are now 6596 /// parsing those parts of the given Method declaration that could 6597 /// not be parsed earlier (C++ [class.mem]p2), such as default 6598 /// arguments. This action should enter the scope of the given 6599 /// Method declaration as if we had just parsed the qualified method 6600 /// name. However, it should not bring the parameters into scope; 6601 /// that will be performed by ActOnDelayedCXXMethodParameter. 6602 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6603 } 6604 6605 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6606 /// C++ method declaration. We're (re-)introducing the given 6607 /// function parameter into scope for use in parsing later parts of 6608 /// the method declaration. For example, we could see an 6609 /// ActOnParamDefaultArgument event for this parameter. 6610 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6611 if (!ParamD) 6612 return; 6613 6614 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6615 6616 // If this parameter has an unparsed default argument, clear it out 6617 // to make way for the parsed default argument. 6618 if (Param->hasUnparsedDefaultArg()) 6619 Param->setDefaultArg(nullptr); 6620 6621 S->AddDecl(Param); 6622 if (Param->getDeclName()) 6623 IdResolver.AddDecl(Param); 6624 } 6625 6626 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6627 /// processing the delayed method declaration for Method. The method 6628 /// declaration is now considered finished. There may be a separate 6629 /// ActOnStartOfFunctionDef action later (not necessarily 6630 /// immediately!) for this method, if it was also defined inside the 6631 /// class body. 6632 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6633 if (!MethodD) 6634 return; 6635 6636 AdjustDeclIfTemplate(MethodD); 6637 6638 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6639 6640 // Now that we have our default arguments, check the constructor 6641 // again. It could produce additional diagnostics or affect whether 6642 // the class has implicitly-declared destructors, among other 6643 // things. 6644 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6645 CheckConstructor(Constructor); 6646 6647 // Check the default arguments, which we may have added. 6648 if (!Method->isInvalidDecl()) 6649 CheckCXXDefaultArguments(Method); 6650 } 6651 6652 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6653 /// the well-formedness of the constructor declarator @p D with type @p 6654 /// R. If there are any errors in the declarator, this routine will 6655 /// emit diagnostics and set the invalid bit to true. In any case, the type 6656 /// will be updated to reflect a well-formed type for the constructor and 6657 /// returned. 6658 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6659 StorageClass &SC) { 6660 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6661 6662 // C++ [class.ctor]p3: 6663 // A constructor shall not be virtual (10.3) or static (9.4). A 6664 // constructor can be invoked for a const, volatile or const 6665 // volatile object. A constructor shall not be declared const, 6666 // volatile, or const volatile (9.3.2). 6667 if (isVirtual) { 6668 if (!D.isInvalidType()) 6669 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6670 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6671 << SourceRange(D.getIdentifierLoc()); 6672 D.setInvalidType(); 6673 } 6674 if (SC == SC_Static) { 6675 if (!D.isInvalidType()) 6676 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6677 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6678 << SourceRange(D.getIdentifierLoc()); 6679 D.setInvalidType(); 6680 SC = SC_None; 6681 } 6682 6683 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6684 diagnoseIgnoredQualifiers( 6685 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6686 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6687 D.getDeclSpec().getRestrictSpecLoc(), 6688 D.getDeclSpec().getAtomicSpecLoc()); 6689 D.setInvalidType(); 6690 } 6691 6692 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6693 if (FTI.TypeQuals != 0) { 6694 if (FTI.TypeQuals & Qualifiers::Const) 6695 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6696 << "const" << SourceRange(D.getIdentifierLoc()); 6697 if (FTI.TypeQuals & Qualifiers::Volatile) 6698 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6699 << "volatile" << SourceRange(D.getIdentifierLoc()); 6700 if (FTI.TypeQuals & Qualifiers::Restrict) 6701 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6702 << "restrict" << SourceRange(D.getIdentifierLoc()); 6703 D.setInvalidType(); 6704 } 6705 6706 // C++0x [class.ctor]p4: 6707 // A constructor shall not be declared with a ref-qualifier. 6708 if (FTI.hasRefQualifier()) { 6709 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6710 << FTI.RefQualifierIsLValueRef 6711 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6712 D.setInvalidType(); 6713 } 6714 6715 // Rebuild the function type "R" without any type qualifiers (in 6716 // case any of the errors above fired) and with "void" as the 6717 // return type, since constructors don't have return types. 6718 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6719 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6720 return R; 6721 6722 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6723 EPI.TypeQuals = 0; 6724 EPI.RefQualifier = RQ_None; 6725 6726 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6727 } 6728 6729 /// CheckConstructor - Checks a fully-formed constructor for 6730 /// well-formedness, issuing any diagnostics required. Returns true if 6731 /// the constructor declarator is invalid. 6732 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6733 CXXRecordDecl *ClassDecl 6734 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6735 if (!ClassDecl) 6736 return Constructor->setInvalidDecl(); 6737 6738 // C++ [class.copy]p3: 6739 // A declaration of a constructor for a class X is ill-formed if 6740 // its first parameter is of type (optionally cv-qualified) X and 6741 // either there are no other parameters or else all other 6742 // parameters have default arguments. 6743 if (!Constructor->isInvalidDecl() && 6744 ((Constructor->getNumParams() == 1) || 6745 (Constructor->getNumParams() > 1 && 6746 Constructor->getParamDecl(1)->hasDefaultArg())) && 6747 Constructor->getTemplateSpecializationKind() 6748 != TSK_ImplicitInstantiation) { 6749 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6750 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6751 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6752 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6753 const char *ConstRef 6754 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6755 : " const &"; 6756 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6757 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6758 6759 // FIXME: Rather that making the constructor invalid, we should endeavor 6760 // to fix the type. 6761 Constructor->setInvalidDecl(); 6762 } 6763 } 6764 } 6765 6766 /// CheckDestructor - Checks a fully-formed destructor definition for 6767 /// well-formedness, issuing any diagnostics required. Returns true 6768 /// on error. 6769 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6770 CXXRecordDecl *RD = Destructor->getParent(); 6771 6772 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6773 SourceLocation Loc; 6774 6775 if (!Destructor->isImplicit()) 6776 Loc = Destructor->getLocation(); 6777 else 6778 Loc = RD->getLocation(); 6779 6780 // If we have a virtual destructor, look up the deallocation function 6781 FunctionDecl *OperatorDelete = nullptr; 6782 DeclarationName Name = 6783 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6784 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6785 return true; 6786 // If there's no class-specific operator delete, look up the global 6787 // non-array delete. 6788 if (!OperatorDelete) 6789 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6790 6791 MarkFunctionReferenced(Loc, OperatorDelete); 6792 6793 Destructor->setOperatorDelete(OperatorDelete); 6794 } 6795 6796 return false; 6797 } 6798 6799 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6800 /// the well-formednes of the destructor declarator @p D with type @p 6801 /// R. If there are any errors in the declarator, this routine will 6802 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6803 /// will be updated to reflect a well-formed type for the destructor and 6804 /// returned. 6805 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6806 StorageClass& SC) { 6807 // C++ [class.dtor]p1: 6808 // [...] A typedef-name that names a class is a class-name 6809 // (7.1.3); however, a typedef-name that names a class shall not 6810 // be used as the identifier in the declarator for a destructor 6811 // declaration. 6812 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6813 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6814 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6815 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6816 else if (const TemplateSpecializationType *TST = 6817 DeclaratorType->getAs<TemplateSpecializationType>()) 6818 if (TST->isTypeAlias()) 6819 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6820 << DeclaratorType << 1; 6821 6822 // C++ [class.dtor]p2: 6823 // A destructor is used to destroy objects of its class type. A 6824 // destructor takes no parameters, and no return type can be 6825 // specified for it (not even void). The address of a destructor 6826 // shall not be taken. A destructor shall not be static. A 6827 // destructor can be invoked for a const, volatile or const 6828 // volatile object. A destructor shall not be declared const, 6829 // volatile or const volatile (9.3.2). 6830 if (SC == SC_Static) { 6831 if (!D.isInvalidType()) 6832 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6833 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6834 << SourceRange(D.getIdentifierLoc()) 6835 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6836 6837 SC = SC_None; 6838 } 6839 if (!D.isInvalidType()) { 6840 // Destructors don't have return types, but the parser will 6841 // happily parse something like: 6842 // 6843 // class X { 6844 // float ~X(); 6845 // }; 6846 // 6847 // The return type will be eliminated later. 6848 if (D.getDeclSpec().hasTypeSpecifier()) 6849 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6850 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6851 << SourceRange(D.getIdentifierLoc()); 6852 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6853 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6854 SourceLocation(), 6855 D.getDeclSpec().getConstSpecLoc(), 6856 D.getDeclSpec().getVolatileSpecLoc(), 6857 D.getDeclSpec().getRestrictSpecLoc(), 6858 D.getDeclSpec().getAtomicSpecLoc()); 6859 D.setInvalidType(); 6860 } 6861 } 6862 6863 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6864 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6865 if (FTI.TypeQuals & Qualifiers::Const) 6866 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6867 << "const" << SourceRange(D.getIdentifierLoc()); 6868 if (FTI.TypeQuals & Qualifiers::Volatile) 6869 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6870 << "volatile" << SourceRange(D.getIdentifierLoc()); 6871 if (FTI.TypeQuals & Qualifiers::Restrict) 6872 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6873 << "restrict" << SourceRange(D.getIdentifierLoc()); 6874 D.setInvalidType(); 6875 } 6876 6877 // C++0x [class.dtor]p2: 6878 // A destructor shall not be declared with a ref-qualifier. 6879 if (FTI.hasRefQualifier()) { 6880 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6881 << FTI.RefQualifierIsLValueRef 6882 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6883 D.setInvalidType(); 6884 } 6885 6886 // Make sure we don't have any parameters. 6887 if (FTIHasNonVoidParameters(FTI)) { 6888 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6889 6890 // Delete the parameters. 6891 FTI.freeParams(); 6892 D.setInvalidType(); 6893 } 6894 6895 // Make sure the destructor isn't variadic. 6896 if (FTI.isVariadic) { 6897 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6898 D.setInvalidType(); 6899 } 6900 6901 // Rebuild the function type "R" without any type qualifiers or 6902 // parameters (in case any of the errors above fired) and with 6903 // "void" as the return type, since destructors don't have return 6904 // types. 6905 if (!D.isInvalidType()) 6906 return R; 6907 6908 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6909 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6910 EPI.Variadic = false; 6911 EPI.TypeQuals = 0; 6912 EPI.RefQualifier = RQ_None; 6913 return Context.getFunctionType(Context.VoidTy, None, EPI); 6914 } 6915 6916 static void extendLeft(SourceRange &R, const SourceRange &Before) { 6917 if (Before.isInvalid()) 6918 return; 6919 R.setBegin(Before.getBegin()); 6920 if (R.getEnd().isInvalid()) 6921 R.setEnd(Before.getEnd()); 6922 } 6923 6924 static void extendRight(SourceRange &R, const SourceRange &After) { 6925 if (After.isInvalid()) 6926 return; 6927 if (R.getBegin().isInvalid()) 6928 R.setBegin(After.getBegin()); 6929 R.setEnd(After.getEnd()); 6930 } 6931 6932 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6933 /// well-formednes of the conversion function declarator @p D with 6934 /// type @p R. If there are any errors in the declarator, this routine 6935 /// will emit diagnostics and return true. Otherwise, it will return 6936 /// false. Either way, the type @p R will be updated to reflect a 6937 /// well-formed type for the conversion operator. 6938 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6939 StorageClass& SC) { 6940 // C++ [class.conv.fct]p1: 6941 // Neither parameter types nor return type can be specified. The 6942 // type of a conversion function (8.3.5) is "function taking no 6943 // parameter returning conversion-type-id." 6944 if (SC == SC_Static) { 6945 if (!D.isInvalidType()) 6946 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6947 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6948 << D.getName().getSourceRange(); 6949 D.setInvalidType(); 6950 SC = SC_None; 6951 } 6952 6953 TypeSourceInfo *ConvTSI = nullptr; 6954 QualType ConvType = 6955 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 6956 6957 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6958 // Conversion functions don't have return types, but the parser will 6959 // happily parse something like: 6960 // 6961 // class X { 6962 // float operator bool(); 6963 // }; 6964 // 6965 // The return type will be changed later anyway. 6966 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6967 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6968 << SourceRange(D.getIdentifierLoc()); 6969 D.setInvalidType(); 6970 } 6971 6972 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6973 6974 // Make sure we don't have any parameters. 6975 if (Proto->getNumParams() > 0) { 6976 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6977 6978 // Delete the parameters. 6979 D.getFunctionTypeInfo().freeParams(); 6980 D.setInvalidType(); 6981 } else if (Proto->isVariadic()) { 6982 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6983 D.setInvalidType(); 6984 } 6985 6986 // Diagnose "&operator bool()" and other such nonsense. This 6987 // is actually a gcc extension which we don't support. 6988 if (Proto->getReturnType() != ConvType) { 6989 bool NeedsTypedef = false; 6990 SourceRange Before, After; 6991 6992 // Walk the chunks and extract information on them for our diagnostic. 6993 bool PastFunctionChunk = false; 6994 for (auto &Chunk : D.type_objects()) { 6995 switch (Chunk.Kind) { 6996 case DeclaratorChunk::Function: 6997 if (!PastFunctionChunk) { 6998 if (Chunk.Fun.HasTrailingReturnType) { 6999 TypeSourceInfo *TRT = nullptr; 7000 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 7001 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 7002 } 7003 PastFunctionChunk = true; 7004 break; 7005 } 7006 // Fall through. 7007 case DeclaratorChunk::Array: 7008 NeedsTypedef = true; 7009 extendRight(After, Chunk.getSourceRange()); 7010 break; 7011 7012 case DeclaratorChunk::Pointer: 7013 case DeclaratorChunk::BlockPointer: 7014 case DeclaratorChunk::Reference: 7015 case DeclaratorChunk::MemberPointer: 7016 extendLeft(Before, Chunk.getSourceRange()); 7017 break; 7018 7019 case DeclaratorChunk::Paren: 7020 extendLeft(Before, Chunk.Loc); 7021 extendRight(After, Chunk.EndLoc); 7022 break; 7023 } 7024 } 7025 7026 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 7027 After.isValid() ? After.getBegin() : 7028 D.getIdentifierLoc(); 7029 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 7030 DB << Before << After; 7031 7032 if (!NeedsTypedef) { 7033 DB << /*don't need a typedef*/0; 7034 7035 // If we can provide a correct fix-it hint, do so. 7036 if (After.isInvalid() && ConvTSI) { 7037 SourceLocation InsertLoc = 7038 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 7039 DB << FixItHint::CreateInsertion(InsertLoc, " ") 7040 << FixItHint::CreateInsertionFromRange( 7041 InsertLoc, CharSourceRange::getTokenRange(Before)) 7042 << FixItHint::CreateRemoval(Before); 7043 } 7044 } else if (!Proto->getReturnType()->isDependentType()) { 7045 DB << /*typedef*/1 << Proto->getReturnType(); 7046 } else if (getLangOpts().CPlusPlus11) { 7047 DB << /*alias template*/2 << Proto->getReturnType(); 7048 } else { 7049 DB << /*might not be fixable*/3; 7050 } 7051 7052 // Recover by incorporating the other type chunks into the result type. 7053 // Note, this does *not* change the name of the function. This is compatible 7054 // with the GCC extension: 7055 // struct S { &operator int(); } s; 7056 // int &r = s.operator int(); // ok in GCC 7057 // S::operator int&() {} // error in GCC, function name is 'operator int'. 7058 ConvType = Proto->getReturnType(); 7059 } 7060 7061 // C++ [class.conv.fct]p4: 7062 // The conversion-type-id shall not represent a function type nor 7063 // an array type. 7064 if (ConvType->isArrayType()) { 7065 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7066 ConvType = Context.getPointerType(ConvType); 7067 D.setInvalidType(); 7068 } else if (ConvType->isFunctionType()) { 7069 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7070 ConvType = Context.getPointerType(ConvType); 7071 D.setInvalidType(); 7072 } 7073 7074 // Rebuild the function type "R" without any parameters (in case any 7075 // of the errors above fired) and with the conversion type as the 7076 // return type. 7077 if (D.isInvalidType()) 7078 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7079 7080 // C++0x explicit conversion operators. 7081 if (D.getDeclSpec().isExplicitSpecified()) 7082 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7083 getLangOpts().CPlusPlus11 ? 7084 diag::warn_cxx98_compat_explicit_conversion_functions : 7085 diag::ext_explicit_conversion_functions) 7086 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7087 } 7088 7089 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 7090 /// the declaration of the given C++ conversion function. This routine 7091 /// is responsible for recording the conversion function in the C++ 7092 /// class, if possible. 7093 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 7094 assert(Conversion && "Expected to receive a conversion function declaration"); 7095 7096 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 7097 7098 // Make sure we aren't redeclaring the conversion function. 7099 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 7100 7101 // C++ [class.conv.fct]p1: 7102 // [...] A conversion function is never used to convert a 7103 // (possibly cv-qualified) object to the (possibly cv-qualified) 7104 // same object type (or a reference to it), to a (possibly 7105 // cv-qualified) base class of that type (or a reference to it), 7106 // or to (possibly cv-qualified) void. 7107 // FIXME: Suppress this warning if the conversion function ends up being a 7108 // virtual function that overrides a virtual function in a base class. 7109 QualType ClassType 7110 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7111 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 7112 ConvType = ConvTypeRef->getPointeeType(); 7113 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 7114 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 7115 /* Suppress diagnostics for instantiations. */; 7116 else if (ConvType->isRecordType()) { 7117 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 7118 if (ConvType == ClassType) 7119 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 7120 << ClassType; 7121 else if (IsDerivedFrom(ClassType, ConvType)) 7122 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 7123 << ClassType << ConvType; 7124 } else if (ConvType->isVoidType()) { 7125 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 7126 << ClassType << ConvType; 7127 } 7128 7129 if (FunctionTemplateDecl *ConversionTemplate 7130 = Conversion->getDescribedFunctionTemplate()) 7131 return ConversionTemplate; 7132 7133 return Conversion; 7134 } 7135 7136 //===----------------------------------------------------------------------===// 7137 // Namespace Handling 7138 //===----------------------------------------------------------------------===// 7139 7140 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 7141 /// reopened. 7142 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 7143 SourceLocation Loc, 7144 IdentifierInfo *II, bool *IsInline, 7145 NamespaceDecl *PrevNS) { 7146 assert(*IsInline != PrevNS->isInline()); 7147 7148 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 7149 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 7150 // inline namespaces, with the intention of bringing names into namespace std. 7151 // 7152 // We support this just well enough to get that case working; this is not 7153 // sufficient to support reopening namespaces as inline in general. 7154 if (*IsInline && II && II->getName().startswith("__atomic") && 7155 S.getSourceManager().isInSystemHeader(Loc)) { 7156 // Mark all prior declarations of the namespace as inline. 7157 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 7158 NS = NS->getPreviousDecl()) 7159 NS->setInline(*IsInline); 7160 // Patch up the lookup table for the containing namespace. This isn't really 7161 // correct, but it's good enough for this particular case. 7162 for (auto *I : PrevNS->decls()) 7163 if (auto *ND = dyn_cast<NamedDecl>(I)) 7164 PrevNS->getParent()->makeDeclVisibleInContext(ND); 7165 return; 7166 } 7167 7168 if (PrevNS->isInline()) 7169 // The user probably just forgot the 'inline', so suggest that it 7170 // be added back. 7171 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 7172 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 7173 else 7174 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 7175 7176 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7177 *IsInline = PrevNS->isInline(); 7178 } 7179 7180 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7181 /// definition. 7182 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7183 SourceLocation InlineLoc, 7184 SourceLocation NamespaceLoc, 7185 SourceLocation IdentLoc, 7186 IdentifierInfo *II, 7187 SourceLocation LBrace, 7188 AttributeList *AttrList) { 7189 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7190 // For anonymous namespace, take the location of the left brace. 7191 SourceLocation Loc = II ? IdentLoc : LBrace; 7192 bool IsInline = InlineLoc.isValid(); 7193 bool IsInvalid = false; 7194 bool IsStd = false; 7195 bool AddToKnown = false; 7196 Scope *DeclRegionScope = NamespcScope->getParent(); 7197 7198 NamespaceDecl *PrevNS = nullptr; 7199 if (II) { 7200 // C++ [namespace.def]p2: 7201 // The identifier in an original-namespace-definition shall not 7202 // have been previously defined in the declarative region in 7203 // which the original-namespace-definition appears. The 7204 // identifier in an original-namespace-definition is the name of 7205 // the namespace. Subsequently in that declarative region, it is 7206 // treated as an original-namespace-name. 7207 // 7208 // Since namespace names are unique in their scope, and we don't 7209 // look through using directives, just look for any ordinary names. 7210 7211 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7212 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7213 Decl::IDNS_Namespace; 7214 NamedDecl *PrevDecl = nullptr; 7215 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7216 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7217 ++I) { 7218 if ((*I)->getIdentifierNamespace() & IDNS) { 7219 PrevDecl = *I; 7220 break; 7221 } 7222 } 7223 7224 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7225 7226 if (PrevNS) { 7227 // This is an extended namespace definition. 7228 if (IsInline != PrevNS->isInline()) 7229 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7230 &IsInline, PrevNS); 7231 } else if (PrevDecl) { 7232 // This is an invalid name redefinition. 7233 Diag(Loc, diag::err_redefinition_different_kind) 7234 << II; 7235 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7236 IsInvalid = true; 7237 // Continue on to push Namespc as current DeclContext and return it. 7238 } else if (II->isStr("std") && 7239 CurContext->getRedeclContext()->isTranslationUnit()) { 7240 // This is the first "real" definition of the namespace "std", so update 7241 // our cache of the "std" namespace to point at this definition. 7242 PrevNS = getStdNamespace(); 7243 IsStd = true; 7244 AddToKnown = !IsInline; 7245 } else { 7246 // We've seen this namespace for the first time. 7247 AddToKnown = !IsInline; 7248 } 7249 } else { 7250 // Anonymous namespaces. 7251 7252 // Determine whether the parent already has an anonymous namespace. 7253 DeclContext *Parent = CurContext->getRedeclContext(); 7254 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7255 PrevNS = TU->getAnonymousNamespace(); 7256 } else { 7257 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7258 PrevNS = ND->getAnonymousNamespace(); 7259 } 7260 7261 if (PrevNS && IsInline != PrevNS->isInline()) 7262 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7263 &IsInline, PrevNS); 7264 } 7265 7266 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7267 StartLoc, Loc, II, PrevNS); 7268 if (IsInvalid) 7269 Namespc->setInvalidDecl(); 7270 7271 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7272 7273 // FIXME: Should we be merging attributes? 7274 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7275 PushNamespaceVisibilityAttr(Attr, Loc); 7276 7277 if (IsStd) 7278 StdNamespace = Namespc; 7279 if (AddToKnown) 7280 KnownNamespaces[Namespc] = false; 7281 7282 if (II) { 7283 PushOnScopeChains(Namespc, DeclRegionScope); 7284 } else { 7285 // Link the anonymous namespace into its parent. 7286 DeclContext *Parent = CurContext->getRedeclContext(); 7287 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7288 TU->setAnonymousNamespace(Namespc); 7289 } else { 7290 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7291 } 7292 7293 CurContext->addDecl(Namespc); 7294 7295 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7296 // behaves as if it were replaced by 7297 // namespace unique { /* empty body */ } 7298 // using namespace unique; 7299 // namespace unique { namespace-body } 7300 // where all occurrences of 'unique' in a translation unit are 7301 // replaced by the same identifier and this identifier differs 7302 // from all other identifiers in the entire program. 7303 7304 // We just create the namespace with an empty name and then add an 7305 // implicit using declaration, just like the standard suggests. 7306 // 7307 // CodeGen enforces the "universally unique" aspect by giving all 7308 // declarations semantically contained within an anonymous 7309 // namespace internal linkage. 7310 7311 if (!PrevNS) { 7312 UsingDirectiveDecl* UD 7313 = UsingDirectiveDecl::Create(Context, Parent, 7314 /* 'using' */ LBrace, 7315 /* 'namespace' */ SourceLocation(), 7316 /* qualifier */ NestedNameSpecifierLoc(), 7317 /* identifier */ SourceLocation(), 7318 Namespc, 7319 /* Ancestor */ Parent); 7320 UD->setImplicit(); 7321 Parent->addDecl(UD); 7322 } 7323 } 7324 7325 ActOnDocumentableDecl(Namespc); 7326 7327 // Although we could have an invalid decl (i.e. the namespace name is a 7328 // redefinition), push it as current DeclContext and try to continue parsing. 7329 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7330 // for the namespace has the declarations that showed up in that particular 7331 // namespace definition. 7332 PushDeclContext(NamespcScope, Namespc); 7333 return Namespc; 7334 } 7335 7336 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7337 /// is a namespace alias, returns the namespace it points to. 7338 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7339 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7340 return AD->getNamespace(); 7341 return dyn_cast_or_null<NamespaceDecl>(D); 7342 } 7343 7344 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7345 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7346 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7347 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7348 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7349 Namespc->setRBraceLoc(RBrace); 7350 PopDeclContext(); 7351 if (Namespc->hasAttr<VisibilityAttr>()) 7352 PopPragmaVisibility(true, RBrace); 7353 } 7354 7355 CXXRecordDecl *Sema::getStdBadAlloc() const { 7356 return cast_or_null<CXXRecordDecl>( 7357 StdBadAlloc.get(Context.getExternalSource())); 7358 } 7359 7360 NamespaceDecl *Sema::getStdNamespace() const { 7361 return cast_or_null<NamespaceDecl>( 7362 StdNamespace.get(Context.getExternalSource())); 7363 } 7364 7365 /// \brief Retrieve the special "std" namespace, which may require us to 7366 /// implicitly define the namespace. 7367 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7368 if (!StdNamespace) { 7369 // The "std" namespace has not yet been defined, so build one implicitly. 7370 StdNamespace = NamespaceDecl::Create(Context, 7371 Context.getTranslationUnitDecl(), 7372 /*Inline=*/false, 7373 SourceLocation(), SourceLocation(), 7374 &PP.getIdentifierTable().get("std"), 7375 /*PrevDecl=*/nullptr); 7376 getStdNamespace()->setImplicit(true); 7377 } 7378 7379 return getStdNamespace(); 7380 } 7381 7382 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7383 assert(getLangOpts().CPlusPlus && 7384 "Looking for std::initializer_list outside of C++."); 7385 7386 // We're looking for implicit instantiations of 7387 // template <typename E> class std::initializer_list. 7388 7389 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7390 return false; 7391 7392 ClassTemplateDecl *Template = nullptr; 7393 const TemplateArgument *Arguments = nullptr; 7394 7395 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7396 7397 ClassTemplateSpecializationDecl *Specialization = 7398 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7399 if (!Specialization) 7400 return false; 7401 7402 Template = Specialization->getSpecializedTemplate(); 7403 Arguments = Specialization->getTemplateArgs().data(); 7404 } else if (const TemplateSpecializationType *TST = 7405 Ty->getAs<TemplateSpecializationType>()) { 7406 Template = dyn_cast_or_null<ClassTemplateDecl>( 7407 TST->getTemplateName().getAsTemplateDecl()); 7408 Arguments = TST->getArgs(); 7409 } 7410 if (!Template) 7411 return false; 7412 7413 if (!StdInitializerList) { 7414 // Haven't recognized std::initializer_list yet, maybe this is it. 7415 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7416 if (TemplateClass->getIdentifier() != 7417 &PP.getIdentifierTable().get("initializer_list") || 7418 !getStdNamespace()->InEnclosingNamespaceSetOf( 7419 TemplateClass->getDeclContext())) 7420 return false; 7421 // This is a template called std::initializer_list, but is it the right 7422 // template? 7423 TemplateParameterList *Params = Template->getTemplateParameters(); 7424 if (Params->getMinRequiredArguments() != 1) 7425 return false; 7426 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7427 return false; 7428 7429 // It's the right template. 7430 StdInitializerList = Template; 7431 } 7432 7433 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 7434 return false; 7435 7436 // This is an instance of std::initializer_list. Find the argument type. 7437 if (Element) 7438 *Element = Arguments[0].getAsType(); 7439 return true; 7440 } 7441 7442 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7443 NamespaceDecl *Std = S.getStdNamespace(); 7444 if (!Std) { 7445 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7446 return nullptr; 7447 } 7448 7449 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7450 Loc, Sema::LookupOrdinaryName); 7451 if (!S.LookupQualifiedName(Result, Std)) { 7452 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7453 return nullptr; 7454 } 7455 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7456 if (!Template) { 7457 Result.suppressDiagnostics(); 7458 // We found something weird. Complain about the first thing we found. 7459 NamedDecl *Found = *Result.begin(); 7460 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7461 return nullptr; 7462 } 7463 7464 // We found some template called std::initializer_list. Now verify that it's 7465 // correct. 7466 TemplateParameterList *Params = Template->getTemplateParameters(); 7467 if (Params->getMinRequiredArguments() != 1 || 7468 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7469 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7470 return nullptr; 7471 } 7472 7473 return Template; 7474 } 7475 7476 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7477 if (!StdInitializerList) { 7478 StdInitializerList = LookupStdInitializerList(*this, Loc); 7479 if (!StdInitializerList) 7480 return QualType(); 7481 } 7482 7483 TemplateArgumentListInfo Args(Loc, Loc); 7484 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7485 Context.getTrivialTypeSourceInfo(Element, 7486 Loc))); 7487 return Context.getCanonicalType( 7488 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7489 } 7490 7491 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7492 // C++ [dcl.init.list]p2: 7493 // A constructor is an initializer-list constructor if its first parameter 7494 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7495 // std::initializer_list<E> for some type E, and either there are no other 7496 // parameters or else all other parameters have default arguments. 7497 if (Ctor->getNumParams() < 1 || 7498 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7499 return false; 7500 7501 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7502 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7503 ArgType = RT->getPointeeType().getUnqualifiedType(); 7504 7505 return isStdInitializerList(ArgType, nullptr); 7506 } 7507 7508 /// \brief Determine whether a using statement is in a context where it will be 7509 /// apply in all contexts. 7510 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7511 switch (CurContext->getDeclKind()) { 7512 case Decl::TranslationUnit: 7513 return true; 7514 case Decl::LinkageSpec: 7515 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7516 default: 7517 return false; 7518 } 7519 } 7520 7521 namespace { 7522 7523 // Callback to only accept typo corrections that are namespaces. 7524 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7525 public: 7526 bool ValidateCandidate(const TypoCorrection &candidate) override { 7527 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7528 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7529 return false; 7530 } 7531 }; 7532 7533 } 7534 7535 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7536 CXXScopeSpec &SS, 7537 SourceLocation IdentLoc, 7538 IdentifierInfo *Ident) { 7539 R.clear(); 7540 if (TypoCorrection Corrected = 7541 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7542 llvm::make_unique<NamespaceValidatorCCC>(), 7543 Sema::CTK_ErrorRecovery)) { 7544 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7545 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7546 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7547 Ident->getName().equals(CorrectedStr); 7548 S.diagnoseTypo(Corrected, 7549 S.PDiag(diag::err_using_directive_member_suggest) 7550 << Ident << DC << DroppedSpecifier << SS.getRange(), 7551 S.PDiag(diag::note_namespace_defined_here)); 7552 } else { 7553 S.diagnoseTypo(Corrected, 7554 S.PDiag(diag::err_using_directive_suggest) << Ident, 7555 S.PDiag(diag::note_namespace_defined_here)); 7556 } 7557 R.addDecl(Corrected.getCorrectionDecl()); 7558 return true; 7559 } 7560 return false; 7561 } 7562 7563 Decl *Sema::ActOnUsingDirective(Scope *S, 7564 SourceLocation UsingLoc, 7565 SourceLocation NamespcLoc, 7566 CXXScopeSpec &SS, 7567 SourceLocation IdentLoc, 7568 IdentifierInfo *NamespcName, 7569 AttributeList *AttrList) { 7570 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7571 assert(NamespcName && "Invalid NamespcName."); 7572 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7573 7574 // This can only happen along a recovery path. 7575 while (S->getFlags() & Scope::TemplateParamScope) 7576 S = S->getParent(); 7577 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7578 7579 UsingDirectiveDecl *UDir = nullptr; 7580 NestedNameSpecifier *Qualifier = nullptr; 7581 if (SS.isSet()) 7582 Qualifier = SS.getScopeRep(); 7583 7584 // Lookup namespace name. 7585 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7586 LookupParsedName(R, S, &SS); 7587 if (R.isAmbiguous()) 7588 return nullptr; 7589 7590 if (R.empty()) { 7591 R.clear(); 7592 // Allow "using namespace std;" or "using namespace ::std;" even if 7593 // "std" hasn't been defined yet, for GCC compatibility. 7594 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7595 NamespcName->isStr("std")) { 7596 Diag(IdentLoc, diag::ext_using_undefined_std); 7597 R.addDecl(getOrCreateStdNamespace()); 7598 R.resolveKind(); 7599 } 7600 // Otherwise, attempt typo correction. 7601 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7602 } 7603 7604 if (!R.empty()) { 7605 NamedDecl *Named = R.getFoundDecl(); 7606 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7607 && "expected namespace decl"); 7608 7609 // The use of a nested name specifier may trigger deprecation warnings. 7610 DiagnoseUseOfDecl(Named, IdentLoc); 7611 7612 // C++ [namespace.udir]p1: 7613 // A using-directive specifies that the names in the nominated 7614 // namespace can be used in the scope in which the 7615 // using-directive appears after the using-directive. During 7616 // unqualified name lookup (3.4.1), the names appear as if they 7617 // were declared in the nearest enclosing namespace which 7618 // contains both the using-directive and the nominated 7619 // namespace. [Note: in this context, "contains" means "contains 7620 // directly or indirectly". ] 7621 7622 // Find enclosing context containing both using-directive and 7623 // nominated namespace. 7624 NamespaceDecl *NS = getNamespaceDecl(Named); 7625 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7626 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7627 CommonAncestor = CommonAncestor->getParent(); 7628 7629 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7630 SS.getWithLocInContext(Context), 7631 IdentLoc, Named, CommonAncestor); 7632 7633 if (IsUsingDirectiveInToplevelContext(CurContext) && 7634 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7635 Diag(IdentLoc, diag::warn_using_directive_in_header); 7636 } 7637 7638 PushUsingDirective(S, UDir); 7639 } else { 7640 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7641 } 7642 7643 if (UDir) 7644 ProcessDeclAttributeList(S, UDir, AttrList); 7645 7646 return UDir; 7647 } 7648 7649 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7650 // If the scope has an associated entity and the using directive is at 7651 // namespace or translation unit scope, add the UsingDirectiveDecl into 7652 // its lookup structure so qualified name lookup can find it. 7653 DeclContext *Ctx = S->getEntity(); 7654 if (Ctx && !Ctx->isFunctionOrMethod()) 7655 Ctx->addDecl(UDir); 7656 else 7657 // Otherwise, it is at block scope. The using-directives will affect lookup 7658 // only to the end of the scope. 7659 S->PushUsingDirective(UDir); 7660 } 7661 7662 7663 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7664 AccessSpecifier AS, 7665 bool HasUsingKeyword, 7666 SourceLocation UsingLoc, 7667 CXXScopeSpec &SS, 7668 UnqualifiedId &Name, 7669 AttributeList *AttrList, 7670 bool HasTypenameKeyword, 7671 SourceLocation TypenameLoc) { 7672 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7673 7674 switch (Name.getKind()) { 7675 case UnqualifiedId::IK_ImplicitSelfParam: 7676 case UnqualifiedId::IK_Identifier: 7677 case UnqualifiedId::IK_OperatorFunctionId: 7678 case UnqualifiedId::IK_LiteralOperatorId: 7679 case UnqualifiedId::IK_ConversionFunctionId: 7680 break; 7681 7682 case UnqualifiedId::IK_ConstructorName: 7683 case UnqualifiedId::IK_ConstructorTemplateId: 7684 // C++11 inheriting constructors. 7685 Diag(Name.getLocStart(), 7686 getLangOpts().CPlusPlus11 ? 7687 diag::warn_cxx98_compat_using_decl_constructor : 7688 diag::err_using_decl_constructor) 7689 << SS.getRange(); 7690 7691 if (getLangOpts().CPlusPlus11) break; 7692 7693 return nullptr; 7694 7695 case UnqualifiedId::IK_DestructorName: 7696 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7697 << SS.getRange(); 7698 return nullptr; 7699 7700 case UnqualifiedId::IK_TemplateId: 7701 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7702 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7703 return nullptr; 7704 } 7705 7706 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7707 DeclarationName TargetName = TargetNameInfo.getName(); 7708 if (!TargetName) 7709 return nullptr; 7710 7711 // Warn about access declarations. 7712 if (!HasUsingKeyword) { 7713 Diag(Name.getLocStart(), 7714 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7715 : diag::warn_access_decl_deprecated) 7716 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7717 } 7718 7719 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7720 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7721 return nullptr; 7722 7723 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7724 TargetNameInfo, AttrList, 7725 /* IsInstantiation */ false, 7726 HasTypenameKeyword, TypenameLoc); 7727 if (UD) 7728 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7729 7730 return UD; 7731 } 7732 7733 /// \brief Determine whether a using declaration considers the given 7734 /// declarations as "equivalent", e.g., if they are redeclarations of 7735 /// the same entity or are both typedefs of the same type. 7736 static bool 7737 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7738 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7739 return true; 7740 7741 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7742 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7743 return Context.hasSameType(TD1->getUnderlyingType(), 7744 TD2->getUnderlyingType()); 7745 7746 return false; 7747 } 7748 7749 7750 /// Determines whether to create a using shadow decl for a particular 7751 /// decl, given the set of decls existing prior to this using lookup. 7752 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7753 const LookupResult &Previous, 7754 UsingShadowDecl *&PrevShadow) { 7755 // Diagnose finding a decl which is not from a base class of the 7756 // current class. We do this now because there are cases where this 7757 // function will silently decide not to build a shadow decl, which 7758 // will pre-empt further diagnostics. 7759 // 7760 // We don't need to do this in C++0x because we do the check once on 7761 // the qualifier. 7762 // 7763 // FIXME: diagnose the following if we care enough: 7764 // struct A { int foo; }; 7765 // struct B : A { using A::foo; }; 7766 // template <class T> struct C : A {}; 7767 // template <class T> struct D : C<T> { using B::foo; } // <--- 7768 // This is invalid (during instantiation) in C++03 because B::foo 7769 // resolves to the using decl in B, which is not a base class of D<T>. 7770 // We can't diagnose it immediately because C<T> is an unknown 7771 // specialization. The UsingShadowDecl in D<T> then points directly 7772 // to A::foo, which will look well-formed when we instantiate. 7773 // The right solution is to not collapse the shadow-decl chain. 7774 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7775 DeclContext *OrigDC = Orig->getDeclContext(); 7776 7777 // Handle enums and anonymous structs. 7778 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7779 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7780 while (OrigRec->isAnonymousStructOrUnion()) 7781 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7782 7783 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7784 if (OrigDC == CurContext) { 7785 Diag(Using->getLocation(), 7786 diag::err_using_decl_nested_name_specifier_is_current_class) 7787 << Using->getQualifierLoc().getSourceRange(); 7788 Diag(Orig->getLocation(), diag::note_using_decl_target); 7789 return true; 7790 } 7791 7792 Diag(Using->getQualifierLoc().getBeginLoc(), 7793 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7794 << Using->getQualifier() 7795 << cast<CXXRecordDecl>(CurContext) 7796 << Using->getQualifierLoc().getSourceRange(); 7797 Diag(Orig->getLocation(), diag::note_using_decl_target); 7798 return true; 7799 } 7800 } 7801 7802 if (Previous.empty()) return false; 7803 7804 NamedDecl *Target = Orig; 7805 if (isa<UsingShadowDecl>(Target)) 7806 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7807 7808 // If the target happens to be one of the previous declarations, we 7809 // don't have a conflict. 7810 // 7811 // FIXME: but we might be increasing its access, in which case we 7812 // should redeclare it. 7813 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7814 bool FoundEquivalentDecl = false; 7815 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7816 I != E; ++I) { 7817 NamedDecl *D = (*I)->getUnderlyingDecl(); 7818 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7819 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7820 PrevShadow = Shadow; 7821 FoundEquivalentDecl = true; 7822 } 7823 7824 if (isVisible(D)) 7825 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7826 } 7827 7828 if (FoundEquivalentDecl) 7829 return false; 7830 7831 if (FunctionDecl *FD = Target->getAsFunction()) { 7832 NamedDecl *OldDecl = nullptr; 7833 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7834 /*IsForUsingDecl*/ true)) { 7835 case Ovl_Overload: 7836 return false; 7837 7838 case Ovl_NonFunction: 7839 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7840 break; 7841 7842 // We found a decl with the exact signature. 7843 case Ovl_Match: 7844 // If we're in a record, we want to hide the target, so we 7845 // return true (without a diagnostic) to tell the caller not to 7846 // build a shadow decl. 7847 if (CurContext->isRecord()) 7848 return true; 7849 7850 // If we're not in a record, this is an error. 7851 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7852 break; 7853 } 7854 7855 Diag(Target->getLocation(), diag::note_using_decl_target); 7856 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7857 return true; 7858 } 7859 7860 // Target is not a function. 7861 7862 if (isa<TagDecl>(Target)) { 7863 // No conflict between a tag and a non-tag. 7864 if (!Tag) return false; 7865 7866 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7867 Diag(Target->getLocation(), diag::note_using_decl_target); 7868 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7869 return true; 7870 } 7871 7872 // No conflict between a tag and a non-tag. 7873 if (!NonTag) return false; 7874 7875 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7876 Diag(Target->getLocation(), diag::note_using_decl_target); 7877 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7878 return true; 7879 } 7880 7881 /// Builds a shadow declaration corresponding to a 'using' declaration. 7882 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7883 UsingDecl *UD, 7884 NamedDecl *Orig, 7885 UsingShadowDecl *PrevDecl) { 7886 7887 // If we resolved to another shadow declaration, just coalesce them. 7888 NamedDecl *Target = Orig; 7889 if (isa<UsingShadowDecl>(Target)) { 7890 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7891 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7892 } 7893 7894 UsingShadowDecl *Shadow 7895 = UsingShadowDecl::Create(Context, CurContext, 7896 UD->getLocation(), UD, Target); 7897 UD->addShadowDecl(Shadow); 7898 7899 Shadow->setAccess(UD->getAccess()); 7900 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7901 Shadow->setInvalidDecl(); 7902 7903 Shadow->setPreviousDecl(PrevDecl); 7904 7905 if (S) 7906 PushOnScopeChains(Shadow, S); 7907 else 7908 CurContext->addDecl(Shadow); 7909 7910 7911 return Shadow; 7912 } 7913 7914 /// Hides a using shadow declaration. This is required by the current 7915 /// using-decl implementation when a resolvable using declaration in a 7916 /// class is followed by a declaration which would hide or override 7917 /// one or more of the using decl's targets; for example: 7918 /// 7919 /// struct Base { void foo(int); }; 7920 /// struct Derived : Base { 7921 /// using Base::foo; 7922 /// void foo(int); 7923 /// }; 7924 /// 7925 /// The governing language is C++03 [namespace.udecl]p12: 7926 /// 7927 /// When a using-declaration brings names from a base class into a 7928 /// derived class scope, member functions in the derived class 7929 /// override and/or hide member functions with the same name and 7930 /// parameter types in a base class (rather than conflicting). 7931 /// 7932 /// There are two ways to implement this: 7933 /// (1) optimistically create shadow decls when they're not hidden 7934 /// by existing declarations, or 7935 /// (2) don't create any shadow decls (or at least don't make them 7936 /// visible) until we've fully parsed/instantiated the class. 7937 /// The problem with (1) is that we might have to retroactively remove 7938 /// a shadow decl, which requires several O(n) operations because the 7939 /// decl structures are (very reasonably) not designed for removal. 7940 /// (2) avoids this but is very fiddly and phase-dependent. 7941 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7942 if (Shadow->getDeclName().getNameKind() == 7943 DeclarationName::CXXConversionFunctionName) 7944 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7945 7946 // Remove it from the DeclContext... 7947 Shadow->getDeclContext()->removeDecl(Shadow); 7948 7949 // ...and the scope, if applicable... 7950 if (S) { 7951 S->RemoveDecl(Shadow); 7952 IdResolver.RemoveDecl(Shadow); 7953 } 7954 7955 // ...and the using decl. 7956 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7957 7958 // TODO: complain somehow if Shadow was used. It shouldn't 7959 // be possible for this to happen, because...? 7960 } 7961 7962 /// Find the base specifier for a base class with the given type. 7963 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7964 QualType DesiredBase, 7965 bool &AnyDependentBases) { 7966 // Check whether the named type is a direct base class. 7967 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7968 for (auto &Base : Derived->bases()) { 7969 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7970 if (CanonicalDesiredBase == BaseType) 7971 return &Base; 7972 if (BaseType->isDependentType()) 7973 AnyDependentBases = true; 7974 } 7975 return nullptr; 7976 } 7977 7978 namespace { 7979 class UsingValidatorCCC : public CorrectionCandidateCallback { 7980 public: 7981 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7982 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7983 : HasTypenameKeyword(HasTypenameKeyword), 7984 IsInstantiation(IsInstantiation), OldNNS(NNS), 7985 RequireMemberOf(RequireMemberOf) {} 7986 7987 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7988 NamedDecl *ND = Candidate.getCorrectionDecl(); 7989 7990 // Keywords are not valid here. 7991 if (!ND || isa<NamespaceDecl>(ND)) 7992 return false; 7993 7994 // Completely unqualified names are invalid for a 'using' declaration. 7995 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7996 return false; 7997 7998 if (RequireMemberOf) { 7999 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8000 if (FoundRecord && FoundRecord->isInjectedClassName()) { 8001 // No-one ever wants a using-declaration to name an injected-class-name 8002 // of a base class, unless they're declaring an inheriting constructor. 8003 ASTContext &Ctx = ND->getASTContext(); 8004 if (!Ctx.getLangOpts().CPlusPlus11) 8005 return false; 8006 QualType FoundType = Ctx.getRecordType(FoundRecord); 8007 8008 // Check that the injected-class-name is named as a member of its own 8009 // type; we don't want to suggest 'using Derived::Base;', since that 8010 // means something else. 8011 NestedNameSpecifier *Specifier = 8012 Candidate.WillReplaceSpecifier() 8013 ? Candidate.getCorrectionSpecifier() 8014 : OldNNS; 8015 if (!Specifier->getAsType() || 8016 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 8017 return false; 8018 8019 // Check that this inheriting constructor declaration actually names a 8020 // direct base class of the current class. 8021 bool AnyDependentBases = false; 8022 if (!findDirectBaseWithType(RequireMemberOf, 8023 Ctx.getRecordType(FoundRecord), 8024 AnyDependentBases) && 8025 !AnyDependentBases) 8026 return false; 8027 } else { 8028 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 8029 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 8030 return false; 8031 8032 // FIXME: Check that the base class member is accessible? 8033 } 8034 } 8035 8036 if (isa<TypeDecl>(ND)) 8037 return HasTypenameKeyword || !IsInstantiation; 8038 8039 return !HasTypenameKeyword; 8040 } 8041 8042 private: 8043 bool HasTypenameKeyword; 8044 bool IsInstantiation; 8045 NestedNameSpecifier *OldNNS; 8046 CXXRecordDecl *RequireMemberOf; 8047 }; 8048 } // end anonymous namespace 8049 8050 /// Builds a using declaration. 8051 /// 8052 /// \param IsInstantiation - Whether this call arises from an 8053 /// instantiation of an unresolved using declaration. We treat 8054 /// the lookup differently for these declarations. 8055 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 8056 SourceLocation UsingLoc, 8057 CXXScopeSpec &SS, 8058 DeclarationNameInfo NameInfo, 8059 AttributeList *AttrList, 8060 bool IsInstantiation, 8061 bool HasTypenameKeyword, 8062 SourceLocation TypenameLoc) { 8063 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8064 SourceLocation IdentLoc = NameInfo.getLoc(); 8065 assert(IdentLoc.isValid() && "Invalid TargetName location."); 8066 8067 // FIXME: We ignore attributes for now. 8068 8069 if (SS.isEmpty()) { 8070 Diag(IdentLoc, diag::err_using_requires_qualname); 8071 return nullptr; 8072 } 8073 8074 // Do the redeclaration lookup in the current scope. 8075 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 8076 ForRedeclaration); 8077 Previous.setHideTags(false); 8078 if (S) { 8079 LookupName(Previous, S); 8080 8081 // It is really dumb that we have to do this. 8082 LookupResult::Filter F = Previous.makeFilter(); 8083 while (F.hasNext()) { 8084 NamedDecl *D = F.next(); 8085 if (!isDeclInScope(D, CurContext, S)) 8086 F.erase(); 8087 // If we found a local extern declaration that's not ordinarily visible, 8088 // and this declaration is being added to a non-block scope, ignore it. 8089 // We're only checking for scope conflicts here, not also for violations 8090 // of the linkage rules. 8091 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 8092 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 8093 F.erase(); 8094 } 8095 F.done(); 8096 } else { 8097 assert(IsInstantiation && "no scope in non-instantiation"); 8098 assert(CurContext->isRecord() && "scope not record in instantiation"); 8099 LookupQualifiedName(Previous, CurContext); 8100 } 8101 8102 // Check for invalid redeclarations. 8103 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 8104 SS, IdentLoc, Previous)) 8105 return nullptr; 8106 8107 // Check for bad qualifiers. 8108 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 8109 return nullptr; 8110 8111 DeclContext *LookupContext = computeDeclContext(SS); 8112 NamedDecl *D; 8113 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8114 if (!LookupContext) { 8115 if (HasTypenameKeyword) { 8116 // FIXME: not all declaration name kinds are legal here 8117 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8118 UsingLoc, TypenameLoc, 8119 QualifierLoc, 8120 IdentLoc, NameInfo.getName()); 8121 } else { 8122 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8123 QualifierLoc, NameInfo); 8124 } 8125 D->setAccess(AS); 8126 CurContext->addDecl(D); 8127 return D; 8128 } 8129 8130 auto Build = [&](bool Invalid) { 8131 UsingDecl *UD = 8132 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8133 HasTypenameKeyword); 8134 UD->setAccess(AS); 8135 CurContext->addDecl(UD); 8136 UD->setInvalidDecl(Invalid); 8137 return UD; 8138 }; 8139 auto BuildInvalid = [&]{ return Build(true); }; 8140 auto BuildValid = [&]{ return Build(false); }; 8141 8142 if (RequireCompleteDeclContext(SS, LookupContext)) 8143 return BuildInvalid(); 8144 8145 // Look up the target name. 8146 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8147 8148 // Unlike most lookups, we don't always want to hide tag 8149 // declarations: tag names are visible through the using declaration 8150 // even if hidden by ordinary names, *except* in a dependent context 8151 // where it's important for the sanity of two-phase lookup. 8152 if (!IsInstantiation) 8153 R.setHideTags(false); 8154 8155 // For the purposes of this lookup, we have a base object type 8156 // equal to that of the current context. 8157 if (CurContext->isRecord()) { 8158 R.setBaseObjectType( 8159 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8160 } 8161 8162 LookupQualifiedName(R, LookupContext); 8163 8164 // Try to correct typos if possible. If constructor name lookup finds no 8165 // results, that means the named class has no explicit constructors, and we 8166 // suppressed declaring implicit ones (probably because it's dependent or 8167 // invalid). 8168 if (R.empty() && 8169 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 8170 if (TypoCorrection Corrected = CorrectTypo( 8171 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8172 llvm::make_unique<UsingValidatorCCC>( 8173 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8174 dyn_cast<CXXRecordDecl>(CurContext)), 8175 CTK_ErrorRecovery)) { 8176 // We reject any correction for which ND would be NULL. 8177 NamedDecl *ND = Corrected.getCorrectionDecl(); 8178 8179 // We reject candidates where DroppedSpecifier == true, hence the 8180 // literal '0' below. 8181 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8182 << NameInfo.getName() << LookupContext << 0 8183 << SS.getRange()); 8184 8185 // If we corrected to an inheriting constructor, handle it as one. 8186 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8187 if (RD && RD->isInjectedClassName()) { 8188 // Fix up the information we'll use to build the using declaration. 8189 if (Corrected.WillReplaceSpecifier()) { 8190 NestedNameSpecifierLocBuilder Builder; 8191 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8192 QualifierLoc.getSourceRange()); 8193 QualifierLoc = Builder.getWithLocInContext(Context); 8194 } 8195 8196 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8197 Context.getCanonicalType(Context.getRecordType(RD)))); 8198 NameInfo.setNamedTypeInfo(nullptr); 8199 for (auto *Ctor : LookupConstructors(RD)) 8200 R.addDecl(Ctor); 8201 } else { 8202 // FIXME: Pick up all the declarations if we found an overloaded function. 8203 R.addDecl(ND); 8204 } 8205 } else { 8206 Diag(IdentLoc, diag::err_no_member) 8207 << NameInfo.getName() << LookupContext << SS.getRange(); 8208 return BuildInvalid(); 8209 } 8210 } 8211 8212 if (R.isAmbiguous()) 8213 return BuildInvalid(); 8214 8215 if (HasTypenameKeyword) { 8216 // If we asked for a typename and got a non-type decl, error out. 8217 if (!R.getAsSingle<TypeDecl>()) { 8218 Diag(IdentLoc, diag::err_using_typename_non_type); 8219 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8220 Diag((*I)->getUnderlyingDecl()->getLocation(), 8221 diag::note_using_decl_target); 8222 return BuildInvalid(); 8223 } 8224 } else { 8225 // If we asked for a non-typename and we got a type, error out, 8226 // but only if this is an instantiation of an unresolved using 8227 // decl. Otherwise just silently find the type name. 8228 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8229 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8230 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8231 return BuildInvalid(); 8232 } 8233 } 8234 8235 // C++0x N2914 [namespace.udecl]p6: 8236 // A using-declaration shall not name a namespace. 8237 if (R.getAsSingle<NamespaceDecl>()) { 8238 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8239 << SS.getRange(); 8240 return BuildInvalid(); 8241 } 8242 8243 UsingDecl *UD = BuildValid(); 8244 8245 // The normal rules do not apply to inheriting constructor declarations. 8246 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8247 // Suppress access diagnostics; the access check is instead performed at the 8248 // point of use for an inheriting constructor. 8249 R.suppressDiagnostics(); 8250 CheckInheritingConstructorUsingDecl(UD); 8251 return UD; 8252 } 8253 8254 // Otherwise, look up the target name. 8255 8256 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8257 UsingShadowDecl *PrevDecl = nullptr; 8258 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8259 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8260 } 8261 8262 return UD; 8263 } 8264 8265 /// Additional checks for a using declaration referring to a constructor name. 8266 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8267 assert(!UD->hasTypename() && "expecting a constructor name"); 8268 8269 const Type *SourceType = UD->getQualifier()->getAsType(); 8270 assert(SourceType && 8271 "Using decl naming constructor doesn't have type in scope spec."); 8272 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8273 8274 // Check whether the named type is a direct base class. 8275 bool AnyDependentBases = false; 8276 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8277 AnyDependentBases); 8278 if (!Base && !AnyDependentBases) { 8279 Diag(UD->getUsingLoc(), 8280 diag::err_using_decl_constructor_not_in_direct_base) 8281 << UD->getNameInfo().getSourceRange() 8282 << QualType(SourceType, 0) << TargetClass; 8283 UD->setInvalidDecl(); 8284 return true; 8285 } 8286 8287 if (Base) 8288 Base->setInheritConstructors(); 8289 8290 return false; 8291 } 8292 8293 /// Checks that the given using declaration is not an invalid 8294 /// redeclaration. Note that this is checking only for the using decl 8295 /// itself, not for any ill-formedness among the UsingShadowDecls. 8296 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8297 bool HasTypenameKeyword, 8298 const CXXScopeSpec &SS, 8299 SourceLocation NameLoc, 8300 const LookupResult &Prev) { 8301 // C++03 [namespace.udecl]p8: 8302 // C++0x [namespace.udecl]p10: 8303 // A using-declaration is a declaration and can therefore be used 8304 // repeatedly where (and only where) multiple declarations are 8305 // allowed. 8306 // 8307 // That's in non-member contexts. 8308 if (!CurContext->getRedeclContext()->isRecord()) 8309 return false; 8310 8311 NestedNameSpecifier *Qual = SS.getScopeRep(); 8312 8313 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8314 NamedDecl *D = *I; 8315 8316 bool DTypename; 8317 NestedNameSpecifier *DQual; 8318 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8319 DTypename = UD->hasTypename(); 8320 DQual = UD->getQualifier(); 8321 } else if (UnresolvedUsingValueDecl *UD 8322 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8323 DTypename = false; 8324 DQual = UD->getQualifier(); 8325 } else if (UnresolvedUsingTypenameDecl *UD 8326 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8327 DTypename = true; 8328 DQual = UD->getQualifier(); 8329 } else continue; 8330 8331 // using decls differ if one says 'typename' and the other doesn't. 8332 // FIXME: non-dependent using decls? 8333 if (HasTypenameKeyword != DTypename) continue; 8334 8335 // using decls differ if they name different scopes (but note that 8336 // template instantiation can cause this check to trigger when it 8337 // didn't before instantiation). 8338 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8339 Context.getCanonicalNestedNameSpecifier(DQual)) 8340 continue; 8341 8342 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8343 Diag(D->getLocation(), diag::note_using_decl) << 1; 8344 return true; 8345 } 8346 8347 return false; 8348 } 8349 8350 8351 /// Checks that the given nested-name qualifier used in a using decl 8352 /// in the current context is appropriately related to the current 8353 /// scope. If an error is found, diagnoses it and returns true. 8354 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8355 const CXXScopeSpec &SS, 8356 const DeclarationNameInfo &NameInfo, 8357 SourceLocation NameLoc) { 8358 DeclContext *NamedContext = computeDeclContext(SS); 8359 8360 if (!CurContext->isRecord()) { 8361 // C++03 [namespace.udecl]p3: 8362 // C++0x [namespace.udecl]p8: 8363 // A using-declaration for a class member shall be a member-declaration. 8364 8365 // If we weren't able to compute a valid scope, it must be a 8366 // dependent class scope. 8367 if (!NamedContext || NamedContext->isRecord()) { 8368 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8369 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8370 RD = nullptr; 8371 8372 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8373 << SS.getRange(); 8374 8375 // If we have a complete, non-dependent source type, try to suggest a 8376 // way to get the same effect. 8377 if (!RD) 8378 return true; 8379 8380 // Find what this using-declaration was referring to. 8381 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8382 R.setHideTags(false); 8383 R.suppressDiagnostics(); 8384 LookupQualifiedName(R, RD); 8385 8386 if (R.getAsSingle<TypeDecl>()) { 8387 if (getLangOpts().CPlusPlus11) { 8388 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8389 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8390 << 0 // alias declaration 8391 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8392 NameInfo.getName().getAsString() + 8393 " = "); 8394 } else { 8395 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8396 SourceLocation InsertLoc = 8397 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8398 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8399 << 1 // typedef declaration 8400 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8401 << FixItHint::CreateInsertion( 8402 InsertLoc, " " + NameInfo.getName().getAsString()); 8403 } 8404 } else if (R.getAsSingle<VarDecl>()) { 8405 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8406 // repeating the type of the static data member here. 8407 FixItHint FixIt; 8408 if (getLangOpts().CPlusPlus11) { 8409 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8410 FixIt = FixItHint::CreateReplacement( 8411 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8412 } 8413 8414 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8415 << 2 // reference declaration 8416 << FixIt; 8417 } 8418 return true; 8419 } 8420 8421 // Otherwise, everything is known to be fine. 8422 return false; 8423 } 8424 8425 // The current scope is a record. 8426 8427 // If the named context is dependent, we can't decide much. 8428 if (!NamedContext) { 8429 // FIXME: in C++0x, we can diagnose if we can prove that the 8430 // nested-name-specifier does not refer to a base class, which is 8431 // still possible in some cases. 8432 8433 // Otherwise we have to conservatively report that things might be 8434 // okay. 8435 return false; 8436 } 8437 8438 if (!NamedContext->isRecord()) { 8439 // Ideally this would point at the last name in the specifier, 8440 // but we don't have that level of source info. 8441 Diag(SS.getRange().getBegin(), 8442 diag::err_using_decl_nested_name_specifier_is_not_class) 8443 << SS.getScopeRep() << SS.getRange(); 8444 return true; 8445 } 8446 8447 if (!NamedContext->isDependentContext() && 8448 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8449 return true; 8450 8451 if (getLangOpts().CPlusPlus11) { 8452 // C++0x [namespace.udecl]p3: 8453 // In a using-declaration used as a member-declaration, the 8454 // nested-name-specifier shall name a base class of the class 8455 // being defined. 8456 8457 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8458 cast<CXXRecordDecl>(NamedContext))) { 8459 if (CurContext == NamedContext) { 8460 Diag(NameLoc, 8461 diag::err_using_decl_nested_name_specifier_is_current_class) 8462 << SS.getRange(); 8463 return true; 8464 } 8465 8466 Diag(SS.getRange().getBegin(), 8467 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8468 << SS.getScopeRep() 8469 << cast<CXXRecordDecl>(CurContext) 8470 << SS.getRange(); 8471 return true; 8472 } 8473 8474 return false; 8475 } 8476 8477 // C++03 [namespace.udecl]p4: 8478 // A using-declaration used as a member-declaration shall refer 8479 // to a member of a base class of the class being defined [etc.]. 8480 8481 // Salient point: SS doesn't have to name a base class as long as 8482 // lookup only finds members from base classes. Therefore we can 8483 // diagnose here only if we can prove that that can't happen, 8484 // i.e. if the class hierarchies provably don't intersect. 8485 8486 // TODO: it would be nice if "definitely valid" results were cached 8487 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8488 // need to be repeated. 8489 8490 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 8491 auto Collect = [&Bases](const CXXRecordDecl *Base) { 8492 Bases.insert(Base); 8493 return true; 8494 }; 8495 8496 // Collect all bases. Return false if we find a dependent base. 8497 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 8498 return false; 8499 8500 // Returns true if the base is dependent or is one of the accumulated base 8501 // classes. 8502 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 8503 return !Bases.count(Base); 8504 }; 8505 8506 // Return false if the class has a dependent base or if it or one 8507 // of its bases is present in the base set of the current context. 8508 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 8509 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 8510 return false; 8511 8512 Diag(SS.getRange().getBegin(), 8513 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8514 << SS.getScopeRep() 8515 << cast<CXXRecordDecl>(CurContext) 8516 << SS.getRange(); 8517 8518 return true; 8519 } 8520 8521 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8522 AccessSpecifier AS, 8523 MultiTemplateParamsArg TemplateParamLists, 8524 SourceLocation UsingLoc, 8525 UnqualifiedId &Name, 8526 AttributeList *AttrList, 8527 TypeResult Type, 8528 Decl *DeclFromDeclSpec) { 8529 // Skip up to the relevant declaration scope. 8530 while (S->getFlags() & Scope::TemplateParamScope) 8531 S = S->getParent(); 8532 assert((S->getFlags() & Scope::DeclScope) && 8533 "got alias-declaration outside of declaration scope"); 8534 8535 if (Type.isInvalid()) 8536 return nullptr; 8537 8538 bool Invalid = false; 8539 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8540 TypeSourceInfo *TInfo = nullptr; 8541 GetTypeFromParser(Type.get(), &TInfo); 8542 8543 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8544 return nullptr; 8545 8546 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8547 UPPC_DeclarationType)) { 8548 Invalid = true; 8549 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8550 TInfo->getTypeLoc().getBeginLoc()); 8551 } 8552 8553 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8554 LookupName(Previous, S); 8555 8556 // Warn about shadowing the name of a template parameter. 8557 if (Previous.isSingleResult() && 8558 Previous.getFoundDecl()->isTemplateParameter()) { 8559 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8560 Previous.clear(); 8561 } 8562 8563 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8564 "name in alias declaration must be an identifier"); 8565 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8566 Name.StartLocation, 8567 Name.Identifier, TInfo); 8568 8569 NewTD->setAccess(AS); 8570 8571 if (Invalid) 8572 NewTD->setInvalidDecl(); 8573 8574 ProcessDeclAttributeList(S, NewTD, AttrList); 8575 8576 CheckTypedefForVariablyModifiedType(S, NewTD); 8577 Invalid |= NewTD->isInvalidDecl(); 8578 8579 bool Redeclaration = false; 8580 8581 NamedDecl *NewND; 8582 if (TemplateParamLists.size()) { 8583 TypeAliasTemplateDecl *OldDecl = nullptr; 8584 TemplateParameterList *OldTemplateParams = nullptr; 8585 8586 if (TemplateParamLists.size() != 1) { 8587 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8588 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8589 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8590 } 8591 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8592 8593 // Only consider previous declarations in the same scope. 8594 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8595 /*ExplicitInstantiationOrSpecialization*/false); 8596 if (!Previous.empty()) { 8597 Redeclaration = true; 8598 8599 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8600 if (!OldDecl && !Invalid) { 8601 Diag(UsingLoc, diag::err_redefinition_different_kind) 8602 << Name.Identifier; 8603 8604 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8605 if (OldD->getLocation().isValid()) 8606 Diag(OldD->getLocation(), diag::note_previous_definition); 8607 8608 Invalid = true; 8609 } 8610 8611 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8612 if (TemplateParameterListsAreEqual(TemplateParams, 8613 OldDecl->getTemplateParameters(), 8614 /*Complain=*/true, 8615 TPL_TemplateMatch)) 8616 OldTemplateParams = OldDecl->getTemplateParameters(); 8617 else 8618 Invalid = true; 8619 8620 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8621 if (!Invalid && 8622 !Context.hasSameType(OldTD->getUnderlyingType(), 8623 NewTD->getUnderlyingType())) { 8624 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8625 // but we can't reasonably accept it. 8626 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8627 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8628 if (OldTD->getLocation().isValid()) 8629 Diag(OldTD->getLocation(), diag::note_previous_definition); 8630 Invalid = true; 8631 } 8632 } 8633 } 8634 8635 // Merge any previous default template arguments into our parameters, 8636 // and check the parameter list. 8637 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8638 TPC_TypeAliasTemplate)) 8639 return nullptr; 8640 8641 TypeAliasTemplateDecl *NewDecl = 8642 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8643 Name.Identifier, TemplateParams, 8644 NewTD); 8645 NewTD->setDescribedAliasTemplate(NewDecl); 8646 8647 NewDecl->setAccess(AS); 8648 8649 if (Invalid) 8650 NewDecl->setInvalidDecl(); 8651 else if (OldDecl) 8652 NewDecl->setPreviousDecl(OldDecl); 8653 8654 NewND = NewDecl; 8655 } else { 8656 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 8657 setTagNameForLinkagePurposes(TD, NewTD); 8658 handleTagNumbering(TD, S); 8659 } 8660 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8661 NewND = NewTD; 8662 } 8663 8664 if (!Redeclaration) 8665 PushOnScopeChains(NewND, S); 8666 8667 ActOnDocumentableDecl(NewND); 8668 return NewND; 8669 } 8670 8671 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8672 SourceLocation AliasLoc, 8673 IdentifierInfo *Alias, CXXScopeSpec &SS, 8674 SourceLocation IdentLoc, 8675 IdentifierInfo *Ident) { 8676 8677 // Lookup the namespace name. 8678 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8679 LookupParsedName(R, S, &SS); 8680 8681 if (R.isAmbiguous()) 8682 return nullptr; 8683 8684 if (R.empty()) { 8685 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8686 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8687 return nullptr; 8688 } 8689 } 8690 assert(!R.isAmbiguous() && !R.empty()); 8691 8692 // Check if we have a previous declaration with the same name. 8693 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8694 ForRedeclaration); 8695 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8696 PrevDecl = nullptr; 8697 8698 NamedDecl *ND = R.getFoundDecl(); 8699 8700 if (PrevDecl) { 8701 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8702 // We already have an alias with the same name that points to the same 8703 // namespace; check that it matches. 8704 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8705 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8706 << Alias; 8707 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8708 << AD->getNamespace(); 8709 return nullptr; 8710 } 8711 } else { 8712 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8713 ? diag::err_redefinition 8714 : diag::err_redefinition_different_kind; 8715 Diag(AliasLoc, DiagID) << Alias; 8716 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8717 return nullptr; 8718 } 8719 } 8720 8721 // The use of a nested name specifier may trigger deprecation warnings. 8722 DiagnoseUseOfDecl(ND, IdentLoc); 8723 8724 NamespaceAliasDecl *AliasDecl = 8725 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8726 Alias, SS.getWithLocInContext(Context), 8727 IdentLoc, ND); 8728 if (PrevDecl) 8729 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8730 8731 PushOnScopeChains(AliasDecl, S); 8732 return AliasDecl; 8733 } 8734 8735 Sema::ImplicitExceptionSpecification 8736 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8737 CXXMethodDecl *MD) { 8738 CXXRecordDecl *ClassDecl = MD->getParent(); 8739 8740 // C++ [except.spec]p14: 8741 // An implicitly declared special member function (Clause 12) shall have an 8742 // exception-specification. [...] 8743 ImplicitExceptionSpecification ExceptSpec(*this); 8744 if (ClassDecl->isInvalidDecl()) 8745 return ExceptSpec; 8746 8747 // Direct base-class constructors. 8748 for (const auto &B : ClassDecl->bases()) { 8749 if (B.isVirtual()) // Handled below. 8750 continue; 8751 8752 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8753 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8754 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8755 // If this is a deleted function, add it anyway. This might be conformant 8756 // with the standard. This might not. I'm not sure. It might not matter. 8757 if (Constructor) 8758 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8759 } 8760 } 8761 8762 // Virtual base-class constructors. 8763 for (const auto &B : ClassDecl->vbases()) { 8764 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8765 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8766 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8767 // If this is a deleted function, add it anyway. This might be conformant 8768 // with the standard. This might not. I'm not sure. It might not matter. 8769 if (Constructor) 8770 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8771 } 8772 } 8773 8774 // Field constructors. 8775 for (const auto *F : ClassDecl->fields()) { 8776 if (F->hasInClassInitializer()) { 8777 if (Expr *E = F->getInClassInitializer()) 8778 ExceptSpec.CalledExpr(E); 8779 } else if (const RecordType *RecordTy 8780 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8781 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8782 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8783 // If this is a deleted function, add it anyway. This might be conformant 8784 // with the standard. This might not. I'm not sure. It might not matter. 8785 // In particular, the problem is that this function never gets called. It 8786 // might just be ill-formed because this function attempts to refer to 8787 // a deleted function here. 8788 if (Constructor) 8789 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8790 } 8791 } 8792 8793 return ExceptSpec; 8794 } 8795 8796 Sema::ImplicitExceptionSpecification 8797 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8798 CXXRecordDecl *ClassDecl = CD->getParent(); 8799 8800 // C++ [except.spec]p14: 8801 // An inheriting constructor [...] shall have an exception-specification. [...] 8802 ImplicitExceptionSpecification ExceptSpec(*this); 8803 if (ClassDecl->isInvalidDecl()) 8804 return ExceptSpec; 8805 8806 // Inherited constructor. 8807 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8808 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8809 // FIXME: Copying or moving the parameters could add extra exceptions to the 8810 // set, as could the default arguments for the inherited constructor. This 8811 // will be addressed when we implement the resolution of core issue 1351. 8812 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8813 8814 // Direct base-class constructors. 8815 for (const auto &B : ClassDecl->bases()) { 8816 if (B.isVirtual()) // Handled below. 8817 continue; 8818 8819 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8820 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8821 if (BaseClassDecl == InheritedDecl) 8822 continue; 8823 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8824 if (Constructor) 8825 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8826 } 8827 } 8828 8829 // Virtual base-class constructors. 8830 for (const auto &B : ClassDecl->vbases()) { 8831 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8832 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8833 if (BaseClassDecl == InheritedDecl) 8834 continue; 8835 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8836 if (Constructor) 8837 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8838 } 8839 } 8840 8841 // Field constructors. 8842 for (const auto *F : ClassDecl->fields()) { 8843 if (F->hasInClassInitializer()) { 8844 if (Expr *E = F->getInClassInitializer()) 8845 ExceptSpec.CalledExpr(E); 8846 } else if (const RecordType *RecordTy 8847 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8848 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8849 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8850 if (Constructor) 8851 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8852 } 8853 } 8854 8855 return ExceptSpec; 8856 } 8857 8858 namespace { 8859 /// RAII object to register a special member as being currently declared. 8860 struct DeclaringSpecialMember { 8861 Sema &S; 8862 Sema::SpecialMemberDecl D; 8863 bool WasAlreadyBeingDeclared; 8864 8865 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8866 : S(S), D(RD, CSM) { 8867 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8868 if (WasAlreadyBeingDeclared) 8869 // This almost never happens, but if it does, ensure that our cache 8870 // doesn't contain a stale result. 8871 S.SpecialMemberCache.clear(); 8872 8873 // FIXME: Register a note to be produced if we encounter an error while 8874 // declaring the special member. 8875 } 8876 ~DeclaringSpecialMember() { 8877 if (!WasAlreadyBeingDeclared) 8878 S.SpecialMembersBeingDeclared.erase(D); 8879 } 8880 8881 /// \brief Are we already trying to declare this special member? 8882 bool isAlreadyBeingDeclared() const { 8883 return WasAlreadyBeingDeclared; 8884 } 8885 }; 8886 } 8887 8888 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8889 CXXRecordDecl *ClassDecl) { 8890 // C++ [class.ctor]p5: 8891 // A default constructor for a class X is a constructor of class X 8892 // that can be called without an argument. If there is no 8893 // user-declared constructor for class X, a default constructor is 8894 // implicitly declared. An implicitly-declared default constructor 8895 // is an inline public member of its class. 8896 assert(ClassDecl->needsImplicitDefaultConstructor() && 8897 "Should not build implicit default constructor!"); 8898 8899 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8900 if (DSM.isAlreadyBeingDeclared()) 8901 return nullptr; 8902 8903 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8904 CXXDefaultConstructor, 8905 false); 8906 8907 // Create the actual constructor declaration. 8908 CanQualType ClassType 8909 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8910 SourceLocation ClassLoc = ClassDecl->getLocation(); 8911 DeclarationName Name 8912 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8913 DeclarationNameInfo NameInfo(Name, ClassLoc); 8914 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8915 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8916 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8917 /*isImplicitlyDeclared=*/true, Constexpr); 8918 DefaultCon->setAccess(AS_public); 8919 DefaultCon->setDefaulted(); 8920 8921 if (getLangOpts().CUDA) { 8922 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8923 DefaultCon, 8924 /* ConstRHS */ false, 8925 /* Diagnose */ false); 8926 } 8927 8928 // Build an exception specification pointing back at this constructor. 8929 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8930 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8931 8932 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8933 // constructors is easy to compute. 8934 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8935 8936 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8937 SetDeclDeleted(DefaultCon, ClassLoc); 8938 8939 // Note that we have declared this constructor. 8940 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8941 8942 if (Scope *S = getScopeForContext(ClassDecl)) 8943 PushOnScopeChains(DefaultCon, S, false); 8944 ClassDecl->addDecl(DefaultCon); 8945 8946 return DefaultCon; 8947 } 8948 8949 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8950 CXXConstructorDecl *Constructor) { 8951 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8952 !Constructor->doesThisDeclarationHaveABody() && 8953 !Constructor->isDeleted()) && 8954 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8955 8956 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8957 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8958 8959 SynthesizedFunctionScope Scope(*this, Constructor); 8960 DiagnosticErrorTrap Trap(Diags); 8961 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8962 Trap.hasErrorOccurred()) { 8963 Diag(CurrentLocation, diag::note_member_synthesized_at) 8964 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8965 Constructor->setInvalidDecl(); 8966 return; 8967 } 8968 8969 // The exception specification is needed because we are defining the 8970 // function. 8971 ResolveExceptionSpec(CurrentLocation, 8972 Constructor->getType()->castAs<FunctionProtoType>()); 8973 8974 SourceLocation Loc = Constructor->getLocEnd().isValid() 8975 ? Constructor->getLocEnd() 8976 : Constructor->getLocation(); 8977 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8978 8979 Constructor->markUsed(Context); 8980 MarkVTableUsed(CurrentLocation, ClassDecl); 8981 8982 if (ASTMutationListener *L = getASTMutationListener()) { 8983 L->CompletedImplicitDefinition(Constructor); 8984 } 8985 8986 DiagnoseUninitializedFields(*this, Constructor); 8987 } 8988 8989 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8990 // Perform any delayed checks on exception specifications. 8991 CheckDelayedMemberExceptionSpecs(); 8992 } 8993 8994 namespace { 8995 /// Information on inheriting constructors to declare. 8996 class InheritingConstructorInfo { 8997 public: 8998 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8999 : SemaRef(SemaRef), Derived(Derived) { 9000 // Mark the constructors that we already have in the derived class. 9001 // 9002 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 9003 // unless there is a user-declared constructor with the same signature in 9004 // the class where the using-declaration appears. 9005 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 9006 } 9007 9008 void inheritAll(CXXRecordDecl *RD) { 9009 visitAll(RD, &InheritingConstructorInfo::inherit); 9010 } 9011 9012 private: 9013 /// Information about an inheriting constructor. 9014 struct InheritingConstructor { 9015 InheritingConstructor() 9016 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 9017 9018 /// If \c true, a constructor with this signature is already declared 9019 /// in the derived class. 9020 bool DeclaredInDerived; 9021 9022 /// The constructor which is inherited. 9023 const CXXConstructorDecl *BaseCtor; 9024 9025 /// The derived constructor we declared. 9026 CXXConstructorDecl *DerivedCtor; 9027 }; 9028 9029 /// Inheriting constructors with a given canonical type. There can be at 9030 /// most one such non-template constructor, and any number of templated 9031 /// constructors. 9032 struct InheritingConstructorsForType { 9033 InheritingConstructor NonTemplate; 9034 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 9035 Templates; 9036 9037 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 9038 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 9039 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 9040 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 9041 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 9042 false, S.TPL_TemplateMatch)) 9043 return Templates[I].second; 9044 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 9045 return Templates.back().second; 9046 } 9047 9048 return NonTemplate; 9049 } 9050 }; 9051 9052 /// Get or create the inheriting constructor record for a constructor. 9053 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 9054 QualType CtorType) { 9055 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 9056 .getEntry(SemaRef, Ctor); 9057 } 9058 9059 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 9060 9061 /// Process all constructors for a class. 9062 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 9063 for (const auto *Ctor : RD->ctors()) 9064 (this->*Callback)(Ctor); 9065 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9066 I(RD->decls_begin()), E(RD->decls_end()); 9067 I != E; ++I) { 9068 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 9069 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 9070 (this->*Callback)(CD); 9071 } 9072 } 9073 9074 /// Note that a constructor (or constructor template) was declared in Derived. 9075 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 9076 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 9077 } 9078 9079 /// Inherit a single constructor. 9080 void inherit(const CXXConstructorDecl *Ctor) { 9081 const FunctionProtoType *CtorType = 9082 Ctor->getType()->castAs<FunctionProtoType>(); 9083 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 9084 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 9085 9086 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 9087 9088 // Core issue (no number yet): the ellipsis is always discarded. 9089 if (EPI.Variadic) { 9090 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 9091 SemaRef.Diag(Ctor->getLocation(), 9092 diag::note_using_decl_constructor_ellipsis); 9093 EPI.Variadic = false; 9094 } 9095 9096 // Declare a constructor for each number of parameters. 9097 // 9098 // C++11 [class.inhctor]p1: 9099 // The candidate set of inherited constructors from the class X named in 9100 // the using-declaration consists of [... modulo defects ...] for each 9101 // constructor or constructor template of X, the set of constructors or 9102 // constructor templates that results from omitting any ellipsis parameter 9103 // specification and successively omitting parameters with a default 9104 // argument from the end of the parameter-type-list 9105 unsigned MinParams = minParamsToInherit(Ctor); 9106 unsigned Params = Ctor->getNumParams(); 9107 if (Params >= MinParams) { 9108 do 9109 declareCtor(UsingLoc, Ctor, 9110 SemaRef.Context.getFunctionType( 9111 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 9112 while (Params > MinParams && 9113 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9114 } 9115 } 9116 9117 /// Find the using-declaration which specified that we should inherit the 9118 /// constructors of \p Base. 9119 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9120 // No fancy lookup required; just look for the base constructor name 9121 // directly within the derived class. 9122 ASTContext &Context = SemaRef.Context; 9123 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9124 Context.getCanonicalType(Context.getRecordType(Base))); 9125 DeclContext::lookup_result Decls = Derived->lookup(Name); 9126 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9127 } 9128 9129 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9130 // C++11 [class.inhctor]p3: 9131 // [F]or each constructor template in the candidate set of inherited 9132 // constructors, a constructor template is implicitly declared 9133 if (Ctor->getDescribedFunctionTemplate()) 9134 return 0; 9135 9136 // For each non-template constructor in the candidate set of inherited 9137 // constructors other than a constructor having no parameters or a 9138 // copy/move constructor having a single parameter, a constructor is 9139 // implicitly declared [...] 9140 if (Ctor->getNumParams() == 0) 9141 return 1; 9142 if (Ctor->isCopyOrMoveConstructor()) 9143 return 2; 9144 9145 // Per discussion on core reflector, never inherit a constructor which 9146 // would become a default, copy, or move constructor of Derived either. 9147 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9148 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9149 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9150 } 9151 9152 /// Declare a single inheriting constructor, inheriting the specified 9153 /// constructor, with the given type. 9154 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9155 QualType DerivedType) { 9156 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9157 9158 // C++11 [class.inhctor]p3: 9159 // ... a constructor is implicitly declared with the same constructor 9160 // characteristics unless there is a user-declared constructor with 9161 // the same signature in the class where the using-declaration appears 9162 if (Entry.DeclaredInDerived) 9163 return; 9164 9165 // C++11 [class.inhctor]p7: 9166 // If two using-declarations declare inheriting constructors with the 9167 // same signature, the program is ill-formed 9168 if (Entry.DerivedCtor) { 9169 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9170 // Only diagnose this once per constructor. 9171 if (Entry.DerivedCtor->isInvalidDecl()) 9172 return; 9173 Entry.DerivedCtor->setInvalidDecl(); 9174 9175 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9176 SemaRef.Diag(BaseCtor->getLocation(), 9177 diag::note_using_decl_constructor_conflict_current_ctor); 9178 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9179 diag::note_using_decl_constructor_conflict_previous_ctor); 9180 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9181 diag::note_using_decl_constructor_conflict_previous_using); 9182 } else { 9183 // Core issue (no number): if the same inheriting constructor is 9184 // produced by multiple base class constructors from the same base 9185 // class, the inheriting constructor is defined as deleted. 9186 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9187 } 9188 9189 return; 9190 } 9191 9192 ASTContext &Context = SemaRef.Context; 9193 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9194 Context.getCanonicalType(Context.getRecordType(Derived))); 9195 DeclarationNameInfo NameInfo(Name, UsingLoc); 9196 9197 TemplateParameterList *TemplateParams = nullptr; 9198 if (const FunctionTemplateDecl *FTD = 9199 BaseCtor->getDescribedFunctionTemplate()) { 9200 TemplateParams = FTD->getTemplateParameters(); 9201 // We're reusing template parameters from a different DeclContext. This 9202 // is questionable at best, but works out because the template depth in 9203 // both places is guaranteed to be 0. 9204 // FIXME: Rebuild the template parameters in the new context, and 9205 // transform the function type to refer to them. 9206 } 9207 9208 // Build type source info pointing at the using-declaration. This is 9209 // required by template instantiation. 9210 TypeSourceInfo *TInfo = 9211 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9212 FunctionProtoTypeLoc ProtoLoc = 9213 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9214 9215 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9216 Context, Derived, UsingLoc, NameInfo, DerivedType, 9217 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9218 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9219 9220 // Build an unevaluated exception specification for this constructor. 9221 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9222 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9223 EPI.ExceptionSpec.Type = EST_Unevaluated; 9224 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9225 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9226 FPT->getParamTypes(), EPI)); 9227 9228 // Build the parameter declarations. 9229 SmallVector<ParmVarDecl *, 16> ParamDecls; 9230 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9231 TypeSourceInfo *TInfo = 9232 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9233 ParmVarDecl *PD = ParmVarDecl::Create( 9234 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9235 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9236 PD->setScopeInfo(0, I); 9237 PD->setImplicit(); 9238 ParamDecls.push_back(PD); 9239 ProtoLoc.setParam(I, PD); 9240 } 9241 9242 // Set up the new constructor. 9243 DerivedCtor->setAccess(BaseCtor->getAccess()); 9244 DerivedCtor->setParams(ParamDecls); 9245 DerivedCtor->setInheritedConstructor(BaseCtor); 9246 if (BaseCtor->isDeleted()) 9247 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9248 9249 // If this is a constructor template, build the template declaration. 9250 if (TemplateParams) { 9251 FunctionTemplateDecl *DerivedTemplate = 9252 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9253 TemplateParams, DerivedCtor); 9254 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9255 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9256 Derived->addDecl(DerivedTemplate); 9257 } else { 9258 Derived->addDecl(DerivedCtor); 9259 } 9260 9261 Entry.BaseCtor = BaseCtor; 9262 Entry.DerivedCtor = DerivedCtor; 9263 } 9264 9265 Sema &SemaRef; 9266 CXXRecordDecl *Derived; 9267 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9268 MapType Map; 9269 }; 9270 } 9271 9272 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9273 // Defer declaring the inheriting constructors until the class is 9274 // instantiated. 9275 if (ClassDecl->isDependentContext()) 9276 return; 9277 9278 // Find base classes from which we might inherit constructors. 9279 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9280 for (const auto &BaseIt : ClassDecl->bases()) 9281 if (BaseIt.getInheritConstructors()) 9282 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9283 9284 // Go no further if we're not inheriting any constructors. 9285 if (InheritedBases.empty()) 9286 return; 9287 9288 // Declare the inherited constructors. 9289 InheritingConstructorInfo ICI(*this, ClassDecl); 9290 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9291 ICI.inheritAll(InheritedBases[I]); 9292 } 9293 9294 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9295 CXXConstructorDecl *Constructor) { 9296 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9297 assert(Constructor->getInheritedConstructor() && 9298 !Constructor->doesThisDeclarationHaveABody() && 9299 !Constructor->isDeleted()); 9300 9301 SynthesizedFunctionScope Scope(*this, Constructor); 9302 DiagnosticErrorTrap Trap(Diags); 9303 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9304 Trap.hasErrorOccurred()) { 9305 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9306 << Context.getTagDeclType(ClassDecl); 9307 Constructor->setInvalidDecl(); 9308 return; 9309 } 9310 9311 SourceLocation Loc = Constructor->getLocation(); 9312 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9313 9314 Constructor->markUsed(Context); 9315 MarkVTableUsed(CurrentLocation, ClassDecl); 9316 9317 if (ASTMutationListener *L = getASTMutationListener()) { 9318 L->CompletedImplicitDefinition(Constructor); 9319 } 9320 } 9321 9322 9323 Sema::ImplicitExceptionSpecification 9324 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9325 CXXRecordDecl *ClassDecl = MD->getParent(); 9326 9327 // C++ [except.spec]p14: 9328 // An implicitly declared special member function (Clause 12) shall have 9329 // an exception-specification. 9330 ImplicitExceptionSpecification ExceptSpec(*this); 9331 if (ClassDecl->isInvalidDecl()) 9332 return ExceptSpec; 9333 9334 // Direct base-class destructors. 9335 for (const auto &B : ClassDecl->bases()) { 9336 if (B.isVirtual()) // Handled below. 9337 continue; 9338 9339 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9340 ExceptSpec.CalledDecl(B.getLocStart(), 9341 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9342 } 9343 9344 // Virtual base-class destructors. 9345 for (const auto &B : ClassDecl->vbases()) { 9346 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9347 ExceptSpec.CalledDecl(B.getLocStart(), 9348 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9349 } 9350 9351 // Field destructors. 9352 for (const auto *F : ClassDecl->fields()) { 9353 if (const RecordType *RecordTy 9354 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9355 ExceptSpec.CalledDecl(F->getLocation(), 9356 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9357 } 9358 9359 return ExceptSpec; 9360 } 9361 9362 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9363 // C++ [class.dtor]p2: 9364 // If a class has no user-declared destructor, a destructor is 9365 // declared implicitly. An implicitly-declared destructor is an 9366 // inline public member of its class. 9367 assert(ClassDecl->needsImplicitDestructor()); 9368 9369 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9370 if (DSM.isAlreadyBeingDeclared()) 9371 return nullptr; 9372 9373 // Create the actual destructor declaration. 9374 CanQualType ClassType 9375 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9376 SourceLocation ClassLoc = ClassDecl->getLocation(); 9377 DeclarationName Name 9378 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9379 DeclarationNameInfo NameInfo(Name, ClassLoc); 9380 CXXDestructorDecl *Destructor 9381 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9382 QualType(), nullptr, /*isInline=*/true, 9383 /*isImplicitlyDeclared=*/true); 9384 Destructor->setAccess(AS_public); 9385 Destructor->setDefaulted(); 9386 9387 if (getLangOpts().CUDA) { 9388 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9389 Destructor, 9390 /* ConstRHS */ false, 9391 /* Diagnose */ false); 9392 } 9393 9394 // Build an exception specification pointing back at this destructor. 9395 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9396 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9397 9398 AddOverriddenMethods(ClassDecl, Destructor); 9399 9400 // We don't need to use SpecialMemberIsTrivial here; triviality for 9401 // destructors is easy to compute. 9402 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9403 9404 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9405 SetDeclDeleted(Destructor, ClassLoc); 9406 9407 // Note that we have declared this destructor. 9408 ++ASTContext::NumImplicitDestructorsDeclared; 9409 9410 // Introduce this destructor into its scope. 9411 if (Scope *S = getScopeForContext(ClassDecl)) 9412 PushOnScopeChains(Destructor, S, false); 9413 ClassDecl->addDecl(Destructor); 9414 9415 return Destructor; 9416 } 9417 9418 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9419 CXXDestructorDecl *Destructor) { 9420 assert((Destructor->isDefaulted() && 9421 !Destructor->doesThisDeclarationHaveABody() && 9422 !Destructor->isDeleted()) && 9423 "DefineImplicitDestructor - call it for implicit default dtor"); 9424 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9425 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9426 9427 if (Destructor->isInvalidDecl()) 9428 return; 9429 9430 SynthesizedFunctionScope Scope(*this, Destructor); 9431 9432 DiagnosticErrorTrap Trap(Diags); 9433 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9434 Destructor->getParent()); 9435 9436 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9437 Diag(CurrentLocation, diag::note_member_synthesized_at) 9438 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9439 9440 Destructor->setInvalidDecl(); 9441 return; 9442 } 9443 9444 // The exception specification is needed because we are defining the 9445 // function. 9446 ResolveExceptionSpec(CurrentLocation, 9447 Destructor->getType()->castAs<FunctionProtoType>()); 9448 9449 SourceLocation Loc = Destructor->getLocEnd().isValid() 9450 ? Destructor->getLocEnd() 9451 : Destructor->getLocation(); 9452 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9453 Destructor->markUsed(Context); 9454 MarkVTableUsed(CurrentLocation, ClassDecl); 9455 9456 if (ASTMutationListener *L = getASTMutationListener()) { 9457 L->CompletedImplicitDefinition(Destructor); 9458 } 9459 } 9460 9461 /// \brief Perform any semantic analysis which needs to be delayed until all 9462 /// pending class member declarations have been parsed. 9463 void Sema::ActOnFinishCXXMemberDecls() { 9464 // If the context is an invalid C++ class, just suppress these checks. 9465 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9466 if (Record->isInvalidDecl()) { 9467 DelayedDefaultedMemberExceptionSpecs.clear(); 9468 DelayedExceptionSpecChecks.clear(); 9469 return; 9470 } 9471 } 9472 } 9473 9474 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 9475 // Don't do anything for template patterns. 9476 if (Class->getDescribedClassTemplate()) 9477 return; 9478 9479 for (Decl *Member : Class->decls()) { 9480 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 9481 if (!CD) { 9482 // Recurse on nested classes. 9483 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 9484 getDefaultArgExprsForConstructors(S, NestedRD); 9485 continue; 9486 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 9487 continue; 9488 } 9489 9490 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) { 9491 // Skip any default arguments that we've already instantiated. 9492 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 9493 continue; 9494 9495 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 9496 CD->getParamDecl(I)).get(); 9497 S.DiscardCleanupsInEvaluationContext(); 9498 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 9499 } 9500 } 9501 } 9502 9503 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 9504 auto *RD = dyn_cast<CXXRecordDecl>(D); 9505 9506 // Default constructors that are annotated with __declspec(dllexport) which 9507 // have default arguments or don't use the standard calling convention are 9508 // wrapped with a thunk called the default constructor closure. 9509 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 9510 getDefaultArgExprsForConstructors(*this, RD); 9511 9512 if (!DelayedDllExportClasses.empty()) { 9513 // Calling ReferenceDllExportedMethods might cause the current function to 9514 // be called again, so use a local copy of DelayedDllExportClasses. 9515 SmallVector<CXXRecordDecl *, 4> WorkList; 9516 std::swap(DelayedDllExportClasses, WorkList); 9517 for (CXXRecordDecl *Class : WorkList) 9518 ReferenceDllExportedMethods(*this, Class); 9519 } 9520 } 9521 9522 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9523 CXXDestructorDecl *Destructor) { 9524 assert(getLangOpts().CPlusPlus11 && 9525 "adjusting dtor exception specs was introduced in c++11"); 9526 9527 // C++11 [class.dtor]p3: 9528 // A declaration of a destructor that does not have an exception- 9529 // specification is implicitly considered to have the same exception- 9530 // specification as an implicit declaration. 9531 const FunctionProtoType *DtorType = Destructor->getType()-> 9532 getAs<FunctionProtoType>(); 9533 if (DtorType->hasExceptionSpec()) 9534 return; 9535 9536 // Replace the destructor's type, building off the existing one. Fortunately, 9537 // the only thing of interest in the destructor type is its extended info. 9538 // The return and arguments are fixed. 9539 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9540 EPI.ExceptionSpec.Type = EST_Unevaluated; 9541 EPI.ExceptionSpec.SourceDecl = Destructor; 9542 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9543 9544 // FIXME: If the destructor has a body that could throw, and the newly created 9545 // spec doesn't allow exceptions, we should emit a warning, because this 9546 // change in behavior can break conforming C++03 programs at runtime. 9547 // However, we don't have a body or an exception specification yet, so it 9548 // needs to be done somewhere else. 9549 } 9550 9551 namespace { 9552 /// \brief An abstract base class for all helper classes used in building the 9553 // copy/move operators. These classes serve as factory functions and help us 9554 // avoid using the same Expr* in the AST twice. 9555 class ExprBuilder { 9556 ExprBuilder(const ExprBuilder&) = delete; 9557 ExprBuilder &operator=(const ExprBuilder&) = delete; 9558 9559 protected: 9560 static Expr *assertNotNull(Expr *E) { 9561 assert(E && "Expression construction must not fail."); 9562 return E; 9563 } 9564 9565 public: 9566 ExprBuilder() {} 9567 virtual ~ExprBuilder() {} 9568 9569 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9570 }; 9571 9572 class RefBuilder: public ExprBuilder { 9573 VarDecl *Var; 9574 QualType VarType; 9575 9576 public: 9577 Expr *build(Sema &S, SourceLocation Loc) const override { 9578 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9579 } 9580 9581 RefBuilder(VarDecl *Var, QualType VarType) 9582 : Var(Var), VarType(VarType) {} 9583 }; 9584 9585 class ThisBuilder: public ExprBuilder { 9586 public: 9587 Expr *build(Sema &S, SourceLocation Loc) const override { 9588 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9589 } 9590 }; 9591 9592 class CastBuilder: public ExprBuilder { 9593 const ExprBuilder &Builder; 9594 QualType Type; 9595 ExprValueKind Kind; 9596 const CXXCastPath &Path; 9597 9598 public: 9599 Expr *build(Sema &S, SourceLocation Loc) const override { 9600 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9601 CK_UncheckedDerivedToBase, Kind, 9602 &Path).get()); 9603 } 9604 9605 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9606 const CXXCastPath &Path) 9607 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9608 }; 9609 9610 class DerefBuilder: public ExprBuilder { 9611 const ExprBuilder &Builder; 9612 9613 public: 9614 Expr *build(Sema &S, SourceLocation Loc) const override { 9615 return assertNotNull( 9616 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9617 } 9618 9619 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9620 }; 9621 9622 class MemberBuilder: public ExprBuilder { 9623 const ExprBuilder &Builder; 9624 QualType Type; 9625 CXXScopeSpec SS; 9626 bool IsArrow; 9627 LookupResult &MemberLookup; 9628 9629 public: 9630 Expr *build(Sema &S, SourceLocation Loc) const override { 9631 return assertNotNull(S.BuildMemberReferenceExpr( 9632 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9633 nullptr, MemberLookup, nullptr, nullptr).get()); 9634 } 9635 9636 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9637 LookupResult &MemberLookup) 9638 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9639 MemberLookup(MemberLookup) {} 9640 }; 9641 9642 class MoveCastBuilder: public ExprBuilder { 9643 const ExprBuilder &Builder; 9644 9645 public: 9646 Expr *build(Sema &S, SourceLocation Loc) const override { 9647 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9648 } 9649 9650 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9651 }; 9652 9653 class LvalueConvBuilder: public ExprBuilder { 9654 const ExprBuilder &Builder; 9655 9656 public: 9657 Expr *build(Sema &S, SourceLocation Loc) const override { 9658 return assertNotNull( 9659 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9660 } 9661 9662 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9663 }; 9664 9665 class SubscriptBuilder: public ExprBuilder { 9666 const ExprBuilder &Base; 9667 const ExprBuilder &Index; 9668 9669 public: 9670 Expr *build(Sema &S, SourceLocation Loc) const override { 9671 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9672 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9673 } 9674 9675 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9676 : Base(Base), Index(Index) {} 9677 }; 9678 9679 } // end anonymous namespace 9680 9681 /// When generating a defaulted copy or move assignment operator, if a field 9682 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9683 /// do so. This optimization only applies for arrays of scalars, and for arrays 9684 /// of class type where the selected copy/move-assignment operator is trivial. 9685 static StmtResult 9686 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9687 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9688 // Compute the size of the memory buffer to be copied. 9689 QualType SizeType = S.Context.getSizeType(); 9690 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9691 S.Context.getTypeSizeInChars(T).getQuantity()); 9692 9693 // Take the address of the field references for "from" and "to". We 9694 // directly construct UnaryOperators here because semantic analysis 9695 // does not permit us to take the address of an xvalue. 9696 Expr *From = FromB.build(S, Loc); 9697 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9698 S.Context.getPointerType(From->getType()), 9699 VK_RValue, OK_Ordinary, Loc); 9700 Expr *To = ToB.build(S, Loc); 9701 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9702 S.Context.getPointerType(To->getType()), 9703 VK_RValue, OK_Ordinary, Loc); 9704 9705 const Type *E = T->getBaseElementTypeUnsafe(); 9706 bool NeedsCollectableMemCpy = 9707 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9708 9709 // Create a reference to the __builtin_objc_memmove_collectable function 9710 StringRef MemCpyName = NeedsCollectableMemCpy ? 9711 "__builtin_objc_memmove_collectable" : 9712 "__builtin_memcpy"; 9713 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9714 Sema::LookupOrdinaryName); 9715 S.LookupName(R, S.TUScope, true); 9716 9717 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9718 if (!MemCpy) 9719 // Something went horribly wrong earlier, and we will have complained 9720 // about it. 9721 return StmtError(); 9722 9723 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9724 VK_RValue, Loc, nullptr); 9725 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9726 9727 Expr *CallArgs[] = { 9728 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9729 }; 9730 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9731 Loc, CallArgs, Loc); 9732 9733 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9734 return Call.getAs<Stmt>(); 9735 } 9736 9737 /// \brief Builds a statement that copies/moves the given entity from \p From to 9738 /// \c To. 9739 /// 9740 /// This routine is used to copy/move the members of a class with an 9741 /// implicitly-declared copy/move assignment operator. When the entities being 9742 /// copied are arrays, this routine builds for loops to copy them. 9743 /// 9744 /// \param S The Sema object used for type-checking. 9745 /// 9746 /// \param Loc The location where the implicit copy/move is being generated. 9747 /// 9748 /// \param T The type of the expressions being copied/moved. Both expressions 9749 /// must have this type. 9750 /// 9751 /// \param To The expression we are copying/moving to. 9752 /// 9753 /// \param From The expression we are copying/moving from. 9754 /// 9755 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9756 /// Otherwise, it's a non-static member subobject. 9757 /// 9758 /// \param Copying Whether we're copying or moving. 9759 /// 9760 /// \param Depth Internal parameter recording the depth of the recursion. 9761 /// 9762 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9763 /// if a memcpy should be used instead. 9764 static StmtResult 9765 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9766 const ExprBuilder &To, const ExprBuilder &From, 9767 bool CopyingBaseSubobject, bool Copying, 9768 unsigned Depth = 0) { 9769 // C++11 [class.copy]p28: 9770 // Each subobject is assigned in the manner appropriate to its type: 9771 // 9772 // - if the subobject is of class type, as if by a call to operator= with 9773 // the subobject as the object expression and the corresponding 9774 // subobject of x as a single function argument (as if by explicit 9775 // qualification; that is, ignoring any possible virtual overriding 9776 // functions in more derived classes); 9777 // 9778 // C++03 [class.copy]p13: 9779 // - if the subobject is of class type, the copy assignment operator for 9780 // the class is used (as if by explicit qualification; that is, 9781 // ignoring any possible virtual overriding functions in more derived 9782 // classes); 9783 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9784 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9785 9786 // Look for operator=. 9787 DeclarationName Name 9788 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9789 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9790 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9791 9792 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9793 // operator. 9794 if (!S.getLangOpts().CPlusPlus11) { 9795 LookupResult::Filter F = OpLookup.makeFilter(); 9796 while (F.hasNext()) { 9797 NamedDecl *D = F.next(); 9798 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9799 if (Method->isCopyAssignmentOperator() || 9800 (!Copying && Method->isMoveAssignmentOperator())) 9801 continue; 9802 9803 F.erase(); 9804 } 9805 F.done(); 9806 } 9807 9808 // Suppress the protected check (C++ [class.protected]) for each of the 9809 // assignment operators we found. This strange dance is required when 9810 // we're assigning via a base classes's copy-assignment operator. To 9811 // ensure that we're getting the right base class subobject (without 9812 // ambiguities), we need to cast "this" to that subobject type; to 9813 // ensure that we don't go through the virtual call mechanism, we need 9814 // to qualify the operator= name with the base class (see below). However, 9815 // this means that if the base class has a protected copy assignment 9816 // operator, the protected member access check will fail. So, we 9817 // rewrite "protected" access to "public" access in this case, since we 9818 // know by construction that we're calling from a derived class. 9819 if (CopyingBaseSubobject) { 9820 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9821 L != LEnd; ++L) { 9822 if (L.getAccess() == AS_protected) 9823 L.setAccess(AS_public); 9824 } 9825 } 9826 9827 // Create the nested-name-specifier that will be used to qualify the 9828 // reference to operator=; this is required to suppress the virtual 9829 // call mechanism. 9830 CXXScopeSpec SS; 9831 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9832 SS.MakeTrivial(S.Context, 9833 NestedNameSpecifier::Create(S.Context, nullptr, false, 9834 CanonicalT), 9835 Loc); 9836 9837 // Create the reference to operator=. 9838 ExprResult OpEqualRef 9839 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9840 SS, /*TemplateKWLoc=*/SourceLocation(), 9841 /*FirstQualifierInScope=*/nullptr, 9842 OpLookup, 9843 /*TemplateArgs=*/nullptr, /*S*/nullptr, 9844 /*SuppressQualifierCheck=*/true); 9845 if (OpEqualRef.isInvalid()) 9846 return StmtError(); 9847 9848 // Build the call to the assignment operator. 9849 9850 Expr *FromInst = From.build(S, Loc); 9851 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9852 OpEqualRef.getAs<Expr>(), 9853 Loc, FromInst, Loc); 9854 if (Call.isInvalid()) 9855 return StmtError(); 9856 9857 // If we built a call to a trivial 'operator=' while copying an array, 9858 // bail out. We'll replace the whole shebang with a memcpy. 9859 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9860 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9861 return StmtResult((Stmt*)nullptr); 9862 9863 // Convert to an expression-statement, and clean up any produced 9864 // temporaries. 9865 return S.ActOnExprStmt(Call); 9866 } 9867 9868 // - if the subobject is of scalar type, the built-in assignment 9869 // operator is used. 9870 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9871 if (!ArrayTy) { 9872 ExprResult Assignment = S.CreateBuiltinBinOp( 9873 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9874 if (Assignment.isInvalid()) 9875 return StmtError(); 9876 return S.ActOnExprStmt(Assignment); 9877 } 9878 9879 // - if the subobject is an array, each element is assigned, in the 9880 // manner appropriate to the element type; 9881 9882 // Construct a loop over the array bounds, e.g., 9883 // 9884 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9885 // 9886 // that will copy each of the array elements. 9887 QualType SizeType = S.Context.getSizeType(); 9888 9889 // Create the iteration variable. 9890 IdentifierInfo *IterationVarName = nullptr; 9891 { 9892 SmallString<8> Str; 9893 llvm::raw_svector_ostream OS(Str); 9894 OS << "__i" << Depth; 9895 IterationVarName = &S.Context.Idents.get(OS.str()); 9896 } 9897 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9898 IterationVarName, SizeType, 9899 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9900 SC_None); 9901 9902 // Initialize the iteration variable to zero. 9903 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9904 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9905 9906 // Creates a reference to the iteration variable. 9907 RefBuilder IterationVarRef(IterationVar, SizeType); 9908 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9909 9910 // Create the DeclStmt that holds the iteration variable. 9911 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9912 9913 // Subscript the "from" and "to" expressions with the iteration variable. 9914 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9915 MoveCastBuilder FromIndexMove(FromIndexCopy); 9916 const ExprBuilder *FromIndex; 9917 if (Copying) 9918 FromIndex = &FromIndexCopy; 9919 else 9920 FromIndex = &FromIndexMove; 9921 9922 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9923 9924 // Build the copy/move for an individual element of the array. 9925 StmtResult Copy = 9926 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9927 ToIndex, *FromIndex, CopyingBaseSubobject, 9928 Copying, Depth + 1); 9929 // Bail out if copying fails or if we determined that we should use memcpy. 9930 if (Copy.isInvalid() || !Copy.get()) 9931 return Copy; 9932 9933 // Create the comparison against the array bound. 9934 llvm::APInt Upper 9935 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9936 Expr *Comparison 9937 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9938 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9939 BO_NE, S.Context.BoolTy, 9940 VK_RValue, OK_Ordinary, Loc, false); 9941 9942 // Create the pre-increment of the iteration variable. 9943 Expr *Increment 9944 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9945 SizeType, VK_LValue, OK_Ordinary, Loc); 9946 9947 // Construct the loop that copies all elements of this array. 9948 return S.ActOnForStmt(Loc, Loc, InitStmt, 9949 S.MakeFullExpr(Comparison), 9950 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9951 Loc, Copy.get()); 9952 } 9953 9954 static StmtResult 9955 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9956 const ExprBuilder &To, const ExprBuilder &From, 9957 bool CopyingBaseSubobject, bool Copying) { 9958 // Maybe we should use a memcpy? 9959 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9960 T.isTriviallyCopyableType(S.Context)) 9961 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9962 9963 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9964 CopyingBaseSubobject, 9965 Copying, 0)); 9966 9967 // If we ended up picking a trivial assignment operator for an array of a 9968 // non-trivially-copyable class type, just emit a memcpy. 9969 if (!Result.isInvalid() && !Result.get()) 9970 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9971 9972 return Result; 9973 } 9974 9975 Sema::ImplicitExceptionSpecification 9976 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9977 CXXRecordDecl *ClassDecl = MD->getParent(); 9978 9979 ImplicitExceptionSpecification ExceptSpec(*this); 9980 if (ClassDecl->isInvalidDecl()) 9981 return ExceptSpec; 9982 9983 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9984 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9985 unsigned ArgQuals = 9986 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9987 9988 // C++ [except.spec]p14: 9989 // An implicitly declared special member function (Clause 12) shall have an 9990 // exception-specification. [...] 9991 9992 // It is unspecified whether or not an implicit copy assignment operator 9993 // attempts to deduplicate calls to assignment operators of virtual bases are 9994 // made. As such, this exception specification is effectively unspecified. 9995 // Based on a similar decision made for constness in C++0x, we're erring on 9996 // the side of assuming such calls to be made regardless of whether they 9997 // actually happen. 9998 for (const auto &Base : ClassDecl->bases()) { 9999 if (Base.isVirtual()) 10000 continue; 10001 10002 CXXRecordDecl *BaseClassDecl 10003 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10004 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10005 ArgQuals, false, 0)) 10006 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10007 } 10008 10009 for (const auto &Base : ClassDecl->vbases()) { 10010 CXXRecordDecl *BaseClassDecl 10011 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10012 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10013 ArgQuals, false, 0)) 10014 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10015 } 10016 10017 for (const auto *Field : ClassDecl->fields()) { 10018 QualType FieldType = Context.getBaseElementType(Field->getType()); 10019 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10020 if (CXXMethodDecl *CopyAssign = 10021 LookupCopyingAssignment(FieldClassDecl, 10022 ArgQuals | FieldType.getCVRQualifiers(), 10023 false, 0)) 10024 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 10025 } 10026 } 10027 10028 return ExceptSpec; 10029 } 10030 10031 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 10032 // Note: The following rules are largely analoguous to the copy 10033 // constructor rules. Note that virtual bases are not taken into account 10034 // for determining the argument type of the operator. Note also that 10035 // operators taking an object instead of a reference are allowed. 10036 assert(ClassDecl->needsImplicitCopyAssignment()); 10037 10038 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 10039 if (DSM.isAlreadyBeingDeclared()) 10040 return nullptr; 10041 10042 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10043 QualType RetType = Context.getLValueReferenceType(ArgType); 10044 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10045 if (Const) 10046 ArgType = ArgType.withConst(); 10047 ArgType = Context.getLValueReferenceType(ArgType); 10048 10049 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10050 CXXCopyAssignment, 10051 Const); 10052 10053 // An implicitly-declared copy assignment operator is an inline public 10054 // member of its class. 10055 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10056 SourceLocation ClassLoc = ClassDecl->getLocation(); 10057 DeclarationNameInfo NameInfo(Name, ClassLoc); 10058 CXXMethodDecl *CopyAssignment = 10059 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10060 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10061 /*isInline=*/true, Constexpr, SourceLocation()); 10062 CopyAssignment->setAccess(AS_public); 10063 CopyAssignment->setDefaulted(); 10064 CopyAssignment->setImplicit(); 10065 10066 if (getLangOpts().CUDA) { 10067 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10068 CopyAssignment, 10069 /* ConstRHS */ Const, 10070 /* Diagnose */ false); 10071 } 10072 10073 // Build an exception specification pointing back at this member. 10074 FunctionProtoType::ExtProtoInfo EPI = 10075 getImplicitMethodEPI(*this, CopyAssignment); 10076 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10077 10078 // Add the parameter to the operator. 10079 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10080 ClassLoc, ClassLoc, 10081 /*Id=*/nullptr, ArgType, 10082 /*TInfo=*/nullptr, SC_None, 10083 nullptr); 10084 CopyAssignment->setParams(FromParam); 10085 10086 AddOverriddenMethods(ClassDecl, CopyAssignment); 10087 10088 CopyAssignment->setTrivial( 10089 ClassDecl->needsOverloadResolutionForCopyAssignment() 10090 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10091 : ClassDecl->hasTrivialCopyAssignment()); 10092 10093 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10094 SetDeclDeleted(CopyAssignment, ClassLoc); 10095 10096 // Note that we have added this copy-assignment operator. 10097 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10098 10099 if (Scope *S = getScopeForContext(ClassDecl)) 10100 PushOnScopeChains(CopyAssignment, S, false); 10101 ClassDecl->addDecl(CopyAssignment); 10102 10103 return CopyAssignment; 10104 } 10105 10106 /// Diagnose an implicit copy operation for a class which is odr-used, but 10107 /// which is deprecated because the class has a user-declared copy constructor, 10108 /// copy assignment operator, or destructor. 10109 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10110 SourceLocation UseLoc) { 10111 assert(CopyOp->isImplicit()); 10112 10113 CXXRecordDecl *RD = CopyOp->getParent(); 10114 CXXMethodDecl *UserDeclaredOperation = nullptr; 10115 10116 // In Microsoft mode, assignment operations don't affect constructors and 10117 // vice versa. 10118 if (RD->hasUserDeclaredDestructor()) { 10119 UserDeclaredOperation = RD->getDestructor(); 10120 } else if (!isa<CXXConstructorDecl>(CopyOp) && 10121 RD->hasUserDeclaredCopyConstructor() && 10122 !S.getLangOpts().MSVCCompat) { 10123 // Find any user-declared copy constructor. 10124 for (auto *I : RD->ctors()) { 10125 if (I->isCopyConstructor()) { 10126 UserDeclaredOperation = I; 10127 break; 10128 } 10129 } 10130 assert(UserDeclaredOperation); 10131 } else if (isa<CXXConstructorDecl>(CopyOp) && 10132 RD->hasUserDeclaredCopyAssignment() && 10133 !S.getLangOpts().MSVCCompat) { 10134 // Find any user-declared move assignment operator. 10135 for (auto *I : RD->methods()) { 10136 if (I->isCopyAssignmentOperator()) { 10137 UserDeclaredOperation = I; 10138 break; 10139 } 10140 } 10141 assert(UserDeclaredOperation); 10142 } 10143 10144 if (UserDeclaredOperation) { 10145 S.Diag(UserDeclaredOperation->getLocation(), 10146 diag::warn_deprecated_copy_operation) 10147 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 10148 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 10149 S.Diag(UseLoc, diag::note_member_synthesized_at) 10150 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 10151 : Sema::CXXCopyAssignment) 10152 << RD; 10153 } 10154 } 10155 10156 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 10157 CXXMethodDecl *CopyAssignOperator) { 10158 assert((CopyAssignOperator->isDefaulted() && 10159 CopyAssignOperator->isOverloadedOperator() && 10160 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10161 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10162 !CopyAssignOperator->isDeleted()) && 10163 "DefineImplicitCopyAssignment called for wrong function"); 10164 10165 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10166 10167 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10168 CopyAssignOperator->setInvalidDecl(); 10169 return; 10170 } 10171 10172 // C++11 [class.copy]p18: 10173 // The [definition of an implicitly declared copy assignment operator] is 10174 // deprecated if the class has a user-declared copy constructor or a 10175 // user-declared destructor. 10176 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10177 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10178 10179 CopyAssignOperator->markUsed(Context); 10180 10181 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10182 DiagnosticErrorTrap Trap(Diags); 10183 10184 // C++0x [class.copy]p30: 10185 // The implicitly-defined or explicitly-defaulted copy assignment operator 10186 // for a non-union class X performs memberwise copy assignment of its 10187 // subobjects. The direct base classes of X are assigned first, in the 10188 // order of their declaration in the base-specifier-list, and then the 10189 // immediate non-static data members of X are assigned, in the order in 10190 // which they were declared in the class definition. 10191 10192 // The statements that form the synthesized function body. 10193 SmallVector<Stmt*, 8> Statements; 10194 10195 // The parameter for the "other" object, which we are copying from. 10196 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10197 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10198 QualType OtherRefType = Other->getType(); 10199 if (const LValueReferenceType *OtherRef 10200 = OtherRefType->getAs<LValueReferenceType>()) { 10201 OtherRefType = OtherRef->getPointeeType(); 10202 OtherQuals = OtherRefType.getQualifiers(); 10203 } 10204 10205 // Our location for everything implicitly-generated. 10206 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10207 ? CopyAssignOperator->getLocEnd() 10208 : CopyAssignOperator->getLocation(); 10209 10210 // Builds a DeclRefExpr for the "other" object. 10211 RefBuilder OtherRef(Other, OtherRefType); 10212 10213 // Builds the "this" pointer. 10214 ThisBuilder This; 10215 10216 // Assign base classes. 10217 bool Invalid = false; 10218 for (auto &Base : ClassDecl->bases()) { 10219 // Form the assignment: 10220 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10221 QualType BaseType = Base.getType().getUnqualifiedType(); 10222 if (!BaseType->isRecordType()) { 10223 Invalid = true; 10224 continue; 10225 } 10226 10227 CXXCastPath BasePath; 10228 BasePath.push_back(&Base); 10229 10230 // Construct the "from" expression, which is an implicit cast to the 10231 // appropriately-qualified base type. 10232 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10233 VK_LValue, BasePath); 10234 10235 // Dereference "this". 10236 DerefBuilder DerefThis(This); 10237 CastBuilder To(DerefThis, 10238 Context.getCVRQualifiedType( 10239 BaseType, CopyAssignOperator->getTypeQualifiers()), 10240 VK_LValue, BasePath); 10241 10242 // Build the copy. 10243 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10244 To, From, 10245 /*CopyingBaseSubobject=*/true, 10246 /*Copying=*/true); 10247 if (Copy.isInvalid()) { 10248 Diag(CurrentLocation, diag::note_member_synthesized_at) 10249 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10250 CopyAssignOperator->setInvalidDecl(); 10251 return; 10252 } 10253 10254 // Success! Record the copy. 10255 Statements.push_back(Copy.getAs<Expr>()); 10256 } 10257 10258 // Assign non-static members. 10259 for (auto *Field : ClassDecl->fields()) { 10260 // FIXME: We should form some kind of AST representation for the implied 10261 // memcpy in a union copy operation. 10262 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10263 continue; 10264 10265 if (Field->isInvalidDecl()) { 10266 Invalid = true; 10267 continue; 10268 } 10269 10270 // Check for members of reference type; we can't copy those. 10271 if (Field->getType()->isReferenceType()) { 10272 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10273 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10274 Diag(Field->getLocation(), diag::note_declared_at); 10275 Diag(CurrentLocation, diag::note_member_synthesized_at) 10276 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10277 Invalid = true; 10278 continue; 10279 } 10280 10281 // Check for members of const-qualified, non-class type. 10282 QualType BaseType = Context.getBaseElementType(Field->getType()); 10283 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10284 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10285 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10286 Diag(Field->getLocation(), diag::note_declared_at); 10287 Diag(CurrentLocation, diag::note_member_synthesized_at) 10288 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10289 Invalid = true; 10290 continue; 10291 } 10292 10293 // Suppress assigning zero-width bitfields. 10294 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10295 continue; 10296 10297 QualType FieldType = Field->getType().getNonReferenceType(); 10298 if (FieldType->isIncompleteArrayType()) { 10299 assert(ClassDecl->hasFlexibleArrayMember() && 10300 "Incomplete array type is not valid"); 10301 continue; 10302 } 10303 10304 // Build references to the field in the object we're copying from and to. 10305 CXXScopeSpec SS; // Intentionally empty 10306 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10307 LookupMemberName); 10308 MemberLookup.addDecl(Field); 10309 MemberLookup.resolveKind(); 10310 10311 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10312 10313 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10314 10315 // Build the copy of this field. 10316 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10317 To, From, 10318 /*CopyingBaseSubobject=*/false, 10319 /*Copying=*/true); 10320 if (Copy.isInvalid()) { 10321 Diag(CurrentLocation, diag::note_member_synthesized_at) 10322 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10323 CopyAssignOperator->setInvalidDecl(); 10324 return; 10325 } 10326 10327 // Success! Record the copy. 10328 Statements.push_back(Copy.getAs<Stmt>()); 10329 } 10330 10331 if (!Invalid) { 10332 // Add a "return *this;" 10333 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10334 10335 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10336 if (Return.isInvalid()) 10337 Invalid = true; 10338 else { 10339 Statements.push_back(Return.getAs<Stmt>()); 10340 10341 if (Trap.hasErrorOccurred()) { 10342 Diag(CurrentLocation, diag::note_member_synthesized_at) 10343 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10344 Invalid = true; 10345 } 10346 } 10347 } 10348 10349 // The exception specification is needed because we are defining the 10350 // function. 10351 ResolveExceptionSpec(CurrentLocation, 10352 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10353 10354 if (Invalid) { 10355 CopyAssignOperator->setInvalidDecl(); 10356 return; 10357 } 10358 10359 StmtResult Body; 10360 { 10361 CompoundScopeRAII CompoundScope(*this); 10362 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10363 /*isStmtExpr=*/false); 10364 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10365 } 10366 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10367 10368 if (ASTMutationListener *L = getASTMutationListener()) { 10369 L->CompletedImplicitDefinition(CopyAssignOperator); 10370 } 10371 } 10372 10373 Sema::ImplicitExceptionSpecification 10374 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10375 CXXRecordDecl *ClassDecl = MD->getParent(); 10376 10377 ImplicitExceptionSpecification ExceptSpec(*this); 10378 if (ClassDecl->isInvalidDecl()) 10379 return ExceptSpec; 10380 10381 // C++0x [except.spec]p14: 10382 // An implicitly declared special member function (Clause 12) shall have an 10383 // exception-specification. [...] 10384 10385 // It is unspecified whether or not an implicit move assignment operator 10386 // attempts to deduplicate calls to assignment operators of virtual bases are 10387 // made. As such, this exception specification is effectively unspecified. 10388 // Based on a similar decision made for constness in C++0x, we're erring on 10389 // the side of assuming such calls to be made regardless of whether they 10390 // actually happen. 10391 // Note that a move constructor is not implicitly declared when there are 10392 // virtual bases, but it can still be user-declared and explicitly defaulted. 10393 for (const auto &Base : ClassDecl->bases()) { 10394 if (Base.isVirtual()) 10395 continue; 10396 10397 CXXRecordDecl *BaseClassDecl 10398 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10399 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10400 0, false, 0)) 10401 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10402 } 10403 10404 for (const auto &Base : ClassDecl->vbases()) { 10405 CXXRecordDecl *BaseClassDecl 10406 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10407 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10408 0, false, 0)) 10409 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10410 } 10411 10412 for (const auto *Field : ClassDecl->fields()) { 10413 QualType FieldType = Context.getBaseElementType(Field->getType()); 10414 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10415 if (CXXMethodDecl *MoveAssign = 10416 LookupMovingAssignment(FieldClassDecl, 10417 FieldType.getCVRQualifiers(), 10418 false, 0)) 10419 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10420 } 10421 } 10422 10423 return ExceptSpec; 10424 } 10425 10426 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10427 assert(ClassDecl->needsImplicitMoveAssignment()); 10428 10429 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10430 if (DSM.isAlreadyBeingDeclared()) 10431 return nullptr; 10432 10433 // Note: The following rules are largely analoguous to the move 10434 // constructor rules. 10435 10436 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10437 QualType RetType = Context.getLValueReferenceType(ArgType); 10438 ArgType = Context.getRValueReferenceType(ArgType); 10439 10440 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10441 CXXMoveAssignment, 10442 false); 10443 10444 // An implicitly-declared move assignment operator is an inline public 10445 // member of its class. 10446 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10447 SourceLocation ClassLoc = ClassDecl->getLocation(); 10448 DeclarationNameInfo NameInfo(Name, ClassLoc); 10449 CXXMethodDecl *MoveAssignment = 10450 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10451 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10452 /*isInline=*/true, Constexpr, SourceLocation()); 10453 MoveAssignment->setAccess(AS_public); 10454 MoveAssignment->setDefaulted(); 10455 MoveAssignment->setImplicit(); 10456 10457 if (getLangOpts().CUDA) { 10458 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10459 MoveAssignment, 10460 /* ConstRHS */ false, 10461 /* Diagnose */ false); 10462 } 10463 10464 // Build an exception specification pointing back at this member. 10465 FunctionProtoType::ExtProtoInfo EPI = 10466 getImplicitMethodEPI(*this, MoveAssignment); 10467 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10468 10469 // Add the parameter to the operator. 10470 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10471 ClassLoc, ClassLoc, 10472 /*Id=*/nullptr, ArgType, 10473 /*TInfo=*/nullptr, SC_None, 10474 nullptr); 10475 MoveAssignment->setParams(FromParam); 10476 10477 AddOverriddenMethods(ClassDecl, MoveAssignment); 10478 10479 MoveAssignment->setTrivial( 10480 ClassDecl->needsOverloadResolutionForMoveAssignment() 10481 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10482 : ClassDecl->hasTrivialMoveAssignment()); 10483 10484 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10485 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10486 SetDeclDeleted(MoveAssignment, ClassLoc); 10487 } 10488 10489 // Note that we have added this copy-assignment operator. 10490 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10491 10492 if (Scope *S = getScopeForContext(ClassDecl)) 10493 PushOnScopeChains(MoveAssignment, S, false); 10494 ClassDecl->addDecl(MoveAssignment); 10495 10496 return MoveAssignment; 10497 } 10498 10499 /// Check if we're implicitly defining a move assignment operator for a class 10500 /// with virtual bases. Such a move assignment might move-assign the virtual 10501 /// base multiple times. 10502 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10503 SourceLocation CurrentLocation) { 10504 assert(!Class->isDependentContext() && "should not define dependent move"); 10505 10506 // Only a virtual base could get implicitly move-assigned multiple times. 10507 // Only a non-trivial move assignment can observe this. We only want to 10508 // diagnose if we implicitly define an assignment operator that assigns 10509 // two base classes, both of which move-assign the same virtual base. 10510 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10511 Class->getNumBases() < 2) 10512 return; 10513 10514 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10515 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10516 VBaseMap VBases; 10517 10518 for (auto &BI : Class->bases()) { 10519 Worklist.push_back(&BI); 10520 while (!Worklist.empty()) { 10521 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10522 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10523 10524 // If the base has no non-trivial move assignment operators, 10525 // we don't care about moves from it. 10526 if (!Base->hasNonTrivialMoveAssignment()) 10527 continue; 10528 10529 // If there's nothing virtual here, skip it. 10530 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10531 continue; 10532 10533 // If we're not actually going to call a move assignment for this base, 10534 // or the selected move assignment is trivial, skip it. 10535 Sema::SpecialMemberOverloadResult *SMOR = 10536 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10537 /*ConstArg*/false, /*VolatileArg*/false, 10538 /*RValueThis*/true, /*ConstThis*/false, 10539 /*VolatileThis*/false); 10540 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10541 !SMOR->getMethod()->isMoveAssignmentOperator()) 10542 continue; 10543 10544 if (BaseSpec->isVirtual()) { 10545 // We're going to move-assign this virtual base, and its move 10546 // assignment operator is not trivial. If this can happen for 10547 // multiple distinct direct bases of Class, diagnose it. (If it 10548 // only happens in one base, we'll diagnose it when synthesizing 10549 // that base class's move assignment operator.) 10550 CXXBaseSpecifier *&Existing = 10551 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10552 .first->second; 10553 if (Existing && Existing != &BI) { 10554 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10555 << Class << Base; 10556 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10557 << (Base->getCanonicalDecl() == 10558 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10559 << Base << Existing->getType() << Existing->getSourceRange(); 10560 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10561 << (Base->getCanonicalDecl() == 10562 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10563 << Base << BI.getType() << BaseSpec->getSourceRange(); 10564 10565 // Only diagnose each vbase once. 10566 Existing = nullptr; 10567 } 10568 } else { 10569 // Only walk over bases that have defaulted move assignment operators. 10570 // We assume that any user-provided move assignment operator handles 10571 // the multiple-moves-of-vbase case itself somehow. 10572 if (!SMOR->getMethod()->isDefaulted()) 10573 continue; 10574 10575 // We're going to move the base classes of Base. Add them to the list. 10576 for (auto &BI : Base->bases()) 10577 Worklist.push_back(&BI); 10578 } 10579 } 10580 } 10581 } 10582 10583 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10584 CXXMethodDecl *MoveAssignOperator) { 10585 assert((MoveAssignOperator->isDefaulted() && 10586 MoveAssignOperator->isOverloadedOperator() && 10587 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10588 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10589 !MoveAssignOperator->isDeleted()) && 10590 "DefineImplicitMoveAssignment called for wrong function"); 10591 10592 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10593 10594 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10595 MoveAssignOperator->setInvalidDecl(); 10596 return; 10597 } 10598 10599 MoveAssignOperator->markUsed(Context); 10600 10601 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10602 DiagnosticErrorTrap Trap(Diags); 10603 10604 // C++0x [class.copy]p28: 10605 // The implicitly-defined or move assignment operator for a non-union class 10606 // X performs memberwise move assignment of its subobjects. The direct base 10607 // classes of X are assigned first, in the order of their declaration in the 10608 // base-specifier-list, and then the immediate non-static data members of X 10609 // are assigned, in the order in which they were declared in the class 10610 // definition. 10611 10612 // Issue a warning if our implicit move assignment operator will move 10613 // from a virtual base more than once. 10614 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10615 10616 // The statements that form the synthesized function body. 10617 SmallVector<Stmt*, 8> Statements; 10618 10619 // The parameter for the "other" object, which we are move from. 10620 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10621 QualType OtherRefType = Other->getType()-> 10622 getAs<RValueReferenceType>()->getPointeeType(); 10623 assert(!OtherRefType.getQualifiers() && 10624 "Bad argument type of defaulted move assignment"); 10625 10626 // Our location for everything implicitly-generated. 10627 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10628 ? MoveAssignOperator->getLocEnd() 10629 : MoveAssignOperator->getLocation(); 10630 10631 // Builds a reference to the "other" object. 10632 RefBuilder OtherRef(Other, OtherRefType); 10633 // Cast to rvalue. 10634 MoveCastBuilder MoveOther(OtherRef); 10635 10636 // Builds the "this" pointer. 10637 ThisBuilder This; 10638 10639 // Assign base classes. 10640 bool Invalid = false; 10641 for (auto &Base : ClassDecl->bases()) { 10642 // C++11 [class.copy]p28: 10643 // It is unspecified whether subobjects representing virtual base classes 10644 // are assigned more than once by the implicitly-defined copy assignment 10645 // operator. 10646 // FIXME: Do not assign to a vbase that will be assigned by some other base 10647 // class. For a move-assignment, this can result in the vbase being moved 10648 // multiple times. 10649 10650 // Form the assignment: 10651 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10652 QualType BaseType = Base.getType().getUnqualifiedType(); 10653 if (!BaseType->isRecordType()) { 10654 Invalid = true; 10655 continue; 10656 } 10657 10658 CXXCastPath BasePath; 10659 BasePath.push_back(&Base); 10660 10661 // Construct the "from" expression, which is an implicit cast to the 10662 // appropriately-qualified base type. 10663 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10664 10665 // Dereference "this". 10666 DerefBuilder DerefThis(This); 10667 10668 // Implicitly cast "this" to the appropriately-qualified base type. 10669 CastBuilder To(DerefThis, 10670 Context.getCVRQualifiedType( 10671 BaseType, MoveAssignOperator->getTypeQualifiers()), 10672 VK_LValue, BasePath); 10673 10674 // Build the move. 10675 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10676 To, From, 10677 /*CopyingBaseSubobject=*/true, 10678 /*Copying=*/false); 10679 if (Move.isInvalid()) { 10680 Diag(CurrentLocation, diag::note_member_synthesized_at) 10681 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10682 MoveAssignOperator->setInvalidDecl(); 10683 return; 10684 } 10685 10686 // Success! Record the move. 10687 Statements.push_back(Move.getAs<Expr>()); 10688 } 10689 10690 // Assign non-static members. 10691 for (auto *Field : ClassDecl->fields()) { 10692 // FIXME: We should form some kind of AST representation for the implied 10693 // memcpy in a union copy operation. 10694 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10695 continue; 10696 10697 if (Field->isInvalidDecl()) { 10698 Invalid = true; 10699 continue; 10700 } 10701 10702 // Check for members of reference type; we can't move those. 10703 if (Field->getType()->isReferenceType()) { 10704 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10705 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10706 Diag(Field->getLocation(), diag::note_declared_at); 10707 Diag(CurrentLocation, diag::note_member_synthesized_at) 10708 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10709 Invalid = true; 10710 continue; 10711 } 10712 10713 // Check for members of const-qualified, non-class type. 10714 QualType BaseType = Context.getBaseElementType(Field->getType()); 10715 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10716 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10717 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10718 Diag(Field->getLocation(), diag::note_declared_at); 10719 Diag(CurrentLocation, diag::note_member_synthesized_at) 10720 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10721 Invalid = true; 10722 continue; 10723 } 10724 10725 // Suppress assigning zero-width bitfields. 10726 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10727 continue; 10728 10729 QualType FieldType = Field->getType().getNonReferenceType(); 10730 if (FieldType->isIncompleteArrayType()) { 10731 assert(ClassDecl->hasFlexibleArrayMember() && 10732 "Incomplete array type is not valid"); 10733 continue; 10734 } 10735 10736 // Build references to the field in the object we're copying from and to. 10737 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10738 LookupMemberName); 10739 MemberLookup.addDecl(Field); 10740 MemberLookup.resolveKind(); 10741 MemberBuilder From(MoveOther, OtherRefType, 10742 /*IsArrow=*/false, MemberLookup); 10743 MemberBuilder To(This, getCurrentThisType(), 10744 /*IsArrow=*/true, MemberLookup); 10745 10746 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10747 "Member reference with rvalue base must be rvalue except for reference " 10748 "members, which aren't allowed for move assignment."); 10749 10750 // Build the move of this field. 10751 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10752 To, From, 10753 /*CopyingBaseSubobject=*/false, 10754 /*Copying=*/false); 10755 if (Move.isInvalid()) { 10756 Diag(CurrentLocation, diag::note_member_synthesized_at) 10757 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10758 MoveAssignOperator->setInvalidDecl(); 10759 return; 10760 } 10761 10762 // Success! Record the copy. 10763 Statements.push_back(Move.getAs<Stmt>()); 10764 } 10765 10766 if (!Invalid) { 10767 // Add a "return *this;" 10768 ExprResult ThisObj = 10769 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10770 10771 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10772 if (Return.isInvalid()) 10773 Invalid = true; 10774 else { 10775 Statements.push_back(Return.getAs<Stmt>()); 10776 10777 if (Trap.hasErrorOccurred()) { 10778 Diag(CurrentLocation, diag::note_member_synthesized_at) 10779 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10780 Invalid = true; 10781 } 10782 } 10783 } 10784 10785 // The exception specification is needed because we are defining the 10786 // function. 10787 ResolveExceptionSpec(CurrentLocation, 10788 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10789 10790 if (Invalid) { 10791 MoveAssignOperator->setInvalidDecl(); 10792 return; 10793 } 10794 10795 StmtResult Body; 10796 { 10797 CompoundScopeRAII CompoundScope(*this); 10798 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10799 /*isStmtExpr=*/false); 10800 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10801 } 10802 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10803 10804 if (ASTMutationListener *L = getASTMutationListener()) { 10805 L->CompletedImplicitDefinition(MoveAssignOperator); 10806 } 10807 } 10808 10809 Sema::ImplicitExceptionSpecification 10810 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10811 CXXRecordDecl *ClassDecl = MD->getParent(); 10812 10813 ImplicitExceptionSpecification ExceptSpec(*this); 10814 if (ClassDecl->isInvalidDecl()) 10815 return ExceptSpec; 10816 10817 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10818 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10819 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10820 10821 // C++ [except.spec]p14: 10822 // An implicitly declared special member function (Clause 12) shall have an 10823 // exception-specification. [...] 10824 for (const auto &Base : ClassDecl->bases()) { 10825 // Virtual bases are handled below. 10826 if (Base.isVirtual()) 10827 continue; 10828 10829 CXXRecordDecl *BaseClassDecl 10830 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10831 if (CXXConstructorDecl *CopyConstructor = 10832 LookupCopyingConstructor(BaseClassDecl, Quals)) 10833 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10834 } 10835 for (const auto &Base : ClassDecl->vbases()) { 10836 CXXRecordDecl *BaseClassDecl 10837 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10838 if (CXXConstructorDecl *CopyConstructor = 10839 LookupCopyingConstructor(BaseClassDecl, Quals)) 10840 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10841 } 10842 for (const auto *Field : ClassDecl->fields()) { 10843 QualType FieldType = Context.getBaseElementType(Field->getType()); 10844 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10845 if (CXXConstructorDecl *CopyConstructor = 10846 LookupCopyingConstructor(FieldClassDecl, 10847 Quals | FieldType.getCVRQualifiers())) 10848 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10849 } 10850 } 10851 10852 return ExceptSpec; 10853 } 10854 10855 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10856 CXXRecordDecl *ClassDecl) { 10857 // C++ [class.copy]p4: 10858 // If the class definition does not explicitly declare a copy 10859 // constructor, one is declared implicitly. 10860 assert(ClassDecl->needsImplicitCopyConstructor()); 10861 10862 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10863 if (DSM.isAlreadyBeingDeclared()) 10864 return nullptr; 10865 10866 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10867 QualType ArgType = ClassType; 10868 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10869 if (Const) 10870 ArgType = ArgType.withConst(); 10871 ArgType = Context.getLValueReferenceType(ArgType); 10872 10873 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10874 CXXCopyConstructor, 10875 Const); 10876 10877 DeclarationName Name 10878 = Context.DeclarationNames.getCXXConstructorName( 10879 Context.getCanonicalType(ClassType)); 10880 SourceLocation ClassLoc = ClassDecl->getLocation(); 10881 DeclarationNameInfo NameInfo(Name, ClassLoc); 10882 10883 // An implicitly-declared copy constructor is an inline public 10884 // member of its class. 10885 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10886 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10887 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10888 Constexpr); 10889 CopyConstructor->setAccess(AS_public); 10890 CopyConstructor->setDefaulted(); 10891 10892 if (getLangOpts().CUDA) { 10893 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10894 CopyConstructor, 10895 /* ConstRHS */ Const, 10896 /* Diagnose */ false); 10897 } 10898 10899 // Build an exception specification pointing back at this member. 10900 FunctionProtoType::ExtProtoInfo EPI = 10901 getImplicitMethodEPI(*this, CopyConstructor); 10902 CopyConstructor->setType( 10903 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10904 10905 // Add the parameter to the constructor. 10906 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10907 ClassLoc, ClassLoc, 10908 /*IdentifierInfo=*/nullptr, 10909 ArgType, /*TInfo=*/nullptr, 10910 SC_None, nullptr); 10911 CopyConstructor->setParams(FromParam); 10912 10913 CopyConstructor->setTrivial( 10914 ClassDecl->needsOverloadResolutionForCopyConstructor() 10915 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10916 : ClassDecl->hasTrivialCopyConstructor()); 10917 10918 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10919 SetDeclDeleted(CopyConstructor, ClassLoc); 10920 10921 // Note that we have declared this constructor. 10922 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10923 10924 if (Scope *S = getScopeForContext(ClassDecl)) 10925 PushOnScopeChains(CopyConstructor, S, false); 10926 ClassDecl->addDecl(CopyConstructor); 10927 10928 return CopyConstructor; 10929 } 10930 10931 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10932 CXXConstructorDecl *CopyConstructor) { 10933 assert((CopyConstructor->isDefaulted() && 10934 CopyConstructor->isCopyConstructor() && 10935 !CopyConstructor->doesThisDeclarationHaveABody() && 10936 !CopyConstructor->isDeleted()) && 10937 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10938 10939 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10940 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10941 10942 // C++11 [class.copy]p7: 10943 // The [definition of an implicitly declared copy constructor] is 10944 // deprecated if the class has a user-declared copy assignment operator 10945 // or a user-declared destructor. 10946 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10947 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10948 10949 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10950 DiagnosticErrorTrap Trap(Diags); 10951 10952 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10953 Trap.hasErrorOccurred()) { 10954 Diag(CurrentLocation, diag::note_member_synthesized_at) 10955 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10956 CopyConstructor->setInvalidDecl(); 10957 } else { 10958 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10959 ? CopyConstructor->getLocEnd() 10960 : CopyConstructor->getLocation(); 10961 Sema::CompoundScopeRAII CompoundScope(*this); 10962 CopyConstructor->setBody( 10963 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10964 } 10965 10966 // The exception specification is needed because we are defining the 10967 // function. 10968 ResolveExceptionSpec(CurrentLocation, 10969 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10970 10971 CopyConstructor->markUsed(Context); 10972 MarkVTableUsed(CurrentLocation, ClassDecl); 10973 10974 if (ASTMutationListener *L = getASTMutationListener()) { 10975 L->CompletedImplicitDefinition(CopyConstructor); 10976 } 10977 } 10978 10979 Sema::ImplicitExceptionSpecification 10980 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10981 CXXRecordDecl *ClassDecl = MD->getParent(); 10982 10983 // C++ [except.spec]p14: 10984 // An implicitly declared special member function (Clause 12) shall have an 10985 // exception-specification. [...] 10986 ImplicitExceptionSpecification ExceptSpec(*this); 10987 if (ClassDecl->isInvalidDecl()) 10988 return ExceptSpec; 10989 10990 // Direct base-class constructors. 10991 for (const auto &B : ClassDecl->bases()) { 10992 if (B.isVirtual()) // Handled below. 10993 continue; 10994 10995 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10996 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10997 CXXConstructorDecl *Constructor = 10998 LookupMovingConstructor(BaseClassDecl, 0); 10999 // If this is a deleted function, add it anyway. This might be conformant 11000 // with the standard. This might not. I'm not sure. It might not matter. 11001 if (Constructor) 11002 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11003 } 11004 } 11005 11006 // Virtual base-class constructors. 11007 for (const auto &B : ClassDecl->vbases()) { 11008 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11009 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11010 CXXConstructorDecl *Constructor = 11011 LookupMovingConstructor(BaseClassDecl, 0); 11012 // If this is a deleted function, add it anyway. This might be conformant 11013 // with the standard. This might not. I'm not sure. It might not matter. 11014 if (Constructor) 11015 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11016 } 11017 } 11018 11019 // Field constructors. 11020 for (const auto *F : ClassDecl->fields()) { 11021 QualType FieldType = Context.getBaseElementType(F->getType()); 11022 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 11023 CXXConstructorDecl *Constructor = 11024 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 11025 // If this is a deleted function, add it anyway. This might be conformant 11026 // with the standard. This might not. I'm not sure. It might not matter. 11027 // In particular, the problem is that this function never gets called. It 11028 // might just be ill-formed because this function attempts to refer to 11029 // a deleted function here. 11030 if (Constructor) 11031 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 11032 } 11033 } 11034 11035 return ExceptSpec; 11036 } 11037 11038 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 11039 CXXRecordDecl *ClassDecl) { 11040 assert(ClassDecl->needsImplicitMoveConstructor()); 11041 11042 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11043 if (DSM.isAlreadyBeingDeclared()) 11044 return nullptr; 11045 11046 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11047 QualType ArgType = Context.getRValueReferenceType(ClassType); 11048 11049 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11050 CXXMoveConstructor, 11051 false); 11052 11053 DeclarationName Name 11054 = Context.DeclarationNames.getCXXConstructorName( 11055 Context.getCanonicalType(ClassType)); 11056 SourceLocation ClassLoc = ClassDecl->getLocation(); 11057 DeclarationNameInfo NameInfo(Name, ClassLoc); 11058 11059 // C++11 [class.copy]p11: 11060 // An implicitly-declared copy/move constructor is an inline public 11061 // member of its class. 11062 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11063 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11064 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11065 Constexpr); 11066 MoveConstructor->setAccess(AS_public); 11067 MoveConstructor->setDefaulted(); 11068 11069 if (getLangOpts().CUDA) { 11070 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11071 MoveConstructor, 11072 /* ConstRHS */ false, 11073 /* Diagnose */ false); 11074 } 11075 11076 // Build an exception specification pointing back at this member. 11077 FunctionProtoType::ExtProtoInfo EPI = 11078 getImplicitMethodEPI(*this, MoveConstructor); 11079 MoveConstructor->setType( 11080 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11081 11082 // Add the parameter to the constructor. 11083 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11084 ClassLoc, ClassLoc, 11085 /*IdentifierInfo=*/nullptr, 11086 ArgType, /*TInfo=*/nullptr, 11087 SC_None, nullptr); 11088 MoveConstructor->setParams(FromParam); 11089 11090 MoveConstructor->setTrivial( 11091 ClassDecl->needsOverloadResolutionForMoveConstructor() 11092 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11093 : ClassDecl->hasTrivialMoveConstructor()); 11094 11095 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 11096 ClassDecl->setImplicitMoveConstructorIsDeleted(); 11097 SetDeclDeleted(MoveConstructor, ClassLoc); 11098 } 11099 11100 // Note that we have declared this constructor. 11101 ++ASTContext::NumImplicitMoveConstructorsDeclared; 11102 11103 if (Scope *S = getScopeForContext(ClassDecl)) 11104 PushOnScopeChains(MoveConstructor, S, false); 11105 ClassDecl->addDecl(MoveConstructor); 11106 11107 return MoveConstructor; 11108 } 11109 11110 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 11111 CXXConstructorDecl *MoveConstructor) { 11112 assert((MoveConstructor->isDefaulted() && 11113 MoveConstructor->isMoveConstructor() && 11114 !MoveConstructor->doesThisDeclarationHaveABody() && 11115 !MoveConstructor->isDeleted()) && 11116 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 11117 11118 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 11119 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 11120 11121 SynthesizedFunctionScope Scope(*this, MoveConstructor); 11122 DiagnosticErrorTrap Trap(Diags); 11123 11124 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 11125 Trap.hasErrorOccurred()) { 11126 Diag(CurrentLocation, diag::note_member_synthesized_at) 11127 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 11128 MoveConstructor->setInvalidDecl(); 11129 } else { 11130 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 11131 ? MoveConstructor->getLocEnd() 11132 : MoveConstructor->getLocation(); 11133 Sema::CompoundScopeRAII CompoundScope(*this); 11134 MoveConstructor->setBody(ActOnCompoundStmt( 11135 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 11136 } 11137 11138 // The exception specification is needed because we are defining the 11139 // function. 11140 ResolveExceptionSpec(CurrentLocation, 11141 MoveConstructor->getType()->castAs<FunctionProtoType>()); 11142 11143 MoveConstructor->markUsed(Context); 11144 MarkVTableUsed(CurrentLocation, ClassDecl); 11145 11146 if (ASTMutationListener *L = getASTMutationListener()) { 11147 L->CompletedImplicitDefinition(MoveConstructor); 11148 } 11149 } 11150 11151 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 11152 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 11153 } 11154 11155 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 11156 SourceLocation CurrentLocation, 11157 CXXConversionDecl *Conv) { 11158 CXXRecordDecl *Lambda = Conv->getParent(); 11159 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 11160 // If we are defining a specialization of a conversion to function-ptr 11161 // cache the deduced template arguments for this specialization 11162 // so that we can use them to retrieve the corresponding call-operator 11163 // and static-invoker. 11164 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11165 11166 // Retrieve the corresponding call-operator specialization. 11167 if (Lambda->isGenericLambda()) { 11168 assert(Conv->isFunctionTemplateSpecialization()); 11169 FunctionTemplateDecl *CallOpTemplate = 11170 CallOp->getDescribedFunctionTemplate(); 11171 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11172 void *InsertPos = nullptr; 11173 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11174 DeducedTemplateArgs->asArray(), 11175 InsertPos); 11176 assert(CallOpSpec && 11177 "Conversion operator must have a corresponding call operator"); 11178 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11179 } 11180 // Mark the call operator referenced (and add to pending instantiations 11181 // if necessary). 11182 // For both the conversion and static-invoker template specializations 11183 // we construct their body's in this function, so no need to add them 11184 // to the PendingInstantiations. 11185 MarkFunctionReferenced(CurrentLocation, CallOp); 11186 11187 SynthesizedFunctionScope Scope(*this, Conv); 11188 DiagnosticErrorTrap Trap(Diags); 11189 11190 // Retrieve the static invoker... 11191 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11192 // ... and get the corresponding specialization for a generic lambda. 11193 if (Lambda->isGenericLambda()) { 11194 assert(DeducedTemplateArgs && 11195 "Must have deduced template arguments from Conversion Operator"); 11196 FunctionTemplateDecl *InvokeTemplate = 11197 Invoker->getDescribedFunctionTemplate(); 11198 void *InsertPos = nullptr; 11199 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11200 DeducedTemplateArgs->asArray(), 11201 InsertPos); 11202 assert(InvokeSpec && 11203 "Must have a corresponding static invoker specialization"); 11204 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11205 } 11206 // Construct the body of the conversion function { return __invoke; }. 11207 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11208 VK_LValue, Conv->getLocation()).get(); 11209 assert(FunctionRef && "Can't refer to __invoke function?"); 11210 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11211 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11212 Conv->getLocation(), 11213 Conv->getLocation())); 11214 11215 Conv->markUsed(Context); 11216 Conv->setReferenced(); 11217 11218 // Fill in the __invoke function with a dummy implementation. IR generation 11219 // will fill in the actual details. 11220 Invoker->markUsed(Context); 11221 Invoker->setReferenced(); 11222 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11223 11224 if (ASTMutationListener *L = getASTMutationListener()) { 11225 L->CompletedImplicitDefinition(Conv); 11226 L->CompletedImplicitDefinition(Invoker); 11227 } 11228 } 11229 11230 11231 11232 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11233 SourceLocation CurrentLocation, 11234 CXXConversionDecl *Conv) 11235 { 11236 assert(!Conv->getParent()->isGenericLambda()); 11237 11238 Conv->markUsed(Context); 11239 11240 SynthesizedFunctionScope Scope(*this, Conv); 11241 DiagnosticErrorTrap Trap(Diags); 11242 11243 // Copy-initialize the lambda object as needed to capture it. 11244 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11245 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11246 11247 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11248 Conv->getLocation(), 11249 Conv, DerefThis); 11250 11251 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11252 // behavior. Note that only the general conversion function does this 11253 // (since it's unusable otherwise); in the case where we inline the 11254 // block literal, it has block literal lifetime semantics. 11255 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11256 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11257 CK_CopyAndAutoreleaseBlockObject, 11258 BuildBlock.get(), nullptr, VK_RValue); 11259 11260 if (BuildBlock.isInvalid()) { 11261 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11262 Conv->setInvalidDecl(); 11263 return; 11264 } 11265 11266 // Create the return statement that returns the block from the conversion 11267 // function. 11268 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11269 if (Return.isInvalid()) { 11270 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11271 Conv->setInvalidDecl(); 11272 return; 11273 } 11274 11275 // Set the body of the conversion function. 11276 Stmt *ReturnS = Return.get(); 11277 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11278 Conv->getLocation(), 11279 Conv->getLocation())); 11280 11281 // We're done; notify the mutation listener, if any. 11282 if (ASTMutationListener *L = getASTMutationListener()) { 11283 L->CompletedImplicitDefinition(Conv); 11284 } 11285 } 11286 11287 /// \brief Determine whether the given list arguments contains exactly one 11288 /// "real" (non-default) argument. 11289 static bool hasOneRealArgument(MultiExprArg Args) { 11290 switch (Args.size()) { 11291 case 0: 11292 return false; 11293 11294 default: 11295 if (!Args[1]->isDefaultArgument()) 11296 return false; 11297 11298 // fall through 11299 case 1: 11300 return !Args[0]->isDefaultArgument(); 11301 } 11302 11303 return false; 11304 } 11305 11306 ExprResult 11307 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11308 CXXConstructorDecl *Constructor, 11309 MultiExprArg ExprArgs, 11310 bool HadMultipleCandidates, 11311 bool IsListInitialization, 11312 bool IsStdInitListInitialization, 11313 bool RequiresZeroInit, 11314 unsigned ConstructKind, 11315 SourceRange ParenRange) { 11316 bool Elidable = false; 11317 11318 // C++0x [class.copy]p34: 11319 // When certain criteria are met, an implementation is allowed to 11320 // omit the copy/move construction of a class object, even if the 11321 // copy/move constructor and/or destructor for the object have 11322 // side effects. [...] 11323 // - when a temporary class object that has not been bound to a 11324 // reference (12.2) would be copied/moved to a class object 11325 // with the same cv-unqualified type, the copy/move operation 11326 // can be omitted by constructing the temporary object 11327 // directly into the target of the omitted copy/move 11328 if (ConstructKind == CXXConstructExpr::CK_Complete && 11329 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11330 Expr *SubExpr = ExprArgs[0]; 11331 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11332 } 11333 11334 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11335 Elidable, ExprArgs, HadMultipleCandidates, 11336 IsListInitialization, 11337 IsStdInitListInitialization, RequiresZeroInit, 11338 ConstructKind, ParenRange); 11339 } 11340 11341 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11342 /// including handling of its default argument expressions. 11343 ExprResult 11344 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11345 CXXConstructorDecl *Constructor, bool Elidable, 11346 MultiExprArg ExprArgs, 11347 bool HadMultipleCandidates, 11348 bool IsListInitialization, 11349 bool IsStdInitListInitialization, 11350 bool RequiresZeroInit, 11351 unsigned ConstructKind, 11352 SourceRange ParenRange) { 11353 MarkFunctionReferenced(ConstructLoc, Constructor); 11354 return CXXConstructExpr::Create( 11355 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11356 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11357 RequiresZeroInit, 11358 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11359 ParenRange); 11360 } 11361 11362 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11363 assert(Field->hasInClassInitializer()); 11364 11365 // If we already have the in-class initializer nothing needs to be done. 11366 if (Field->getInClassInitializer()) 11367 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11368 11369 // Maybe we haven't instantiated the in-class initializer. Go check the 11370 // pattern FieldDecl to see if it has one. 11371 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11372 11373 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11374 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11375 DeclContext::lookup_result Lookup = 11376 ClassPattern->lookup(Field->getDeclName()); 11377 assert(Lookup.size() == 1); 11378 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11379 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11380 getTemplateInstantiationArgs(Field))) 11381 return ExprError(); 11382 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11383 } 11384 11385 // DR1351: 11386 // If the brace-or-equal-initializer of a non-static data member 11387 // invokes a defaulted default constructor of its class or of an 11388 // enclosing class in a potentially evaluated subexpression, the 11389 // program is ill-formed. 11390 // 11391 // This resolution is unworkable: the exception specification of the 11392 // default constructor can be needed in an unevaluated context, in 11393 // particular, in the operand of a noexcept-expression, and we can be 11394 // unable to compute an exception specification for an enclosed class. 11395 // 11396 // Any attempt to resolve the exception specification of a defaulted default 11397 // constructor before the initializer is lexically complete will ultimately 11398 // come here at which point we can diagnose it. 11399 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11400 if (OutermostClass == ParentRD) { 11401 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11402 << ParentRD << Field; 11403 } else { 11404 Diag(Field->getLocEnd(), 11405 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11406 << ParentRD << OutermostClass << Field; 11407 } 11408 11409 return ExprError(); 11410 } 11411 11412 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11413 if (VD->isInvalidDecl()) return; 11414 11415 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11416 if (ClassDecl->isInvalidDecl()) return; 11417 if (ClassDecl->hasIrrelevantDestructor()) return; 11418 if (ClassDecl->isDependentContext()) return; 11419 11420 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11421 MarkFunctionReferenced(VD->getLocation(), Destructor); 11422 CheckDestructorAccess(VD->getLocation(), Destructor, 11423 PDiag(diag::err_access_dtor_var) 11424 << VD->getDeclName() 11425 << VD->getType()); 11426 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11427 11428 if (Destructor->isTrivial()) return; 11429 if (!VD->hasGlobalStorage()) return; 11430 11431 // Emit warning for non-trivial dtor in global scope (a real global, 11432 // class-static, function-static). 11433 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11434 11435 // TODO: this should be re-enabled for static locals by !CXAAtExit 11436 if (!VD->isStaticLocal()) 11437 Diag(VD->getLocation(), diag::warn_global_destructor); 11438 } 11439 11440 /// \brief Given a constructor and the set of arguments provided for the 11441 /// constructor, convert the arguments and add any required default arguments 11442 /// to form a proper call to this constructor. 11443 /// 11444 /// \returns true if an error occurred, false otherwise. 11445 bool 11446 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11447 MultiExprArg ArgsPtr, 11448 SourceLocation Loc, 11449 SmallVectorImpl<Expr*> &ConvertedArgs, 11450 bool AllowExplicit, 11451 bool IsListInitialization) { 11452 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11453 unsigned NumArgs = ArgsPtr.size(); 11454 Expr **Args = ArgsPtr.data(); 11455 11456 const FunctionProtoType *Proto 11457 = Constructor->getType()->getAs<FunctionProtoType>(); 11458 assert(Proto && "Constructor without a prototype?"); 11459 unsigned NumParams = Proto->getNumParams(); 11460 11461 // If too few arguments are available, we'll fill in the rest with defaults. 11462 if (NumArgs < NumParams) 11463 ConvertedArgs.reserve(NumParams); 11464 else 11465 ConvertedArgs.reserve(NumArgs); 11466 11467 VariadicCallType CallType = 11468 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11469 SmallVector<Expr *, 8> AllArgs; 11470 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11471 Proto, 0, 11472 llvm::makeArrayRef(Args, NumArgs), 11473 AllArgs, 11474 CallType, AllowExplicit, 11475 IsListInitialization); 11476 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11477 11478 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11479 11480 CheckConstructorCall(Constructor, 11481 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11482 Proto, Loc); 11483 11484 return Invalid; 11485 } 11486 11487 static inline bool 11488 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11489 const FunctionDecl *FnDecl) { 11490 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11491 if (isa<NamespaceDecl>(DC)) { 11492 return SemaRef.Diag(FnDecl->getLocation(), 11493 diag::err_operator_new_delete_declared_in_namespace) 11494 << FnDecl->getDeclName(); 11495 } 11496 11497 if (isa<TranslationUnitDecl>(DC) && 11498 FnDecl->getStorageClass() == SC_Static) { 11499 return SemaRef.Diag(FnDecl->getLocation(), 11500 diag::err_operator_new_delete_declared_static) 11501 << FnDecl->getDeclName(); 11502 } 11503 11504 return false; 11505 } 11506 11507 static inline bool 11508 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11509 CanQualType ExpectedResultType, 11510 CanQualType ExpectedFirstParamType, 11511 unsigned DependentParamTypeDiag, 11512 unsigned InvalidParamTypeDiag) { 11513 QualType ResultType = 11514 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11515 11516 // Check that the result type is not dependent. 11517 if (ResultType->isDependentType()) 11518 return SemaRef.Diag(FnDecl->getLocation(), 11519 diag::err_operator_new_delete_dependent_result_type) 11520 << FnDecl->getDeclName() << ExpectedResultType; 11521 11522 // Check that the result type is what we expect. 11523 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11524 return SemaRef.Diag(FnDecl->getLocation(), 11525 diag::err_operator_new_delete_invalid_result_type) 11526 << FnDecl->getDeclName() << ExpectedResultType; 11527 11528 // A function template must have at least 2 parameters. 11529 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11530 return SemaRef.Diag(FnDecl->getLocation(), 11531 diag::err_operator_new_delete_template_too_few_parameters) 11532 << FnDecl->getDeclName(); 11533 11534 // The function decl must have at least 1 parameter. 11535 if (FnDecl->getNumParams() == 0) 11536 return SemaRef.Diag(FnDecl->getLocation(), 11537 diag::err_operator_new_delete_too_few_parameters) 11538 << FnDecl->getDeclName(); 11539 11540 // Check the first parameter type is not dependent. 11541 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11542 if (FirstParamType->isDependentType()) 11543 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11544 << FnDecl->getDeclName() << ExpectedFirstParamType; 11545 11546 // Check that the first parameter type is what we expect. 11547 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11548 ExpectedFirstParamType) 11549 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11550 << FnDecl->getDeclName() << ExpectedFirstParamType; 11551 11552 return false; 11553 } 11554 11555 static bool 11556 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11557 // C++ [basic.stc.dynamic.allocation]p1: 11558 // A program is ill-formed if an allocation function is declared in a 11559 // namespace scope other than global scope or declared static in global 11560 // scope. 11561 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11562 return true; 11563 11564 CanQualType SizeTy = 11565 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11566 11567 // C++ [basic.stc.dynamic.allocation]p1: 11568 // The return type shall be void*. The first parameter shall have type 11569 // std::size_t. 11570 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11571 SizeTy, 11572 diag::err_operator_new_dependent_param_type, 11573 diag::err_operator_new_param_type)) 11574 return true; 11575 11576 // C++ [basic.stc.dynamic.allocation]p1: 11577 // The first parameter shall not have an associated default argument. 11578 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11579 return SemaRef.Diag(FnDecl->getLocation(), 11580 diag::err_operator_new_default_arg) 11581 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11582 11583 return false; 11584 } 11585 11586 static bool 11587 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11588 // C++ [basic.stc.dynamic.deallocation]p1: 11589 // A program is ill-formed if deallocation functions are declared in a 11590 // namespace scope other than global scope or declared static in global 11591 // scope. 11592 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11593 return true; 11594 11595 // C++ [basic.stc.dynamic.deallocation]p2: 11596 // Each deallocation function shall return void and its first parameter 11597 // shall be void*. 11598 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11599 SemaRef.Context.VoidPtrTy, 11600 diag::err_operator_delete_dependent_param_type, 11601 diag::err_operator_delete_param_type)) 11602 return true; 11603 11604 return false; 11605 } 11606 11607 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11608 /// of this overloaded operator is well-formed. If so, returns false; 11609 /// otherwise, emits appropriate diagnostics and returns true. 11610 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11611 assert(FnDecl && FnDecl->isOverloadedOperator() && 11612 "Expected an overloaded operator declaration"); 11613 11614 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11615 11616 // C++ [over.oper]p5: 11617 // The allocation and deallocation functions, operator new, 11618 // operator new[], operator delete and operator delete[], are 11619 // described completely in 3.7.3. The attributes and restrictions 11620 // found in the rest of this subclause do not apply to them unless 11621 // explicitly stated in 3.7.3. 11622 if (Op == OO_Delete || Op == OO_Array_Delete) 11623 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11624 11625 if (Op == OO_New || Op == OO_Array_New) 11626 return CheckOperatorNewDeclaration(*this, FnDecl); 11627 11628 // C++ [over.oper]p6: 11629 // An operator function shall either be a non-static member 11630 // function or be a non-member function and have at least one 11631 // parameter whose type is a class, a reference to a class, an 11632 // enumeration, or a reference to an enumeration. 11633 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11634 if (MethodDecl->isStatic()) 11635 return Diag(FnDecl->getLocation(), 11636 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11637 } else { 11638 bool ClassOrEnumParam = false; 11639 for (auto Param : FnDecl->params()) { 11640 QualType ParamType = Param->getType().getNonReferenceType(); 11641 if (ParamType->isDependentType() || ParamType->isRecordType() || 11642 ParamType->isEnumeralType()) { 11643 ClassOrEnumParam = true; 11644 break; 11645 } 11646 } 11647 11648 if (!ClassOrEnumParam) 11649 return Diag(FnDecl->getLocation(), 11650 diag::err_operator_overload_needs_class_or_enum) 11651 << FnDecl->getDeclName(); 11652 } 11653 11654 // C++ [over.oper]p8: 11655 // An operator function cannot have default arguments (8.3.6), 11656 // except where explicitly stated below. 11657 // 11658 // Only the function-call operator allows default arguments 11659 // (C++ [over.call]p1). 11660 if (Op != OO_Call) { 11661 for (auto Param : FnDecl->params()) { 11662 if (Param->hasDefaultArg()) 11663 return Diag(Param->getLocation(), 11664 diag::err_operator_overload_default_arg) 11665 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11666 } 11667 } 11668 11669 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11670 { false, false, false } 11671 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11672 , { Unary, Binary, MemberOnly } 11673 #include "clang/Basic/OperatorKinds.def" 11674 }; 11675 11676 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11677 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11678 bool MustBeMemberOperator = OperatorUses[Op][2]; 11679 11680 // C++ [over.oper]p8: 11681 // [...] Operator functions cannot have more or fewer parameters 11682 // than the number required for the corresponding operator, as 11683 // described in the rest of this subclause. 11684 unsigned NumParams = FnDecl->getNumParams() 11685 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11686 if (Op != OO_Call && 11687 ((NumParams == 1 && !CanBeUnaryOperator) || 11688 (NumParams == 2 && !CanBeBinaryOperator) || 11689 (NumParams < 1) || (NumParams > 2))) { 11690 // We have the wrong number of parameters. 11691 unsigned ErrorKind; 11692 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11693 ErrorKind = 2; // 2 -> unary or binary. 11694 } else if (CanBeUnaryOperator) { 11695 ErrorKind = 0; // 0 -> unary 11696 } else { 11697 assert(CanBeBinaryOperator && 11698 "All non-call overloaded operators are unary or binary!"); 11699 ErrorKind = 1; // 1 -> binary 11700 } 11701 11702 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11703 << FnDecl->getDeclName() << NumParams << ErrorKind; 11704 } 11705 11706 // Overloaded operators other than operator() cannot be variadic. 11707 if (Op != OO_Call && 11708 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11709 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11710 << FnDecl->getDeclName(); 11711 } 11712 11713 // Some operators must be non-static member functions. 11714 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11715 return Diag(FnDecl->getLocation(), 11716 diag::err_operator_overload_must_be_member) 11717 << FnDecl->getDeclName(); 11718 } 11719 11720 // C++ [over.inc]p1: 11721 // The user-defined function called operator++ implements the 11722 // prefix and postfix ++ operator. If this function is a member 11723 // function with no parameters, or a non-member function with one 11724 // parameter of class or enumeration type, it defines the prefix 11725 // increment operator ++ for objects of that type. If the function 11726 // is a member function with one parameter (which shall be of type 11727 // int) or a non-member function with two parameters (the second 11728 // of which shall be of type int), it defines the postfix 11729 // increment operator ++ for objects of that type. 11730 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11731 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11732 QualType ParamType = LastParam->getType(); 11733 11734 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11735 !ParamType->isDependentType()) 11736 return Diag(LastParam->getLocation(), 11737 diag::err_operator_overload_post_incdec_must_be_int) 11738 << LastParam->getType() << (Op == OO_MinusMinus); 11739 } 11740 11741 return false; 11742 } 11743 11744 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11745 /// of this literal operator function is well-formed. If so, returns 11746 /// false; otherwise, emits appropriate diagnostics and returns true. 11747 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11748 if (isa<CXXMethodDecl>(FnDecl)) { 11749 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11750 << FnDecl->getDeclName(); 11751 return true; 11752 } 11753 11754 if (FnDecl->isExternC()) { 11755 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11756 return true; 11757 } 11758 11759 bool Valid = false; 11760 11761 // This might be the definition of a literal operator template. 11762 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11763 // This might be a specialization of a literal operator template. 11764 if (!TpDecl) 11765 TpDecl = FnDecl->getPrimaryTemplate(); 11766 11767 // template <char...> type operator "" name() and 11768 // template <class T, T...> type operator "" name() are the only valid 11769 // template signatures, and the only valid signatures with no parameters. 11770 if (TpDecl) { 11771 if (FnDecl->param_size() == 0) { 11772 // Must have one or two template parameters 11773 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11774 if (Params->size() == 1) { 11775 NonTypeTemplateParmDecl *PmDecl = 11776 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11777 11778 // The template parameter must be a char parameter pack. 11779 if (PmDecl && PmDecl->isTemplateParameterPack() && 11780 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11781 Valid = true; 11782 } else if (Params->size() == 2) { 11783 TemplateTypeParmDecl *PmType = 11784 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11785 NonTypeTemplateParmDecl *PmArgs = 11786 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11787 11788 // The second template parameter must be a parameter pack with the 11789 // first template parameter as its type. 11790 if (PmType && PmArgs && 11791 !PmType->isTemplateParameterPack() && 11792 PmArgs->isTemplateParameterPack()) { 11793 const TemplateTypeParmType *TArgs = 11794 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11795 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11796 TArgs->getIndex() == PmType->getIndex()) { 11797 Valid = true; 11798 if (ActiveTemplateInstantiations.empty()) 11799 Diag(FnDecl->getLocation(), 11800 diag::ext_string_literal_operator_template); 11801 } 11802 } 11803 } 11804 } 11805 } else if (FnDecl->param_size()) { 11806 // Check the first parameter 11807 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11808 11809 QualType T = (*Param)->getType().getUnqualifiedType(); 11810 11811 // unsigned long long int, long double, and any character type are allowed 11812 // as the only parameters. 11813 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11814 Context.hasSameType(T, Context.LongDoubleTy) || 11815 Context.hasSameType(T, Context.CharTy) || 11816 Context.hasSameType(T, Context.WideCharTy) || 11817 Context.hasSameType(T, Context.Char16Ty) || 11818 Context.hasSameType(T, Context.Char32Ty)) { 11819 if (++Param == FnDecl->param_end()) 11820 Valid = true; 11821 goto FinishedParams; 11822 } 11823 11824 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11825 const PointerType *PT = T->getAs<PointerType>(); 11826 if (!PT) 11827 goto FinishedParams; 11828 T = PT->getPointeeType(); 11829 if (!T.isConstQualified() || T.isVolatileQualified()) 11830 goto FinishedParams; 11831 T = T.getUnqualifiedType(); 11832 11833 // Move on to the second parameter; 11834 ++Param; 11835 11836 // If there is no second parameter, the first must be a const char * 11837 if (Param == FnDecl->param_end()) { 11838 if (Context.hasSameType(T, Context.CharTy)) 11839 Valid = true; 11840 goto FinishedParams; 11841 } 11842 11843 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11844 // are allowed as the first parameter to a two-parameter function 11845 if (!(Context.hasSameType(T, Context.CharTy) || 11846 Context.hasSameType(T, Context.WideCharTy) || 11847 Context.hasSameType(T, Context.Char16Ty) || 11848 Context.hasSameType(T, Context.Char32Ty))) 11849 goto FinishedParams; 11850 11851 // The second and final parameter must be an std::size_t 11852 T = (*Param)->getType().getUnqualifiedType(); 11853 if (Context.hasSameType(T, Context.getSizeType()) && 11854 ++Param == FnDecl->param_end()) 11855 Valid = true; 11856 } 11857 11858 // FIXME: This diagnostic is absolutely terrible. 11859 FinishedParams: 11860 if (!Valid) { 11861 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11862 << FnDecl->getDeclName(); 11863 return true; 11864 } 11865 11866 // A parameter-declaration-clause containing a default argument is not 11867 // equivalent to any of the permitted forms. 11868 for (auto Param : FnDecl->params()) { 11869 if (Param->hasDefaultArg()) { 11870 Diag(Param->getDefaultArgRange().getBegin(), 11871 diag::err_literal_operator_default_argument) 11872 << Param->getDefaultArgRange(); 11873 break; 11874 } 11875 } 11876 11877 StringRef LiteralName 11878 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11879 if (LiteralName[0] != '_') { 11880 // C++11 [usrlit.suffix]p1: 11881 // Literal suffix identifiers that do not start with an underscore 11882 // are reserved for future standardization. 11883 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11884 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11885 } 11886 11887 return false; 11888 } 11889 11890 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11891 /// linkage specification, including the language and (if present) 11892 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11893 /// language string literal. LBraceLoc, if valid, provides the location of 11894 /// the '{' brace. Otherwise, this linkage specification does not 11895 /// have any braces. 11896 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11897 Expr *LangStr, 11898 SourceLocation LBraceLoc) { 11899 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11900 if (!Lit->isAscii()) { 11901 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11902 << LangStr->getSourceRange(); 11903 return nullptr; 11904 } 11905 11906 StringRef Lang = Lit->getString(); 11907 LinkageSpecDecl::LanguageIDs Language; 11908 if (Lang == "C") 11909 Language = LinkageSpecDecl::lang_c; 11910 else if (Lang == "C++") 11911 Language = LinkageSpecDecl::lang_cxx; 11912 else { 11913 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11914 << LangStr->getSourceRange(); 11915 return nullptr; 11916 } 11917 11918 // FIXME: Add all the various semantics of linkage specifications 11919 11920 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11921 LangStr->getExprLoc(), Language, 11922 LBraceLoc.isValid()); 11923 CurContext->addDecl(D); 11924 PushDeclContext(S, D); 11925 return D; 11926 } 11927 11928 /// ActOnFinishLinkageSpecification - Complete the definition of 11929 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11930 /// valid, it's the position of the closing '}' brace in a linkage 11931 /// specification that uses braces. 11932 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11933 Decl *LinkageSpec, 11934 SourceLocation RBraceLoc) { 11935 if (RBraceLoc.isValid()) { 11936 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11937 LSDecl->setRBraceLoc(RBraceLoc); 11938 } 11939 PopDeclContext(); 11940 return LinkageSpec; 11941 } 11942 11943 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11944 AttributeList *AttrList, 11945 SourceLocation SemiLoc) { 11946 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11947 // Attribute declarations appertain to empty declaration so we handle 11948 // them here. 11949 if (AttrList) 11950 ProcessDeclAttributeList(S, ED, AttrList); 11951 11952 CurContext->addDecl(ED); 11953 return ED; 11954 } 11955 11956 /// \brief Perform semantic analysis for the variable declaration that 11957 /// occurs within a C++ catch clause, returning the newly-created 11958 /// variable. 11959 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11960 TypeSourceInfo *TInfo, 11961 SourceLocation StartLoc, 11962 SourceLocation Loc, 11963 IdentifierInfo *Name) { 11964 bool Invalid = false; 11965 QualType ExDeclType = TInfo->getType(); 11966 11967 // Arrays and functions decay. 11968 if (ExDeclType->isArrayType()) 11969 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11970 else if (ExDeclType->isFunctionType()) 11971 ExDeclType = Context.getPointerType(ExDeclType); 11972 11973 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11974 // The exception-declaration shall not denote a pointer or reference to an 11975 // incomplete type, other than [cv] void*. 11976 // N2844 forbids rvalue references. 11977 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11978 Diag(Loc, diag::err_catch_rvalue_ref); 11979 Invalid = true; 11980 } 11981 11982 QualType BaseType = ExDeclType; 11983 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11984 unsigned DK = diag::err_catch_incomplete; 11985 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11986 BaseType = Ptr->getPointeeType(); 11987 Mode = 1; 11988 DK = diag::err_catch_incomplete_ptr; 11989 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11990 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11991 BaseType = Ref->getPointeeType(); 11992 Mode = 2; 11993 DK = diag::err_catch_incomplete_ref; 11994 } 11995 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11996 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11997 Invalid = true; 11998 11999 if (!Invalid && !ExDeclType->isDependentType() && 12000 RequireNonAbstractType(Loc, ExDeclType, 12001 diag::err_abstract_type_in_decl, 12002 AbstractVariableType)) 12003 Invalid = true; 12004 12005 // Only the non-fragile NeXT runtime currently supports C++ catches 12006 // of ObjC types, and no runtime supports catching ObjC types by value. 12007 if (!Invalid && getLangOpts().ObjC1) { 12008 QualType T = ExDeclType; 12009 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 12010 T = RT->getPointeeType(); 12011 12012 if (T->isObjCObjectType()) { 12013 Diag(Loc, diag::err_objc_object_catch); 12014 Invalid = true; 12015 } else if (T->isObjCObjectPointerType()) { 12016 // FIXME: should this be a test for macosx-fragile specifically? 12017 if (getLangOpts().ObjCRuntime.isFragile()) 12018 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 12019 } 12020 } 12021 12022 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 12023 ExDeclType, TInfo, SC_None); 12024 ExDecl->setExceptionVariable(true); 12025 12026 // In ARC, infer 'retaining' for variables of retainable type. 12027 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 12028 Invalid = true; 12029 12030 if (!Invalid && !ExDeclType->isDependentType()) { 12031 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 12032 // Insulate this from anything else we might currently be parsing. 12033 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 12034 12035 // C++ [except.handle]p16: 12036 // The object declared in an exception-declaration or, if the 12037 // exception-declaration does not specify a name, a temporary (12.2) is 12038 // copy-initialized (8.5) from the exception object. [...] 12039 // The object is destroyed when the handler exits, after the destruction 12040 // of any automatic objects initialized within the handler. 12041 // 12042 // We just pretend to initialize the object with itself, then make sure 12043 // it can be destroyed later. 12044 QualType initType = Context.getExceptionObjectType(ExDeclType); 12045 12046 InitializedEntity entity = 12047 InitializedEntity::InitializeVariable(ExDecl); 12048 InitializationKind initKind = 12049 InitializationKind::CreateCopy(Loc, SourceLocation()); 12050 12051 Expr *opaqueValue = 12052 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 12053 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 12054 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 12055 if (result.isInvalid()) 12056 Invalid = true; 12057 else { 12058 // If the constructor used was non-trivial, set this as the 12059 // "initializer". 12060 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 12061 if (!construct->getConstructor()->isTrivial()) { 12062 Expr *init = MaybeCreateExprWithCleanups(construct); 12063 ExDecl->setInit(init); 12064 } 12065 12066 // And make sure it's destructable. 12067 FinalizeVarWithDestructor(ExDecl, recordType); 12068 } 12069 } 12070 } 12071 12072 if (Invalid) 12073 ExDecl->setInvalidDecl(); 12074 12075 return ExDecl; 12076 } 12077 12078 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 12079 /// handler. 12080 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 12081 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12082 bool Invalid = D.isInvalidType(); 12083 12084 // Check for unexpanded parameter packs. 12085 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12086 UPPC_ExceptionType)) { 12087 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12088 D.getIdentifierLoc()); 12089 Invalid = true; 12090 } 12091 12092 IdentifierInfo *II = D.getIdentifier(); 12093 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 12094 LookupOrdinaryName, 12095 ForRedeclaration)) { 12096 // The scope should be freshly made just for us. There is just no way 12097 // it contains any previous declaration, except for function parameters in 12098 // a function-try-block's catch statement. 12099 assert(!S->isDeclScope(PrevDecl)); 12100 if (isDeclInScope(PrevDecl, CurContext, S)) { 12101 Diag(D.getIdentifierLoc(), diag::err_redefinition) 12102 << D.getIdentifier(); 12103 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12104 Invalid = true; 12105 } else if (PrevDecl->isTemplateParameter()) 12106 // Maybe we will complain about the shadowed template parameter. 12107 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12108 } 12109 12110 if (D.getCXXScopeSpec().isSet() && !Invalid) { 12111 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 12112 << D.getCXXScopeSpec().getRange(); 12113 Invalid = true; 12114 } 12115 12116 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 12117 D.getLocStart(), 12118 D.getIdentifierLoc(), 12119 D.getIdentifier()); 12120 if (Invalid) 12121 ExDecl->setInvalidDecl(); 12122 12123 // Add the exception declaration into this scope. 12124 if (II) 12125 PushOnScopeChains(ExDecl, S); 12126 else 12127 CurContext->addDecl(ExDecl); 12128 12129 ProcessDeclAttributes(S, ExDecl, D); 12130 return ExDecl; 12131 } 12132 12133 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12134 Expr *AssertExpr, 12135 Expr *AssertMessageExpr, 12136 SourceLocation RParenLoc) { 12137 StringLiteral *AssertMessage = 12138 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 12139 12140 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 12141 return nullptr; 12142 12143 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 12144 AssertMessage, RParenLoc, false); 12145 } 12146 12147 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12148 Expr *AssertExpr, 12149 StringLiteral *AssertMessage, 12150 SourceLocation RParenLoc, 12151 bool Failed) { 12152 assert(AssertExpr != nullptr && "Expected non-null condition"); 12153 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 12154 !Failed) { 12155 // In a static_assert-declaration, the constant-expression shall be a 12156 // constant expression that can be contextually converted to bool. 12157 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 12158 if (Converted.isInvalid()) 12159 Failed = true; 12160 12161 llvm::APSInt Cond; 12162 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 12163 diag::err_static_assert_expression_is_not_constant, 12164 /*AllowFold=*/false).isInvalid()) 12165 Failed = true; 12166 12167 if (!Failed && !Cond) { 12168 SmallString<256> MsgBuffer; 12169 llvm::raw_svector_ostream Msg(MsgBuffer); 12170 if (AssertMessage) 12171 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12172 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12173 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12174 Failed = true; 12175 } 12176 } 12177 12178 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12179 AssertExpr, AssertMessage, RParenLoc, 12180 Failed); 12181 12182 CurContext->addDecl(Decl); 12183 return Decl; 12184 } 12185 12186 /// \brief Perform semantic analysis of the given friend type declaration. 12187 /// 12188 /// \returns A friend declaration that. 12189 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12190 SourceLocation FriendLoc, 12191 TypeSourceInfo *TSInfo) { 12192 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12193 12194 QualType T = TSInfo->getType(); 12195 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12196 12197 // C++03 [class.friend]p2: 12198 // An elaborated-type-specifier shall be used in a friend declaration 12199 // for a class.* 12200 // 12201 // * The class-key of the elaborated-type-specifier is required. 12202 if (!ActiveTemplateInstantiations.empty()) { 12203 // Do not complain about the form of friend template types during 12204 // template instantiation; we will already have complained when the 12205 // template was declared. 12206 } else { 12207 if (!T->isElaboratedTypeSpecifier()) { 12208 // If we evaluated the type to a record type, suggest putting 12209 // a tag in front. 12210 if (const RecordType *RT = T->getAs<RecordType>()) { 12211 RecordDecl *RD = RT->getDecl(); 12212 12213 SmallString<16> InsertionText(" "); 12214 InsertionText += RD->getKindName(); 12215 12216 Diag(TypeRange.getBegin(), 12217 getLangOpts().CPlusPlus11 ? 12218 diag::warn_cxx98_compat_unelaborated_friend_type : 12219 diag::ext_unelaborated_friend_type) 12220 << (unsigned) RD->getTagKind() 12221 << T 12222 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 12223 InsertionText); 12224 } else { 12225 Diag(FriendLoc, 12226 getLangOpts().CPlusPlus11 ? 12227 diag::warn_cxx98_compat_nonclass_type_friend : 12228 diag::ext_nonclass_type_friend) 12229 << T 12230 << TypeRange; 12231 } 12232 } else if (T->getAs<EnumType>()) { 12233 Diag(FriendLoc, 12234 getLangOpts().CPlusPlus11 ? 12235 diag::warn_cxx98_compat_enum_friend : 12236 diag::ext_enum_friend) 12237 << T 12238 << TypeRange; 12239 } 12240 12241 // C++11 [class.friend]p3: 12242 // A friend declaration that does not declare a function shall have one 12243 // of the following forms: 12244 // friend elaborated-type-specifier ; 12245 // friend simple-type-specifier ; 12246 // friend typename-specifier ; 12247 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12248 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12249 } 12250 12251 // If the type specifier in a friend declaration designates a (possibly 12252 // cv-qualified) class type, that class is declared as a friend; otherwise, 12253 // the friend declaration is ignored. 12254 return FriendDecl::Create(Context, CurContext, 12255 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12256 FriendLoc); 12257 } 12258 12259 /// Handle a friend tag declaration where the scope specifier was 12260 /// templated. 12261 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12262 unsigned TagSpec, SourceLocation TagLoc, 12263 CXXScopeSpec &SS, 12264 IdentifierInfo *Name, 12265 SourceLocation NameLoc, 12266 AttributeList *Attr, 12267 MultiTemplateParamsArg TempParamLists) { 12268 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12269 12270 bool isExplicitSpecialization = false; 12271 bool Invalid = false; 12272 12273 if (TemplateParameterList *TemplateParams = 12274 MatchTemplateParametersToScopeSpecifier( 12275 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12276 isExplicitSpecialization, Invalid)) { 12277 if (TemplateParams->size() > 0) { 12278 // This is a declaration of a class template. 12279 if (Invalid) 12280 return nullptr; 12281 12282 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12283 NameLoc, Attr, TemplateParams, AS_public, 12284 /*ModulePrivateLoc=*/SourceLocation(), 12285 FriendLoc, TempParamLists.size() - 1, 12286 TempParamLists.data()).get(); 12287 } else { 12288 // The "template<>" header is extraneous. 12289 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12290 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12291 isExplicitSpecialization = true; 12292 } 12293 } 12294 12295 if (Invalid) return nullptr; 12296 12297 bool isAllExplicitSpecializations = true; 12298 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12299 if (TempParamLists[I]->size()) { 12300 isAllExplicitSpecializations = false; 12301 break; 12302 } 12303 } 12304 12305 // FIXME: don't ignore attributes. 12306 12307 // If it's explicit specializations all the way down, just forget 12308 // about the template header and build an appropriate non-templated 12309 // friend. TODO: for source fidelity, remember the headers. 12310 if (isAllExplicitSpecializations) { 12311 if (SS.isEmpty()) { 12312 bool Owned = false; 12313 bool IsDependent = false; 12314 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12315 Attr, AS_public, 12316 /*ModulePrivateLoc=*/SourceLocation(), 12317 MultiTemplateParamsArg(), Owned, IsDependent, 12318 /*ScopedEnumKWLoc=*/SourceLocation(), 12319 /*ScopedEnumUsesClassTag=*/false, 12320 /*UnderlyingType=*/TypeResult(), 12321 /*IsTypeSpecifier=*/false); 12322 } 12323 12324 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12325 ElaboratedTypeKeyword Keyword 12326 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12327 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12328 *Name, NameLoc); 12329 if (T.isNull()) 12330 return nullptr; 12331 12332 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12333 if (isa<DependentNameType>(T)) { 12334 DependentNameTypeLoc TL = 12335 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12336 TL.setElaboratedKeywordLoc(TagLoc); 12337 TL.setQualifierLoc(QualifierLoc); 12338 TL.setNameLoc(NameLoc); 12339 } else { 12340 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12341 TL.setElaboratedKeywordLoc(TagLoc); 12342 TL.setQualifierLoc(QualifierLoc); 12343 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12344 } 12345 12346 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12347 TSI, FriendLoc, TempParamLists); 12348 Friend->setAccess(AS_public); 12349 CurContext->addDecl(Friend); 12350 return Friend; 12351 } 12352 12353 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12354 12355 12356 12357 // Handle the case of a templated-scope friend class. e.g. 12358 // template <class T> class A<T>::B; 12359 // FIXME: we don't support these right now. 12360 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12361 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12362 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12363 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12364 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12365 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12366 TL.setElaboratedKeywordLoc(TagLoc); 12367 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12368 TL.setNameLoc(NameLoc); 12369 12370 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12371 TSI, FriendLoc, TempParamLists); 12372 Friend->setAccess(AS_public); 12373 Friend->setUnsupportedFriend(true); 12374 CurContext->addDecl(Friend); 12375 return Friend; 12376 } 12377 12378 12379 /// Handle a friend type declaration. This works in tandem with 12380 /// ActOnTag. 12381 /// 12382 /// Notes on friend class templates: 12383 /// 12384 /// We generally treat friend class declarations as if they were 12385 /// declaring a class. So, for example, the elaborated type specifier 12386 /// in a friend declaration is required to obey the restrictions of a 12387 /// class-head (i.e. no typedefs in the scope chain), template 12388 /// parameters are required to match up with simple template-ids, &c. 12389 /// However, unlike when declaring a template specialization, it's 12390 /// okay to refer to a template specialization without an empty 12391 /// template parameter declaration, e.g. 12392 /// friend class A<T>::B<unsigned>; 12393 /// We permit this as a special case; if there are any template 12394 /// parameters present at all, require proper matching, i.e. 12395 /// template <> template \<class T> friend class A<int>::B; 12396 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12397 MultiTemplateParamsArg TempParams) { 12398 SourceLocation Loc = DS.getLocStart(); 12399 12400 assert(DS.isFriendSpecified()); 12401 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12402 12403 // Try to convert the decl specifier to a type. This works for 12404 // friend templates because ActOnTag never produces a ClassTemplateDecl 12405 // for a TUK_Friend. 12406 Declarator TheDeclarator(DS, Declarator::MemberContext); 12407 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12408 QualType T = TSI->getType(); 12409 if (TheDeclarator.isInvalidType()) 12410 return nullptr; 12411 12412 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12413 return nullptr; 12414 12415 // This is definitely an error in C++98. It's probably meant to 12416 // be forbidden in C++0x, too, but the specification is just 12417 // poorly written. 12418 // 12419 // The problem is with declarations like the following: 12420 // template <T> friend A<T>::foo; 12421 // where deciding whether a class C is a friend or not now hinges 12422 // on whether there exists an instantiation of A that causes 12423 // 'foo' to equal C. There are restrictions on class-heads 12424 // (which we declare (by fiat) elaborated friend declarations to 12425 // be) that makes this tractable. 12426 // 12427 // FIXME: handle "template <> friend class A<T>;", which 12428 // is possibly well-formed? Who even knows? 12429 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12430 Diag(Loc, diag::err_tagless_friend_type_template) 12431 << DS.getSourceRange(); 12432 return nullptr; 12433 } 12434 12435 // C++98 [class.friend]p1: A friend of a class is a function 12436 // or class that is not a member of the class . . . 12437 // This is fixed in DR77, which just barely didn't make the C++03 12438 // deadline. It's also a very silly restriction that seriously 12439 // affects inner classes and which nobody else seems to implement; 12440 // thus we never diagnose it, not even in -pedantic. 12441 // 12442 // But note that we could warn about it: it's always useless to 12443 // friend one of your own members (it's not, however, worthless to 12444 // friend a member of an arbitrary specialization of your template). 12445 12446 Decl *D; 12447 if (unsigned NumTempParamLists = TempParams.size()) 12448 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12449 NumTempParamLists, 12450 TempParams.data(), 12451 TSI, 12452 DS.getFriendSpecLoc()); 12453 else 12454 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12455 12456 if (!D) 12457 return nullptr; 12458 12459 D->setAccess(AS_public); 12460 CurContext->addDecl(D); 12461 12462 return D; 12463 } 12464 12465 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12466 MultiTemplateParamsArg TemplateParams) { 12467 const DeclSpec &DS = D.getDeclSpec(); 12468 12469 assert(DS.isFriendSpecified()); 12470 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12471 12472 SourceLocation Loc = D.getIdentifierLoc(); 12473 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12474 12475 // C++ [class.friend]p1 12476 // A friend of a class is a function or class.... 12477 // Note that this sees through typedefs, which is intended. 12478 // It *doesn't* see through dependent types, which is correct 12479 // according to [temp.arg.type]p3: 12480 // If a declaration acquires a function type through a 12481 // type dependent on a template-parameter and this causes 12482 // a declaration that does not use the syntactic form of a 12483 // function declarator to have a function type, the program 12484 // is ill-formed. 12485 if (!TInfo->getType()->isFunctionType()) { 12486 Diag(Loc, diag::err_unexpected_friend); 12487 12488 // It might be worthwhile to try to recover by creating an 12489 // appropriate declaration. 12490 return nullptr; 12491 } 12492 12493 // C++ [namespace.memdef]p3 12494 // - If a friend declaration in a non-local class first declares a 12495 // class or function, the friend class or function is a member 12496 // of the innermost enclosing namespace. 12497 // - The name of the friend is not found by simple name lookup 12498 // until a matching declaration is provided in that namespace 12499 // scope (either before or after the class declaration granting 12500 // friendship). 12501 // - If a friend function is called, its name may be found by the 12502 // name lookup that considers functions from namespaces and 12503 // classes associated with the types of the function arguments. 12504 // - When looking for a prior declaration of a class or a function 12505 // declared as a friend, scopes outside the innermost enclosing 12506 // namespace scope are not considered. 12507 12508 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12509 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12510 DeclarationName Name = NameInfo.getName(); 12511 assert(Name); 12512 12513 // Check for unexpanded parameter packs. 12514 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12515 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12516 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12517 return nullptr; 12518 12519 // The context we found the declaration in, or in which we should 12520 // create the declaration. 12521 DeclContext *DC; 12522 Scope *DCScope = S; 12523 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12524 ForRedeclaration); 12525 12526 // There are five cases here. 12527 // - There's no scope specifier and we're in a local class. Only look 12528 // for functions declared in the immediately-enclosing block scope. 12529 // We recover from invalid scope qualifiers as if they just weren't there. 12530 FunctionDecl *FunctionContainingLocalClass = nullptr; 12531 if ((SS.isInvalid() || !SS.isSet()) && 12532 (FunctionContainingLocalClass = 12533 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12534 // C++11 [class.friend]p11: 12535 // If a friend declaration appears in a local class and the name 12536 // specified is an unqualified name, a prior declaration is 12537 // looked up without considering scopes that are outside the 12538 // innermost enclosing non-class scope. For a friend function 12539 // declaration, if there is no prior declaration, the program is 12540 // ill-formed. 12541 12542 // Find the innermost enclosing non-class scope. This is the block 12543 // scope containing the local class definition (or for a nested class, 12544 // the outer local class). 12545 DCScope = S->getFnParent(); 12546 12547 // Look up the function name in the scope. 12548 Previous.clear(LookupLocalFriendName); 12549 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12550 12551 if (!Previous.empty()) { 12552 // All possible previous declarations must have the same context: 12553 // either they were declared at block scope or they are members of 12554 // one of the enclosing local classes. 12555 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12556 } else { 12557 // This is ill-formed, but provide the context that we would have 12558 // declared the function in, if we were permitted to, for error recovery. 12559 DC = FunctionContainingLocalClass; 12560 } 12561 adjustContextForLocalExternDecl(DC); 12562 12563 // C++ [class.friend]p6: 12564 // A function can be defined in a friend declaration of a class if and 12565 // only if the class is a non-local class (9.8), the function name is 12566 // unqualified, and the function has namespace scope. 12567 if (D.isFunctionDefinition()) { 12568 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12569 } 12570 12571 // - There's no scope specifier, in which case we just go to the 12572 // appropriate scope and look for a function or function template 12573 // there as appropriate. 12574 } else if (SS.isInvalid() || !SS.isSet()) { 12575 // C++11 [namespace.memdef]p3: 12576 // If the name in a friend declaration is neither qualified nor 12577 // a template-id and the declaration is a function or an 12578 // elaborated-type-specifier, the lookup to determine whether 12579 // the entity has been previously declared shall not consider 12580 // any scopes outside the innermost enclosing namespace. 12581 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12582 12583 // Find the appropriate context according to the above. 12584 DC = CurContext; 12585 12586 // Skip class contexts. If someone can cite chapter and verse 12587 // for this behavior, that would be nice --- it's what GCC and 12588 // EDG do, and it seems like a reasonable intent, but the spec 12589 // really only says that checks for unqualified existing 12590 // declarations should stop at the nearest enclosing namespace, 12591 // not that they should only consider the nearest enclosing 12592 // namespace. 12593 while (DC->isRecord()) 12594 DC = DC->getParent(); 12595 12596 DeclContext *LookupDC = DC; 12597 while (LookupDC->isTransparentContext()) 12598 LookupDC = LookupDC->getParent(); 12599 12600 while (true) { 12601 LookupQualifiedName(Previous, LookupDC); 12602 12603 if (!Previous.empty()) { 12604 DC = LookupDC; 12605 break; 12606 } 12607 12608 if (isTemplateId) { 12609 if (isa<TranslationUnitDecl>(LookupDC)) break; 12610 } else { 12611 if (LookupDC->isFileContext()) break; 12612 } 12613 LookupDC = LookupDC->getParent(); 12614 } 12615 12616 DCScope = getScopeForDeclContext(S, DC); 12617 12618 // - There's a non-dependent scope specifier, in which case we 12619 // compute it and do a previous lookup there for a function 12620 // or function template. 12621 } else if (!SS.getScopeRep()->isDependent()) { 12622 DC = computeDeclContext(SS); 12623 if (!DC) return nullptr; 12624 12625 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12626 12627 LookupQualifiedName(Previous, DC); 12628 12629 // Ignore things found implicitly in the wrong scope. 12630 // TODO: better diagnostics for this case. Suggesting the right 12631 // qualified scope would be nice... 12632 LookupResult::Filter F = Previous.makeFilter(); 12633 while (F.hasNext()) { 12634 NamedDecl *D = F.next(); 12635 if (!DC->InEnclosingNamespaceSetOf( 12636 D->getDeclContext()->getRedeclContext())) 12637 F.erase(); 12638 } 12639 F.done(); 12640 12641 if (Previous.empty()) { 12642 D.setInvalidType(); 12643 Diag(Loc, diag::err_qualified_friend_not_found) 12644 << Name << TInfo->getType(); 12645 return nullptr; 12646 } 12647 12648 // C++ [class.friend]p1: A friend of a class is a function or 12649 // class that is not a member of the class . . . 12650 if (DC->Equals(CurContext)) 12651 Diag(DS.getFriendSpecLoc(), 12652 getLangOpts().CPlusPlus11 ? 12653 diag::warn_cxx98_compat_friend_is_member : 12654 diag::err_friend_is_member); 12655 12656 if (D.isFunctionDefinition()) { 12657 // C++ [class.friend]p6: 12658 // A function can be defined in a friend declaration of a class if and 12659 // only if the class is a non-local class (9.8), the function name is 12660 // unqualified, and the function has namespace scope. 12661 SemaDiagnosticBuilder DB 12662 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12663 12664 DB << SS.getScopeRep(); 12665 if (DC->isFileContext()) 12666 DB << FixItHint::CreateRemoval(SS.getRange()); 12667 SS.clear(); 12668 } 12669 12670 // - There's a scope specifier that does not match any template 12671 // parameter lists, in which case we use some arbitrary context, 12672 // create a method or method template, and wait for instantiation. 12673 // - There's a scope specifier that does match some template 12674 // parameter lists, which we don't handle right now. 12675 } else { 12676 if (D.isFunctionDefinition()) { 12677 // C++ [class.friend]p6: 12678 // A function can be defined in a friend declaration of a class if and 12679 // only if the class is a non-local class (9.8), the function name is 12680 // unqualified, and the function has namespace scope. 12681 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12682 << SS.getScopeRep(); 12683 } 12684 12685 DC = CurContext; 12686 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12687 } 12688 12689 if (!DC->isRecord()) { 12690 // This implies that it has to be an operator or function. 12691 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12692 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12693 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12694 Diag(Loc, diag::err_introducing_special_friend) << 12695 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12696 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12697 return nullptr; 12698 } 12699 } 12700 12701 // FIXME: This is an egregious hack to cope with cases where the scope stack 12702 // does not contain the declaration context, i.e., in an out-of-line 12703 // definition of a class. 12704 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12705 if (!DCScope) { 12706 FakeDCScope.setEntity(DC); 12707 DCScope = &FakeDCScope; 12708 } 12709 12710 bool AddToScope = true; 12711 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12712 TemplateParams, AddToScope); 12713 if (!ND) return nullptr; 12714 12715 assert(ND->getLexicalDeclContext() == CurContext); 12716 12717 // If we performed typo correction, we might have added a scope specifier 12718 // and changed the decl context. 12719 DC = ND->getDeclContext(); 12720 12721 // Add the function declaration to the appropriate lookup tables, 12722 // adjusting the redeclarations list as necessary. We don't 12723 // want to do this yet if the friending class is dependent. 12724 // 12725 // Also update the scope-based lookup if the target context's 12726 // lookup context is in lexical scope. 12727 if (!CurContext->isDependentContext()) { 12728 DC = DC->getRedeclContext(); 12729 DC->makeDeclVisibleInContext(ND); 12730 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12731 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12732 } 12733 12734 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12735 D.getIdentifierLoc(), ND, 12736 DS.getFriendSpecLoc()); 12737 FrD->setAccess(AS_public); 12738 CurContext->addDecl(FrD); 12739 12740 if (ND->isInvalidDecl()) { 12741 FrD->setInvalidDecl(); 12742 } else { 12743 if (DC->isRecord()) CheckFriendAccess(ND); 12744 12745 FunctionDecl *FD; 12746 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12747 FD = FTD->getTemplatedDecl(); 12748 else 12749 FD = cast<FunctionDecl>(ND); 12750 12751 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12752 // default argument expression, that declaration shall be a definition 12753 // and shall be the only declaration of the function or function 12754 // template in the translation unit. 12755 if (functionDeclHasDefaultArgument(FD)) { 12756 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12757 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12758 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12759 } else if (!D.isFunctionDefinition()) 12760 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12761 } 12762 12763 // Mark templated-scope function declarations as unsupported. 12764 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12765 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12766 << SS.getScopeRep() << SS.getRange() 12767 << cast<CXXRecordDecl>(CurContext); 12768 FrD->setUnsupportedFriend(true); 12769 } 12770 } 12771 12772 return ND; 12773 } 12774 12775 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12776 AdjustDeclIfTemplate(Dcl); 12777 12778 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12779 if (!Fn) { 12780 Diag(DelLoc, diag::err_deleted_non_function); 12781 return; 12782 } 12783 12784 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12785 // Don't consider the implicit declaration we generate for explicit 12786 // specializations. FIXME: Do not generate these implicit declarations. 12787 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12788 Prev->getPreviousDecl()) && 12789 !Prev->isDefined()) { 12790 Diag(DelLoc, diag::err_deleted_decl_not_first); 12791 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12792 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12793 : diag::note_previous_declaration); 12794 } 12795 // If the declaration wasn't the first, we delete the function anyway for 12796 // recovery. 12797 Fn = Fn->getCanonicalDecl(); 12798 } 12799 12800 // dllimport/dllexport cannot be deleted. 12801 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12802 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12803 Fn->setInvalidDecl(); 12804 } 12805 12806 if (Fn->isDeleted()) 12807 return; 12808 12809 // See if we're deleting a function which is already known to override a 12810 // non-deleted virtual function. 12811 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12812 bool IssuedDiagnostic = false; 12813 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12814 E = MD->end_overridden_methods(); 12815 I != E; ++I) { 12816 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12817 if (!IssuedDiagnostic) { 12818 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12819 IssuedDiagnostic = true; 12820 } 12821 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12822 } 12823 } 12824 } 12825 12826 // C++11 [basic.start.main]p3: 12827 // A program that defines main as deleted [...] is ill-formed. 12828 if (Fn->isMain()) 12829 Diag(DelLoc, diag::err_deleted_main); 12830 12831 Fn->setDeletedAsWritten(); 12832 } 12833 12834 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12835 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12836 12837 if (MD) { 12838 if (MD->getParent()->isDependentType()) { 12839 MD->setDefaulted(); 12840 MD->setExplicitlyDefaulted(); 12841 return; 12842 } 12843 12844 CXXSpecialMember Member = getSpecialMember(MD); 12845 if (Member == CXXInvalid) { 12846 if (!MD->isInvalidDecl()) 12847 Diag(DefaultLoc, diag::err_default_special_members); 12848 return; 12849 } 12850 12851 MD->setDefaulted(); 12852 MD->setExplicitlyDefaulted(); 12853 12854 // If this definition appears within the record, do the checking when 12855 // the record is complete. 12856 const FunctionDecl *Primary = MD; 12857 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12858 // Find the uninstantiated declaration that actually had the '= default' 12859 // on it. 12860 Pattern->isDefined(Primary); 12861 12862 // If the method was defaulted on its first declaration, we will have 12863 // already performed the checking in CheckCompletedCXXClass. Such a 12864 // declaration doesn't trigger an implicit definition. 12865 if (Primary == Primary->getCanonicalDecl()) 12866 return; 12867 12868 CheckExplicitlyDefaultedSpecialMember(MD); 12869 12870 if (MD->isInvalidDecl()) 12871 return; 12872 12873 switch (Member) { 12874 case CXXDefaultConstructor: 12875 DefineImplicitDefaultConstructor(DefaultLoc, 12876 cast<CXXConstructorDecl>(MD)); 12877 break; 12878 case CXXCopyConstructor: 12879 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12880 break; 12881 case CXXCopyAssignment: 12882 DefineImplicitCopyAssignment(DefaultLoc, MD); 12883 break; 12884 case CXXDestructor: 12885 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12886 break; 12887 case CXXMoveConstructor: 12888 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12889 break; 12890 case CXXMoveAssignment: 12891 DefineImplicitMoveAssignment(DefaultLoc, MD); 12892 break; 12893 case CXXInvalid: 12894 llvm_unreachable("Invalid special member."); 12895 } 12896 } else { 12897 Diag(DefaultLoc, diag::err_default_special_members); 12898 } 12899 } 12900 12901 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12902 for (Stmt *SubStmt : S->children()) { 12903 if (!SubStmt) 12904 continue; 12905 if (isa<ReturnStmt>(SubStmt)) 12906 Self.Diag(SubStmt->getLocStart(), 12907 diag::err_return_in_constructor_handler); 12908 if (!isa<Expr>(SubStmt)) 12909 SearchForReturnInStmt(Self, SubStmt); 12910 } 12911 } 12912 12913 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12914 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12915 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12916 SearchForReturnInStmt(*this, Handler); 12917 } 12918 } 12919 12920 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12921 const CXXMethodDecl *Old) { 12922 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12923 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12924 12925 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12926 12927 // If the calling conventions match, everything is fine 12928 if (NewCC == OldCC) 12929 return false; 12930 12931 // If the calling conventions mismatch because the new function is static, 12932 // suppress the calling convention mismatch error; the error about static 12933 // function override (err_static_overrides_virtual from 12934 // Sema::CheckFunctionDeclaration) is more clear. 12935 if (New->getStorageClass() == SC_Static) 12936 return false; 12937 12938 Diag(New->getLocation(), 12939 diag::err_conflicting_overriding_cc_attributes) 12940 << New->getDeclName() << New->getType() << Old->getType(); 12941 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12942 return true; 12943 } 12944 12945 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12946 const CXXMethodDecl *Old) { 12947 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12948 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12949 12950 if (Context.hasSameType(NewTy, OldTy) || 12951 NewTy->isDependentType() || OldTy->isDependentType()) 12952 return false; 12953 12954 // Check if the return types are covariant 12955 QualType NewClassTy, OldClassTy; 12956 12957 /// Both types must be pointers or references to classes. 12958 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12959 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12960 NewClassTy = NewPT->getPointeeType(); 12961 OldClassTy = OldPT->getPointeeType(); 12962 } 12963 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12964 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12965 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12966 NewClassTy = NewRT->getPointeeType(); 12967 OldClassTy = OldRT->getPointeeType(); 12968 } 12969 } 12970 } 12971 12972 // The return types aren't either both pointers or references to a class type. 12973 if (NewClassTy.isNull()) { 12974 Diag(New->getLocation(), 12975 diag::err_different_return_type_for_overriding_virtual_function) 12976 << New->getDeclName() << NewTy << OldTy 12977 << New->getReturnTypeSourceRange(); 12978 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12979 << Old->getReturnTypeSourceRange(); 12980 12981 return true; 12982 } 12983 12984 // C++ [class.virtual]p6: 12985 // If the return type of D::f differs from the return type of B::f, the 12986 // class type in the return type of D::f shall be complete at the point of 12987 // declaration of D::f or shall be the class type D. 12988 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12989 if (!RT->isBeingDefined() && 12990 RequireCompleteType(New->getLocation(), NewClassTy, 12991 diag::err_covariant_return_incomplete, 12992 New->getDeclName())) 12993 return true; 12994 } 12995 12996 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12997 // Check if the new class derives from the old class. 12998 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12999 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 13000 << New->getDeclName() << NewTy << OldTy 13001 << New->getReturnTypeSourceRange(); 13002 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13003 << Old->getReturnTypeSourceRange(); 13004 return true; 13005 } 13006 13007 // Check if we the conversion from derived to base is valid. 13008 if (CheckDerivedToBaseConversion( 13009 NewClassTy, OldClassTy, 13010 diag::err_covariant_return_inaccessible_base, 13011 diag::err_covariant_return_ambiguous_derived_to_base_conv, 13012 New->getLocation(), New->getReturnTypeSourceRange(), 13013 New->getDeclName(), nullptr)) { 13014 // FIXME: this note won't trigger for delayed access control 13015 // diagnostics, and it's impossible to get an undelayed error 13016 // here from access control during the original parse because 13017 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 13018 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13019 << Old->getReturnTypeSourceRange(); 13020 return true; 13021 } 13022 } 13023 13024 // The qualifiers of the return types must be the same. 13025 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 13026 Diag(New->getLocation(), 13027 diag::err_covariant_return_type_different_qualifications) 13028 << New->getDeclName() << NewTy << OldTy 13029 << New->getReturnTypeSourceRange(); 13030 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13031 << Old->getReturnTypeSourceRange(); 13032 return true; 13033 }; 13034 13035 13036 // The new class type must have the same or less qualifiers as the old type. 13037 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 13038 Diag(New->getLocation(), 13039 diag::err_covariant_return_type_class_type_more_qualified) 13040 << New->getDeclName() << NewTy << OldTy 13041 << New->getReturnTypeSourceRange(); 13042 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13043 << Old->getReturnTypeSourceRange(); 13044 return true; 13045 }; 13046 13047 return false; 13048 } 13049 13050 /// \brief Mark the given method pure. 13051 /// 13052 /// \param Method the method to be marked pure. 13053 /// 13054 /// \param InitRange the source range that covers the "0" initializer. 13055 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 13056 SourceLocation EndLoc = InitRange.getEnd(); 13057 if (EndLoc.isValid()) 13058 Method->setRangeEnd(EndLoc); 13059 13060 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 13061 Method->setPure(); 13062 return false; 13063 } 13064 13065 if (!Method->isInvalidDecl()) 13066 Diag(Method->getLocation(), diag::err_non_virtual_pure) 13067 << Method->getDeclName() << InitRange; 13068 return true; 13069 } 13070 13071 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 13072 if (D->getFriendObjectKind()) 13073 Diag(D->getLocation(), diag::err_pure_friend); 13074 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 13075 CheckPureMethod(M, ZeroLoc); 13076 else 13077 Diag(D->getLocation(), diag::err_illegal_initializer); 13078 } 13079 13080 /// \brief Determine whether the given declaration is a static data member. 13081 static bool isStaticDataMember(const Decl *D) { 13082 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 13083 return Var->isStaticDataMember(); 13084 13085 return false; 13086 } 13087 13088 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 13089 /// an initializer for the out-of-line declaration 'Dcl'. The scope 13090 /// is a fresh scope pushed for just this purpose. 13091 /// 13092 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 13093 /// static data member of class X, names should be looked up in the scope of 13094 /// class X. 13095 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 13096 // If there is no declaration, there was an error parsing it. 13097 if (!D || D->isInvalidDecl()) 13098 return; 13099 13100 // We will always have a nested name specifier here, but this declaration 13101 // might not be out of line if the specifier names the current namespace: 13102 // extern int n; 13103 // int ::n = 0; 13104 if (D->isOutOfLine()) 13105 EnterDeclaratorContext(S, D->getDeclContext()); 13106 13107 // If we are parsing the initializer for a static data member, push a 13108 // new expression evaluation context that is associated with this static 13109 // data member. 13110 if (isStaticDataMember(D)) 13111 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 13112 } 13113 13114 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 13115 /// initializer for the out-of-line declaration 'D'. 13116 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 13117 // If there is no declaration, there was an error parsing it. 13118 if (!D || D->isInvalidDecl()) 13119 return; 13120 13121 if (isStaticDataMember(D)) 13122 PopExpressionEvaluationContext(); 13123 13124 if (D->isOutOfLine()) 13125 ExitDeclaratorContext(S); 13126 } 13127 13128 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 13129 /// C++ if/switch/while/for statement. 13130 /// e.g: "if (int x = f()) {...}" 13131 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 13132 // C++ 6.4p2: 13133 // The declarator shall not specify a function or an array. 13134 // The type-specifier-seq shall not contain typedef and shall not declare a 13135 // new class or enumeration. 13136 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 13137 "Parser allowed 'typedef' as storage class of condition decl."); 13138 13139 Decl *Dcl = ActOnDeclarator(S, D); 13140 if (!Dcl) 13141 return true; 13142 13143 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 13144 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 13145 << D.getSourceRange(); 13146 return true; 13147 } 13148 13149 return Dcl; 13150 } 13151 13152 void Sema::LoadExternalVTableUses() { 13153 if (!ExternalSource) 13154 return; 13155 13156 SmallVector<ExternalVTableUse, 4> VTables; 13157 ExternalSource->ReadUsedVTables(VTables); 13158 SmallVector<VTableUse, 4> NewUses; 13159 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 13160 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 13161 = VTablesUsed.find(VTables[I].Record); 13162 // Even if a definition wasn't required before, it may be required now. 13163 if (Pos != VTablesUsed.end()) { 13164 if (!Pos->second && VTables[I].DefinitionRequired) 13165 Pos->second = true; 13166 continue; 13167 } 13168 13169 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 13170 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 13171 } 13172 13173 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13174 } 13175 13176 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13177 bool DefinitionRequired) { 13178 // Ignore any vtable uses in unevaluated operands or for classes that do 13179 // not have a vtable. 13180 if (!Class->isDynamicClass() || Class->isDependentContext() || 13181 CurContext->isDependentContext() || isUnevaluatedContext()) 13182 return; 13183 13184 // Try to insert this class into the map. 13185 LoadExternalVTableUses(); 13186 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13187 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13188 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13189 if (!Pos.second) { 13190 // If we already had an entry, check to see if we are promoting this vtable 13191 // to require a definition. If so, we need to reappend to the VTableUses 13192 // list, since we may have already processed the first entry. 13193 if (DefinitionRequired && !Pos.first->second) { 13194 Pos.first->second = true; 13195 } else { 13196 // Otherwise, we can early exit. 13197 return; 13198 } 13199 } else { 13200 // The Microsoft ABI requires that we perform the destructor body 13201 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13202 // the deleting destructor is emitted with the vtable, not with the 13203 // destructor definition as in the Itanium ABI. 13204 // If it has a definition, we do the check at that point instead. 13205 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13206 Class->hasUserDeclaredDestructor() && 13207 !Class->getDestructor()->isDefined() && 13208 !Class->getDestructor()->isDeleted()) { 13209 CXXDestructorDecl *DD = Class->getDestructor(); 13210 ContextRAII SavedContext(*this, DD); 13211 CheckDestructor(DD); 13212 } 13213 } 13214 13215 // Local classes need to have their virtual members marked 13216 // immediately. For all other classes, we mark their virtual members 13217 // at the end of the translation unit. 13218 if (Class->isLocalClass()) 13219 MarkVirtualMembersReferenced(Loc, Class); 13220 else 13221 VTableUses.push_back(std::make_pair(Class, Loc)); 13222 } 13223 13224 bool Sema::DefineUsedVTables() { 13225 LoadExternalVTableUses(); 13226 if (VTableUses.empty()) 13227 return false; 13228 13229 // Note: The VTableUses vector could grow as a result of marking 13230 // the members of a class as "used", so we check the size each 13231 // time through the loop and prefer indices (which are stable) to 13232 // iterators (which are not). 13233 bool DefinedAnything = false; 13234 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13235 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13236 if (!Class) 13237 continue; 13238 13239 SourceLocation Loc = VTableUses[I].second; 13240 13241 bool DefineVTable = true; 13242 13243 // If this class has a key function, but that key function is 13244 // defined in another translation unit, we don't need to emit the 13245 // vtable even though we're using it. 13246 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13247 if (KeyFunction && !KeyFunction->hasBody()) { 13248 // The key function is in another translation unit. 13249 DefineVTable = false; 13250 TemplateSpecializationKind TSK = 13251 KeyFunction->getTemplateSpecializationKind(); 13252 assert(TSK != TSK_ExplicitInstantiationDefinition && 13253 TSK != TSK_ImplicitInstantiation && 13254 "Instantiations don't have key functions"); 13255 (void)TSK; 13256 } else if (!KeyFunction) { 13257 // If we have a class with no key function that is the subject 13258 // of an explicit instantiation declaration, suppress the 13259 // vtable; it will live with the explicit instantiation 13260 // definition. 13261 bool IsExplicitInstantiationDeclaration 13262 = Class->getTemplateSpecializationKind() 13263 == TSK_ExplicitInstantiationDeclaration; 13264 for (auto R : Class->redecls()) { 13265 TemplateSpecializationKind TSK 13266 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13267 if (TSK == TSK_ExplicitInstantiationDeclaration) 13268 IsExplicitInstantiationDeclaration = true; 13269 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13270 IsExplicitInstantiationDeclaration = false; 13271 break; 13272 } 13273 } 13274 13275 if (IsExplicitInstantiationDeclaration) 13276 DefineVTable = false; 13277 } 13278 13279 // The exception specifications for all virtual members may be needed even 13280 // if we are not providing an authoritative form of the vtable in this TU. 13281 // We may choose to emit it available_externally anyway. 13282 if (!DefineVTable) { 13283 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13284 continue; 13285 } 13286 13287 // Mark all of the virtual members of this class as referenced, so 13288 // that we can build a vtable. Then, tell the AST consumer that a 13289 // vtable for this class is required. 13290 DefinedAnything = true; 13291 MarkVirtualMembersReferenced(Loc, Class); 13292 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13293 if (VTablesUsed[Canonical]) 13294 Consumer.HandleVTable(Class); 13295 13296 // Optionally warn if we're emitting a weak vtable. 13297 if (Class->isExternallyVisible() && 13298 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13299 const FunctionDecl *KeyFunctionDef = nullptr; 13300 if (!KeyFunction || 13301 (KeyFunction->hasBody(KeyFunctionDef) && 13302 KeyFunctionDef->isInlined())) 13303 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13304 TSK_ExplicitInstantiationDefinition 13305 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13306 << Class; 13307 } 13308 } 13309 VTableUses.clear(); 13310 13311 return DefinedAnything; 13312 } 13313 13314 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13315 const CXXRecordDecl *RD) { 13316 for (const auto *I : RD->methods()) 13317 if (I->isVirtual() && !I->isPure()) 13318 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13319 } 13320 13321 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13322 const CXXRecordDecl *RD) { 13323 // Mark all functions which will appear in RD's vtable as used. 13324 CXXFinalOverriderMap FinalOverriders; 13325 RD->getFinalOverriders(FinalOverriders); 13326 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13327 E = FinalOverriders.end(); 13328 I != E; ++I) { 13329 for (OverridingMethods::const_iterator OI = I->second.begin(), 13330 OE = I->second.end(); 13331 OI != OE; ++OI) { 13332 assert(OI->second.size() > 0 && "no final overrider"); 13333 CXXMethodDecl *Overrider = OI->second.front().Method; 13334 13335 // C++ [basic.def.odr]p2: 13336 // [...] A virtual member function is used if it is not pure. [...] 13337 if (!Overrider->isPure()) 13338 MarkFunctionReferenced(Loc, Overrider); 13339 } 13340 } 13341 13342 // Only classes that have virtual bases need a VTT. 13343 if (RD->getNumVBases() == 0) 13344 return; 13345 13346 for (const auto &I : RD->bases()) { 13347 const CXXRecordDecl *Base = 13348 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13349 if (Base->getNumVBases() == 0) 13350 continue; 13351 MarkVirtualMembersReferenced(Loc, Base); 13352 } 13353 } 13354 13355 /// SetIvarInitializers - This routine builds initialization ASTs for the 13356 /// Objective-C implementation whose ivars need be initialized. 13357 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13358 if (!getLangOpts().CPlusPlus) 13359 return; 13360 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13361 SmallVector<ObjCIvarDecl*, 8> ivars; 13362 CollectIvarsToConstructOrDestruct(OID, ivars); 13363 if (ivars.empty()) 13364 return; 13365 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13366 for (unsigned i = 0; i < ivars.size(); i++) { 13367 FieldDecl *Field = ivars[i]; 13368 if (Field->isInvalidDecl()) 13369 continue; 13370 13371 CXXCtorInitializer *Member; 13372 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13373 InitializationKind InitKind = 13374 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13375 13376 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13377 ExprResult MemberInit = 13378 InitSeq.Perform(*this, InitEntity, InitKind, None); 13379 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13380 // Note, MemberInit could actually come back empty if no initialization 13381 // is required (e.g., because it would call a trivial default constructor) 13382 if (!MemberInit.get() || MemberInit.isInvalid()) 13383 continue; 13384 13385 Member = 13386 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13387 SourceLocation(), 13388 MemberInit.getAs<Expr>(), 13389 SourceLocation()); 13390 AllToInit.push_back(Member); 13391 13392 // Be sure that the destructor is accessible and is marked as referenced. 13393 if (const RecordType *RecordTy = 13394 Context.getBaseElementType(Field->getType()) 13395 ->getAs<RecordType>()) { 13396 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13397 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13398 MarkFunctionReferenced(Field->getLocation(), Destructor); 13399 CheckDestructorAccess(Field->getLocation(), Destructor, 13400 PDiag(diag::err_access_dtor_ivar) 13401 << Context.getBaseElementType(Field->getType())); 13402 } 13403 } 13404 } 13405 ObjCImplementation->setIvarInitializers(Context, 13406 AllToInit.data(), AllToInit.size()); 13407 } 13408 } 13409 13410 static 13411 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13412 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13413 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13414 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13415 Sema &S) { 13416 if (Ctor->isInvalidDecl()) 13417 return; 13418 13419 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13420 13421 // Target may not be determinable yet, for instance if this is a dependent 13422 // call in an uninstantiated template. 13423 if (Target) { 13424 const FunctionDecl *FNTarget = nullptr; 13425 (void)Target->hasBody(FNTarget); 13426 Target = const_cast<CXXConstructorDecl*>( 13427 cast_or_null<CXXConstructorDecl>(FNTarget)); 13428 } 13429 13430 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13431 // Avoid dereferencing a null pointer here. 13432 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13433 13434 if (!Current.insert(Canonical).second) 13435 return; 13436 13437 // We know that beyond here, we aren't chaining into a cycle. 13438 if (!Target || !Target->isDelegatingConstructor() || 13439 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13440 Valid.insert(Current.begin(), Current.end()); 13441 Current.clear(); 13442 // We've hit a cycle. 13443 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13444 Current.count(TCanonical)) { 13445 // If we haven't diagnosed this cycle yet, do so now. 13446 if (!Invalid.count(TCanonical)) { 13447 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13448 diag::warn_delegating_ctor_cycle) 13449 << Ctor; 13450 13451 // Don't add a note for a function delegating directly to itself. 13452 if (TCanonical != Canonical) 13453 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13454 13455 CXXConstructorDecl *C = Target; 13456 while (C->getCanonicalDecl() != Canonical) { 13457 const FunctionDecl *FNTarget = nullptr; 13458 (void)C->getTargetConstructor()->hasBody(FNTarget); 13459 assert(FNTarget && "Ctor cycle through bodiless function"); 13460 13461 C = const_cast<CXXConstructorDecl*>( 13462 cast<CXXConstructorDecl>(FNTarget)); 13463 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13464 } 13465 } 13466 13467 Invalid.insert(Current.begin(), Current.end()); 13468 Current.clear(); 13469 } else { 13470 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13471 } 13472 } 13473 13474 13475 void Sema::CheckDelegatingCtorCycles() { 13476 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13477 13478 for (DelegatingCtorDeclsType::iterator 13479 I = DelegatingCtorDecls.begin(ExternalSource), 13480 E = DelegatingCtorDecls.end(); 13481 I != E; ++I) 13482 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13483 13484 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13485 CE = Invalid.end(); 13486 CI != CE; ++CI) 13487 (*CI)->setInvalidDecl(); 13488 } 13489 13490 namespace { 13491 /// \brief AST visitor that finds references to the 'this' expression. 13492 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13493 Sema &S; 13494 13495 public: 13496 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13497 13498 bool VisitCXXThisExpr(CXXThisExpr *E) { 13499 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13500 << E->isImplicit(); 13501 return false; 13502 } 13503 }; 13504 } 13505 13506 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13507 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13508 if (!TSInfo) 13509 return false; 13510 13511 TypeLoc TL = TSInfo->getTypeLoc(); 13512 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13513 if (!ProtoTL) 13514 return false; 13515 13516 // C++11 [expr.prim.general]p3: 13517 // [The expression this] shall not appear before the optional 13518 // cv-qualifier-seq and it shall not appear within the declaration of a 13519 // static member function (although its type and value category are defined 13520 // within a static member function as they are within a non-static member 13521 // function). [ Note: this is because declaration matching does not occur 13522 // until the complete declarator is known. - end note ] 13523 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13524 FindCXXThisExpr Finder(*this); 13525 13526 // If the return type came after the cv-qualifier-seq, check it now. 13527 if (Proto->hasTrailingReturn() && 13528 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13529 return true; 13530 13531 // Check the exception specification. 13532 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13533 return true; 13534 13535 return checkThisInStaticMemberFunctionAttributes(Method); 13536 } 13537 13538 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13539 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13540 if (!TSInfo) 13541 return false; 13542 13543 TypeLoc TL = TSInfo->getTypeLoc(); 13544 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13545 if (!ProtoTL) 13546 return false; 13547 13548 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13549 FindCXXThisExpr Finder(*this); 13550 13551 switch (Proto->getExceptionSpecType()) { 13552 case EST_Unparsed: 13553 case EST_Uninstantiated: 13554 case EST_Unevaluated: 13555 case EST_BasicNoexcept: 13556 case EST_DynamicNone: 13557 case EST_MSAny: 13558 case EST_None: 13559 break; 13560 13561 case EST_ComputedNoexcept: 13562 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13563 return true; 13564 13565 case EST_Dynamic: 13566 for (const auto &E : Proto->exceptions()) { 13567 if (!Finder.TraverseType(E)) 13568 return true; 13569 } 13570 break; 13571 } 13572 13573 return false; 13574 } 13575 13576 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13577 FindCXXThisExpr Finder(*this); 13578 13579 // Check attributes. 13580 for (const auto *A : Method->attrs()) { 13581 // FIXME: This should be emitted by tblgen. 13582 Expr *Arg = nullptr; 13583 ArrayRef<Expr *> Args; 13584 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13585 Arg = G->getArg(); 13586 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13587 Arg = G->getArg(); 13588 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13589 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13590 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13591 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13592 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13593 Arg = ETLF->getSuccessValue(); 13594 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13595 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13596 Arg = STLF->getSuccessValue(); 13597 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13598 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13599 Arg = LR->getArg(); 13600 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13601 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13602 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13603 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13604 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13605 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13606 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13607 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13608 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13609 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13610 13611 if (Arg && !Finder.TraverseStmt(Arg)) 13612 return true; 13613 13614 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13615 if (!Finder.TraverseStmt(Args[I])) 13616 return true; 13617 } 13618 } 13619 13620 return false; 13621 } 13622 13623 void Sema::checkExceptionSpecification( 13624 bool IsTopLevel, ExceptionSpecificationType EST, 13625 ArrayRef<ParsedType> DynamicExceptions, 13626 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13627 SmallVectorImpl<QualType> &Exceptions, 13628 FunctionProtoType::ExceptionSpecInfo &ESI) { 13629 Exceptions.clear(); 13630 ESI.Type = EST; 13631 if (EST == EST_Dynamic) { 13632 Exceptions.reserve(DynamicExceptions.size()); 13633 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13634 // FIXME: Preserve type source info. 13635 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13636 13637 if (IsTopLevel) { 13638 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13639 collectUnexpandedParameterPacks(ET, Unexpanded); 13640 if (!Unexpanded.empty()) { 13641 DiagnoseUnexpandedParameterPacks( 13642 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13643 Unexpanded); 13644 continue; 13645 } 13646 } 13647 13648 // Check that the type is valid for an exception spec, and 13649 // drop it if not. 13650 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13651 Exceptions.push_back(ET); 13652 } 13653 ESI.Exceptions = Exceptions; 13654 return; 13655 } 13656 13657 if (EST == EST_ComputedNoexcept) { 13658 // If an error occurred, there's no expression here. 13659 if (NoexceptExpr) { 13660 assert((NoexceptExpr->isTypeDependent() || 13661 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13662 Context.BoolTy) && 13663 "Parser should have made sure that the expression is boolean"); 13664 if (IsTopLevel && NoexceptExpr && 13665 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13666 ESI.Type = EST_BasicNoexcept; 13667 return; 13668 } 13669 13670 if (!NoexceptExpr->isValueDependent()) 13671 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13672 diag::err_noexcept_needs_constant_expression, 13673 /*AllowFold*/ false).get(); 13674 ESI.NoexceptExpr = NoexceptExpr; 13675 } 13676 return; 13677 } 13678 } 13679 13680 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13681 ExceptionSpecificationType EST, 13682 SourceRange SpecificationRange, 13683 ArrayRef<ParsedType> DynamicExceptions, 13684 ArrayRef<SourceRange> DynamicExceptionRanges, 13685 Expr *NoexceptExpr) { 13686 if (!MethodD) 13687 return; 13688 13689 // Dig out the method we're referring to. 13690 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13691 MethodD = FunTmpl->getTemplatedDecl(); 13692 13693 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13694 if (!Method) 13695 return; 13696 13697 // Check the exception specification. 13698 llvm::SmallVector<QualType, 4> Exceptions; 13699 FunctionProtoType::ExceptionSpecInfo ESI; 13700 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13701 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13702 ESI); 13703 13704 // Update the exception specification on the function type. 13705 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13706 13707 if (Method->isStatic()) 13708 checkThisInStaticMemberFunctionExceptionSpec(Method); 13709 13710 if (Method->isVirtual()) { 13711 // Check overrides, which we previously had to delay. 13712 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13713 OEnd = Method->end_overridden_methods(); 13714 O != OEnd; ++O) 13715 CheckOverridingFunctionExceptionSpec(Method, *O); 13716 } 13717 } 13718 13719 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13720 /// 13721 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13722 SourceLocation DeclStart, 13723 Declarator &D, Expr *BitWidth, 13724 InClassInitStyle InitStyle, 13725 AccessSpecifier AS, 13726 AttributeList *MSPropertyAttr) { 13727 IdentifierInfo *II = D.getIdentifier(); 13728 if (!II) { 13729 Diag(DeclStart, diag::err_anonymous_property); 13730 return nullptr; 13731 } 13732 SourceLocation Loc = D.getIdentifierLoc(); 13733 13734 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13735 QualType T = TInfo->getType(); 13736 if (getLangOpts().CPlusPlus) { 13737 CheckExtraCXXDefaultArguments(D); 13738 13739 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13740 UPPC_DataMemberType)) { 13741 D.setInvalidType(); 13742 T = Context.IntTy; 13743 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13744 } 13745 } 13746 13747 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13748 13749 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13750 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13751 diag::err_invalid_thread) 13752 << DeclSpec::getSpecifierName(TSCS); 13753 13754 // Check to see if this name was declared as a member previously 13755 NamedDecl *PrevDecl = nullptr; 13756 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13757 LookupName(Previous, S); 13758 switch (Previous.getResultKind()) { 13759 case LookupResult::Found: 13760 case LookupResult::FoundUnresolvedValue: 13761 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13762 break; 13763 13764 case LookupResult::FoundOverloaded: 13765 PrevDecl = Previous.getRepresentativeDecl(); 13766 break; 13767 13768 case LookupResult::NotFound: 13769 case LookupResult::NotFoundInCurrentInstantiation: 13770 case LookupResult::Ambiguous: 13771 break; 13772 } 13773 13774 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13775 // Maybe we will complain about the shadowed template parameter. 13776 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13777 // Just pretend that we didn't see the previous declaration. 13778 PrevDecl = nullptr; 13779 } 13780 13781 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13782 PrevDecl = nullptr; 13783 13784 SourceLocation TSSL = D.getLocStart(); 13785 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13786 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13787 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13788 ProcessDeclAttributes(TUScope, NewPD, D); 13789 NewPD->setAccess(AS); 13790 13791 if (NewPD->isInvalidDecl()) 13792 Record->setInvalidDecl(); 13793 13794 if (D.getDeclSpec().isModulePrivateSpecified()) 13795 NewPD->setModulePrivate(); 13796 13797 if (NewPD->isInvalidDecl() && PrevDecl) { 13798 // Don't introduce NewFD into scope; there's already something 13799 // with the same name in the same scope. 13800 } else if (II) { 13801 PushOnScopeChains(NewPD, S); 13802 } else 13803 Record->addDecl(NewPD); 13804 13805 return NewPD; 13806 } 13807