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::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 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 this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.getAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // Check that the default argument is well-formed 322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 323 if (DefaultArgChecker.Visit(DefaultArg)) { 324 Param->setInvalidDecl(); 325 return; 326 } 327 328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 329 } 330 331 /// ActOnParamUnparsedDefaultArgument - We've seen a default 332 /// argument for a function parameter, but we can't parse it yet 333 /// because we're inside a class definition. Note that this default 334 /// argument will be parsed later. 335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 Param->setUnparsedDefaultArg(); 343 UnparsedDefaultArgLocs[Param] = ArgLoc; 344 } 345 346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 347 /// the default argument for the parameter param failed. 348 void Sema::ActOnParamDefaultArgumentError(Decl *param, 349 SourceLocation EqualLoc) { 350 if (!param) 351 return; 352 353 ParmVarDecl *Param = cast<ParmVarDecl>(param); 354 Param->setInvalidDecl(); 355 UnparsedDefaultArgLocs.erase(Param); 356 Param->setDefaultArg(new(Context) 357 OpaqueValueExpr(EqualLoc, 358 Param->getType().getNonReferenceType(), 359 VK_RValue)); 360 } 361 362 /// CheckExtraCXXDefaultArguments - Check for any extra default 363 /// arguments in the declarator, which is not a function declaration 364 /// or definition and therefore is not permitted to have default 365 /// arguments. This routine should be invoked for every declarator 366 /// that is not a function declaration or definition. 367 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 368 // C++ [dcl.fct.default]p3 369 // A default argument expression shall be specified only in the 370 // parameter-declaration-clause of a function declaration or in a 371 // template-parameter (14.1). It shall not be specified for a 372 // parameter pack. If it is specified in a 373 // parameter-declaration-clause, it shall not occur within a 374 // declarator or abstract-declarator of a parameter-declaration. 375 bool MightBeFunction = D.isFunctionDeclarationContext(); 376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 377 DeclaratorChunk &chunk = D.getTypeObject(i); 378 if (chunk.Kind == DeclaratorChunk::Function) { 379 if (MightBeFunction) { 380 // This is a function declaration. It can have default arguments, but 381 // keep looking in case its return type is a function type with default 382 // arguments. 383 MightBeFunction = false; 384 continue; 385 } 386 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 387 ++argIdx) { 388 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 389 if (Param->hasUnparsedDefaultArg()) { 390 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 392 << SourceRange((*Toks)[1].getLocation(), 393 Toks->back().getLocation()); 394 delete Toks; 395 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 396 } else if (Param->getDefaultArg()) { 397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 398 << Param->getDefaultArg()->getSourceRange(); 399 Param->setDefaultArg(nullptr); 400 } 401 } 402 } else if (chunk.Kind != DeclaratorChunk::Paren) { 403 MightBeFunction = false; 404 } 405 } 406 } 407 408 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 409 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 410 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 411 if (!PVD->hasDefaultArg()) 412 return false; 413 if (!PVD->hasInheritedDefaultArg()) 414 return true; 415 } 416 return false; 417 } 418 419 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 420 /// function, once we already know that they have the same 421 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 422 /// error, false otherwise. 423 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 424 Scope *S) { 425 bool Invalid = false; 426 427 // C++ [dcl.fct.default]p4: 428 // For non-template functions, default arguments can be added in 429 // later declarations of a function in the same 430 // scope. Declarations in different scopes have completely 431 // distinct sets of default arguments. That is, declarations in 432 // inner scopes do not acquire default arguments from 433 // declarations in outer scopes, and vice versa. In a given 434 // function declaration, all parameters subsequent to a 435 // parameter with a default argument shall have default 436 // arguments supplied in this or previous declarations. A 437 // default argument shall not be redefined by a later 438 // declaration (not even to the same value). 439 // 440 // C++ [dcl.fct.default]p6: 441 // Except for member functions of class templates, the default arguments 442 // in a member function definition that appears outside of the class 443 // definition are added to the set of default arguments provided by the 444 // member function declaration in the class definition. 445 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 446 ParmVarDecl *OldParam = Old->getParamDecl(p); 447 ParmVarDecl *NewParam = New->getParamDecl(p); 448 449 bool OldParamHasDfl = OldParam->hasDefaultArg(); 450 bool NewParamHasDfl = NewParam->hasDefaultArg(); 451 452 // The declaration context corresponding to the scope is the semantic 453 // parent, unless this is a local function declaration, in which case 454 // it is that surrounding function. 455 DeclContext *ScopeDC = New->isLocalExternDecl() 456 ? New->getLexicalDeclContext() 457 : New->getDeclContext(); 458 if (S && !isDeclInScope(Old, ScopeDC, S) && 459 !New->getDeclContext()->isRecord()) 460 // Ignore default parameters 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 OldParamHasDfl = false; 464 if (New->isLocalExternDecl() != Old->isLocalExternDecl()) 465 // If only one of these is a local function declaration, then they are 466 // declared in different scopes, even though isDeclInScope may think 467 // they're in the same scope. (If both are local, the scope check is 468 // sufficent, and if neither is local, then they are in the same scope.) 469 OldParamHasDfl = false; 470 471 if (OldParamHasDfl && NewParamHasDfl) { 472 473 unsigned DiagDefaultParamID = 474 diag::err_param_default_argument_redefinition; 475 476 // MSVC accepts that default parameters be redefined for member functions 477 // of template class. The new default parameter's value is ignored. 478 Invalid = true; 479 if (getLangOpts().MicrosoftExt) { 480 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 481 if (MD && MD->getParent()->getDescribedClassTemplate()) { 482 // Merge the old default argument into the new parameter. 483 NewParam->setHasInheritedDefaultArg(); 484 if (OldParam->hasUninstantiatedDefaultArg()) 485 NewParam->setUninstantiatedDefaultArg( 486 OldParam->getUninstantiatedDefaultArg()); 487 else 488 NewParam->setDefaultArg(OldParam->getInit()); 489 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 490 Invalid = false; 491 } 492 } 493 494 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 495 // hint here. Alternatively, we could walk the type-source information 496 // for NewParam to find the last source location in the type... but it 497 // isn't worth the effort right now. This is the kind of test case that 498 // is hard to get right: 499 // int f(int); 500 // void g(int (*fp)(int) = f); 501 // void g(int (*fp)(int) = &f); 502 Diag(NewParam->getLocation(), DiagDefaultParamID) 503 << NewParam->getDefaultArgRange(); 504 505 // Look for the function declaration where the default argument was 506 // actually written, which may be a declaration prior to Old. 507 for (FunctionDecl *Older = Old->getPreviousDecl(); 508 Older; Older = Older->getPreviousDecl()) { 509 if (!Older->getParamDecl(p)->hasDefaultArg()) 510 break; 511 512 OldParam = Older->getParamDecl(p); 513 } 514 515 Diag(OldParam->getLocation(), diag::note_previous_definition) 516 << OldParam->getDefaultArgRange(); 517 } else if (OldParamHasDfl) { 518 // Merge the old default argument into the new parameter. 519 // It's important to use getInit() here; getDefaultArg() 520 // strips off any top-level ExprWithCleanups. 521 NewParam->setHasInheritedDefaultArg(); 522 if (OldParam->hasUninstantiatedDefaultArg()) 523 NewParam->setUninstantiatedDefaultArg( 524 OldParam->getUninstantiatedDefaultArg()); 525 else 526 NewParam->setDefaultArg(OldParam->getInit()); 527 } else if (NewParamHasDfl) { 528 if (New->getDescribedFunctionTemplate()) { 529 // Paragraph 4, quoted above, only applies to non-template functions. 530 Diag(NewParam->getLocation(), 531 diag::err_param_default_argument_template_redecl) 532 << NewParam->getDefaultArgRange(); 533 Diag(Old->getLocation(), diag::note_template_prev_declaration) 534 << false; 535 } else if (New->getTemplateSpecializationKind() 536 != TSK_ImplicitInstantiation && 537 New->getTemplateSpecializationKind() != TSK_Undeclared) { 538 // C++ [temp.expr.spec]p21: 539 // Default function arguments shall not be specified in a declaration 540 // or a definition for one of the following explicit specializations: 541 // - the explicit specialization of a function template; 542 // - the explicit specialization of a member function template; 543 // - the explicit specialization of a member function of a class 544 // template where the class template specialization to which the 545 // member function specialization belongs is implicitly 546 // instantiated. 547 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 548 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 549 << New->getDeclName() 550 << NewParam->getDefaultArgRange(); 551 } else if (New->getDeclContext()->isDependentContext()) { 552 // C++ [dcl.fct.default]p6 (DR217): 553 // Default arguments for a member function of a class template shall 554 // be specified on the initial declaration of the member function 555 // within the class template. 556 // 557 // Reading the tea leaves a bit in DR217 and its reference to DR205 558 // leads me to the conclusion that one cannot add default function 559 // arguments for an out-of-line definition of a member function of a 560 // dependent type. 561 int WhichKind = 2; 562 if (CXXRecordDecl *Record 563 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 564 if (Record->getDescribedClassTemplate()) 565 WhichKind = 0; 566 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 567 WhichKind = 1; 568 else 569 WhichKind = 2; 570 } 571 572 Diag(NewParam->getLocation(), 573 diag::err_param_default_argument_member_template_redecl) 574 << WhichKind 575 << NewParam->getDefaultArgRange(); 576 } 577 } 578 } 579 580 // DR1344: If a default argument is added outside a class definition and that 581 // default argument makes the function a special member function, the program 582 // is ill-formed. This can only happen for constructors. 583 if (isa<CXXConstructorDecl>(New) && 584 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 585 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 586 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 587 if (NewSM != OldSM) { 588 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 589 assert(NewParam->hasDefaultArg()); 590 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 591 << NewParam->getDefaultArgRange() << NewSM; 592 Diag(Old->getLocation(), diag::note_previous_declaration); 593 } 594 } 595 596 const FunctionDecl *Def; 597 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 598 // template has a constexpr specifier then all its declarations shall 599 // contain the constexpr specifier. 600 if (New->isConstexpr() != Old->isConstexpr()) { 601 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 602 << New << New->isConstexpr(); 603 Diag(Old->getLocation(), diag::note_previous_declaration); 604 Invalid = true; 605 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 606 // C++11 [dcl.fcn.spec]p4: 607 // If the definition of a function appears in a translation unit before its 608 // first declaration as inline, the program is ill-formed. 609 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 610 Diag(Def->getLocation(), diag::note_previous_definition); 611 Invalid = true; 612 } 613 614 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 615 // argument expression, that declaration shall be a definition and shall be 616 // the only declaration of the function or function template in the 617 // translation unit. 618 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 619 functionDeclHasDefaultArgument(Old)) { 620 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 621 Diag(Old->getLocation(), diag::note_previous_declaration); 622 Invalid = true; 623 } 624 625 if (CheckEquivalentExceptionSpec(Old, New)) 626 Invalid = true; 627 628 return Invalid; 629 } 630 631 /// \brief Merge the exception specifications of two variable declarations. 632 /// 633 /// This is called when there's a redeclaration of a VarDecl. The function 634 /// checks if the redeclaration might have an exception specification and 635 /// validates compatibility and merges the specs if necessary. 636 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 637 // Shortcut if exceptions are disabled. 638 if (!getLangOpts().CXXExceptions) 639 return; 640 641 assert(Context.hasSameType(New->getType(), Old->getType()) && 642 "Should only be called if types are otherwise the same."); 643 644 QualType NewType = New->getType(); 645 QualType OldType = Old->getType(); 646 647 // We're only interested in pointers and references to functions, as well 648 // as pointers to member functions. 649 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 650 NewType = R->getPointeeType(); 651 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 652 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 653 NewType = P->getPointeeType(); 654 OldType = OldType->getAs<PointerType>()->getPointeeType(); 655 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 656 NewType = M->getPointeeType(); 657 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 658 } 659 660 if (!NewType->isFunctionProtoType()) 661 return; 662 663 // There's lots of special cases for functions. For function pointers, system 664 // libraries are hopefully not as broken so that we don't need these 665 // workarounds. 666 if (CheckEquivalentExceptionSpec( 667 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 668 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 669 New->setInvalidDecl(); 670 } 671 } 672 673 /// CheckCXXDefaultArguments - Verify that the default arguments for a 674 /// function declaration are well-formed according to C++ 675 /// [dcl.fct.default]. 676 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 677 unsigned NumParams = FD->getNumParams(); 678 unsigned p; 679 680 // Find first parameter with a default argument 681 for (p = 0; p < NumParams; ++p) { 682 ParmVarDecl *Param = FD->getParamDecl(p); 683 if (Param->hasDefaultArg()) 684 break; 685 } 686 687 // C++ [dcl.fct.default]p4: 688 // In a given function declaration, all parameters 689 // subsequent to a parameter with a default argument shall 690 // have default arguments supplied in this or previous 691 // declarations. A default argument shall not be redefined 692 // by a later declaration (not even to the same value). 693 unsigned LastMissingDefaultArg = 0; 694 for (; p < NumParams; ++p) { 695 ParmVarDecl *Param = FD->getParamDecl(p); 696 if (!Param->hasDefaultArg()) { 697 if (Param->isInvalidDecl()) 698 /* We already complained about this parameter. */; 699 else if (Param->getIdentifier()) 700 Diag(Param->getLocation(), 701 diag::err_param_default_argument_missing_name) 702 << Param->getIdentifier(); 703 else 704 Diag(Param->getLocation(), 705 diag::err_param_default_argument_missing); 706 707 LastMissingDefaultArg = p; 708 } 709 } 710 711 if (LastMissingDefaultArg > 0) { 712 // Some default arguments were missing. Clear out all of the 713 // default arguments up to (and including) the last missing 714 // default argument, so that we leave the function parameters 715 // in a semantically valid state. 716 for (p = 0; p <= LastMissingDefaultArg; ++p) { 717 ParmVarDecl *Param = FD->getParamDecl(p); 718 if (Param->hasDefaultArg()) { 719 Param->setDefaultArg(nullptr); 720 } 721 } 722 } 723 } 724 725 // CheckConstexprParameterTypes - Check whether a function's parameter types 726 // are all literal types. If so, return true. If not, produce a suitable 727 // diagnostic and return false. 728 static bool CheckConstexprParameterTypes(Sema &SemaRef, 729 const FunctionDecl *FD) { 730 unsigned ArgIndex = 0; 731 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 732 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 733 e = FT->param_type_end(); 734 i != e; ++i, ++ArgIndex) { 735 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 736 SourceLocation ParamLoc = PD->getLocation(); 737 if (!(*i)->isDependentType() && 738 SemaRef.RequireLiteralType(ParamLoc, *i, 739 diag::err_constexpr_non_literal_param, 740 ArgIndex+1, PD->getSourceRange(), 741 isa<CXXConstructorDecl>(FD))) 742 return false; 743 } 744 return true; 745 } 746 747 /// \brief Get diagnostic %select index for tag kind for 748 /// record diagnostic message. 749 /// WARNING: Indexes apply to particular diagnostics only! 750 /// 751 /// \returns diagnostic %select index. 752 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 753 switch (Tag) { 754 case TTK_Struct: return 0; 755 case TTK_Interface: return 1; 756 case TTK_Class: return 2; 757 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 758 } 759 } 760 761 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 762 // the requirements of a constexpr function definition or a constexpr 763 // constructor definition. If so, return true. If not, produce appropriate 764 // diagnostics and return false. 765 // 766 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 767 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 768 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 769 if (MD && MD->isInstance()) { 770 // C++11 [dcl.constexpr]p4: 771 // The definition of a constexpr constructor shall satisfy the following 772 // constraints: 773 // - the class shall not have any virtual base classes; 774 const CXXRecordDecl *RD = MD->getParent(); 775 if (RD->getNumVBases()) { 776 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 777 << isa<CXXConstructorDecl>(NewFD) 778 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 779 for (const auto &I : RD->vbases()) 780 Diag(I.getLocStart(), 781 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 782 return false; 783 } 784 } 785 786 if (!isa<CXXConstructorDecl>(NewFD)) { 787 // C++11 [dcl.constexpr]p3: 788 // The definition of a constexpr function shall satisfy the following 789 // constraints: 790 // - it shall not be virtual; 791 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 792 if (Method && Method->isVirtual()) { 793 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 794 795 // If it's not obvious why this function is virtual, find an overridden 796 // function which uses the 'virtual' keyword. 797 const CXXMethodDecl *WrittenVirtual = Method; 798 while (!WrittenVirtual->isVirtualAsWritten()) 799 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 800 if (WrittenVirtual != Method) 801 Diag(WrittenVirtual->getLocation(), 802 diag::note_overridden_virtual_function); 803 return false; 804 } 805 806 // - its return type shall be a literal type; 807 QualType RT = NewFD->getReturnType(); 808 if (!RT->isDependentType() && 809 RequireLiteralType(NewFD->getLocation(), RT, 810 diag::err_constexpr_non_literal_return)) 811 return false; 812 } 813 814 // - each of its parameter types shall be a literal type; 815 if (!CheckConstexprParameterTypes(*this, NewFD)) 816 return false; 817 818 return true; 819 } 820 821 /// Check the given declaration statement is legal within a constexpr function 822 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 823 /// 824 /// \return true if the body is OK (maybe only as an extension), false if we 825 /// have diagnosed a problem. 826 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 827 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 828 // C++11 [dcl.constexpr]p3 and p4: 829 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 830 // contain only 831 for (const auto *DclIt : DS->decls()) { 832 switch (DclIt->getKind()) { 833 case Decl::StaticAssert: 834 case Decl::Using: 835 case Decl::UsingShadow: 836 case Decl::UsingDirective: 837 case Decl::UnresolvedUsingTypename: 838 case Decl::UnresolvedUsingValue: 839 // - static_assert-declarations 840 // - using-declarations, 841 // - using-directives, 842 continue; 843 844 case Decl::Typedef: 845 case Decl::TypeAlias: { 846 // - typedef declarations and alias-declarations that do not define 847 // classes or enumerations, 848 const auto *TN = cast<TypedefNameDecl>(DclIt); 849 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 850 // Don't allow variably-modified types in constexpr functions. 851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 853 << TL.getSourceRange() << TL.getType() 854 << isa<CXXConstructorDecl>(Dcl); 855 return false; 856 } 857 continue; 858 } 859 860 case Decl::Enum: 861 case Decl::CXXRecord: 862 // C++1y allows types to be defined, not just declared. 863 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 864 SemaRef.Diag(DS->getLocStart(), 865 SemaRef.getLangOpts().CPlusPlus14 866 ? diag::warn_cxx11_compat_constexpr_type_definition 867 : diag::ext_constexpr_type_definition) 868 << isa<CXXConstructorDecl>(Dcl); 869 continue; 870 871 case Decl::EnumConstant: 872 case Decl::IndirectField: 873 case Decl::ParmVar: 874 // These can only appear with other declarations which are banned in 875 // C++11 and permitted in C++1y, so ignore them. 876 continue; 877 878 case Decl::Var: { 879 // C++1y [dcl.constexpr]p3 allows anything except: 880 // a definition of a variable of non-literal type or of static or 881 // thread storage duration or for which no initialization is performed. 882 const auto *VD = cast<VarDecl>(DclIt); 883 if (VD->isThisDeclarationADefinition()) { 884 if (VD->isStaticLocal()) { 885 SemaRef.Diag(VD->getLocation(), 886 diag::err_constexpr_local_var_static) 887 << isa<CXXConstructorDecl>(Dcl) 888 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 889 return false; 890 } 891 if (!VD->getType()->isDependentType() && 892 SemaRef.RequireLiteralType( 893 VD->getLocation(), VD->getType(), 894 diag::err_constexpr_local_var_non_literal_type, 895 isa<CXXConstructorDecl>(Dcl))) 896 return false; 897 if (!VD->getType()->isDependentType() && 898 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 899 SemaRef.Diag(VD->getLocation(), 900 diag::err_constexpr_local_var_no_init) 901 << isa<CXXConstructorDecl>(Dcl); 902 return false; 903 } 904 } 905 SemaRef.Diag(VD->getLocation(), 906 SemaRef.getLangOpts().CPlusPlus14 907 ? diag::warn_cxx11_compat_constexpr_local_var 908 : diag::ext_constexpr_local_var) 909 << isa<CXXConstructorDecl>(Dcl); 910 continue; 911 } 912 913 case Decl::NamespaceAlias: 914 case Decl::Function: 915 // These are disallowed in C++11 and permitted in C++1y. Allow them 916 // everywhere as an extension. 917 if (!Cxx1yLoc.isValid()) 918 Cxx1yLoc = DS->getLocStart(); 919 continue; 920 921 default: 922 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 923 << isa<CXXConstructorDecl>(Dcl); 924 return false; 925 } 926 } 927 928 return true; 929 } 930 931 /// Check that the given field is initialized within a constexpr constructor. 932 /// 933 /// \param Dcl The constexpr constructor being checked. 934 /// \param Field The field being checked. This may be a member of an anonymous 935 /// struct or union nested within the class being checked. 936 /// \param Inits All declarations, including anonymous struct/union members and 937 /// indirect members, for which any initialization was provided. 938 /// \param Diagnosed Set to true if an error is produced. 939 static void CheckConstexprCtorInitializer(Sema &SemaRef, 940 const FunctionDecl *Dcl, 941 FieldDecl *Field, 942 llvm::SmallSet<Decl*, 16> &Inits, 943 bool &Diagnosed) { 944 if (Field->isInvalidDecl()) 945 return; 946 947 if (Field->isUnnamedBitfield()) 948 return; 949 950 // Anonymous unions with no variant members and empty anonymous structs do not 951 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 952 // indirect fields don't need initializing. 953 if (Field->isAnonymousStructOrUnion() && 954 (Field->getType()->isUnionType() 955 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 956 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 957 return; 958 959 if (!Inits.count(Field)) { 960 if (!Diagnosed) { 961 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 962 Diagnosed = true; 963 } 964 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 965 } else if (Field->isAnonymousStructOrUnion()) { 966 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 967 for (auto *I : RD->fields()) 968 // If an anonymous union contains an anonymous struct of which any member 969 // is initialized, all members must be initialized. 970 if (!RD->isUnion() || Inits.count(I)) 971 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 972 } 973 } 974 975 /// Check the provided statement is allowed in a constexpr function 976 /// definition. 977 static bool 978 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 979 SmallVectorImpl<SourceLocation> &ReturnStmts, 980 SourceLocation &Cxx1yLoc) { 981 // - its function-body shall be [...] a compound-statement that contains only 982 switch (S->getStmtClass()) { 983 case Stmt::NullStmtClass: 984 // - null statements, 985 return true; 986 987 case Stmt::DeclStmtClass: 988 // - static_assert-declarations 989 // - using-declarations, 990 // - using-directives, 991 // - typedef declarations and alias-declarations that do not define 992 // classes or enumerations, 993 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 994 return false; 995 return true; 996 997 case Stmt::ReturnStmtClass: 998 // - and exactly one return statement; 999 if (isa<CXXConstructorDecl>(Dcl)) { 1000 // C++1y allows return statements in constexpr constructors. 1001 if (!Cxx1yLoc.isValid()) 1002 Cxx1yLoc = S->getLocStart(); 1003 return true; 1004 } 1005 1006 ReturnStmts.push_back(S->getLocStart()); 1007 return true; 1008 1009 case Stmt::CompoundStmtClass: { 1010 // C++1y allows compound-statements. 1011 if (!Cxx1yLoc.isValid()) 1012 Cxx1yLoc = S->getLocStart(); 1013 1014 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1015 for (auto *BodyIt : CompStmt->body()) { 1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1017 Cxx1yLoc)) 1018 return false; 1019 } 1020 return true; 1021 } 1022 1023 case Stmt::AttributedStmtClass: 1024 if (!Cxx1yLoc.isValid()) 1025 Cxx1yLoc = S->getLocStart(); 1026 return true; 1027 1028 case Stmt::IfStmtClass: { 1029 // C++1y allows if-statements. 1030 if (!Cxx1yLoc.isValid()) 1031 Cxx1yLoc = S->getLocStart(); 1032 1033 IfStmt *If = cast<IfStmt>(S); 1034 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1035 Cxx1yLoc)) 1036 return false; 1037 if (If->getElse() && 1038 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1039 Cxx1yLoc)) 1040 return false; 1041 return true; 1042 } 1043 1044 case Stmt::WhileStmtClass: 1045 case Stmt::DoStmtClass: 1046 case Stmt::ForStmtClass: 1047 case Stmt::CXXForRangeStmtClass: 1048 case Stmt::ContinueStmtClass: 1049 // C++1y allows all of these. We don't allow them as extensions in C++11, 1050 // because they don't make sense without variable mutation. 1051 if (!SemaRef.getLangOpts().CPlusPlus14) 1052 break; 1053 if (!Cxx1yLoc.isValid()) 1054 Cxx1yLoc = S->getLocStart(); 1055 for (Stmt::child_range Children = S->children(); Children; ++Children) 1056 if (*Children && 1057 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1058 Cxx1yLoc)) 1059 return false; 1060 return true; 1061 1062 case Stmt::SwitchStmtClass: 1063 case Stmt::CaseStmtClass: 1064 case Stmt::DefaultStmtClass: 1065 case Stmt::BreakStmtClass: 1066 // C++1y allows switch-statements, and since they don't need variable 1067 // mutation, we can reasonably allow them in C++11 as an extension. 1068 if (!Cxx1yLoc.isValid()) 1069 Cxx1yLoc = S->getLocStart(); 1070 for (Stmt::child_range Children = S->children(); Children; ++Children) 1071 if (*Children && 1072 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1073 Cxx1yLoc)) 1074 return false; 1075 return true; 1076 1077 default: 1078 if (!isa<Expr>(S)) 1079 break; 1080 1081 // C++1y allows expression-statements. 1082 if (!Cxx1yLoc.isValid()) 1083 Cxx1yLoc = S->getLocStart(); 1084 return true; 1085 } 1086 1087 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1088 << isa<CXXConstructorDecl>(Dcl); 1089 return false; 1090 } 1091 1092 /// Check the body for the given constexpr function declaration only contains 1093 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1094 /// 1095 /// \return true if the body is OK, false if we have diagnosed a problem. 1096 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1097 if (isa<CXXTryStmt>(Body)) { 1098 // C++11 [dcl.constexpr]p3: 1099 // The definition of a constexpr function shall satisfy the following 1100 // constraints: [...] 1101 // - its function-body shall be = delete, = default, or a 1102 // compound-statement 1103 // 1104 // C++11 [dcl.constexpr]p4: 1105 // In the definition of a constexpr constructor, [...] 1106 // - its function-body shall not be a function-try-block; 1107 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1108 << isa<CXXConstructorDecl>(Dcl); 1109 return false; 1110 } 1111 1112 SmallVector<SourceLocation, 4> ReturnStmts; 1113 1114 // - its function-body shall be [...] a compound-statement that contains only 1115 // [... list of cases ...] 1116 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1117 SourceLocation Cxx1yLoc; 1118 for (auto *BodyIt : CompBody->body()) { 1119 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1120 return false; 1121 } 1122 1123 if (Cxx1yLoc.isValid()) 1124 Diag(Cxx1yLoc, 1125 getLangOpts().CPlusPlus14 1126 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1127 : diag::ext_constexpr_body_invalid_stmt) 1128 << isa<CXXConstructorDecl>(Dcl); 1129 1130 if (const CXXConstructorDecl *Constructor 1131 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1132 const CXXRecordDecl *RD = Constructor->getParent(); 1133 // DR1359: 1134 // - every non-variant non-static data member and base class sub-object 1135 // shall be initialized; 1136 // DR1460: 1137 // - if the class is a union having variant members, exactly one of them 1138 // shall be initialized; 1139 if (RD->isUnion()) { 1140 if (Constructor->getNumCtorInitializers() == 0 && 1141 RD->hasVariantMembers()) { 1142 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1143 return false; 1144 } 1145 } else if (!Constructor->isDependentContext() && 1146 !Constructor->isDelegatingConstructor()) { 1147 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1148 1149 // Skip detailed checking if we have enough initializers, and we would 1150 // allow at most one initializer per member. 1151 bool AnyAnonStructUnionMembers = false; 1152 unsigned Fields = 0; 1153 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1154 E = RD->field_end(); I != E; ++I, ++Fields) { 1155 if (I->isAnonymousStructOrUnion()) { 1156 AnyAnonStructUnionMembers = true; 1157 break; 1158 } 1159 } 1160 // DR1460: 1161 // - if the class is a union-like class, but is not a union, for each of 1162 // its anonymous union members having variant members, exactly one of 1163 // them shall be initialized; 1164 if (AnyAnonStructUnionMembers || 1165 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1166 // Check initialization of non-static data members. Base classes are 1167 // always initialized so do not need to be checked. Dependent bases 1168 // might not have initializers in the member initializer list. 1169 llvm::SmallSet<Decl*, 16> Inits; 1170 for (const auto *I: Constructor->inits()) { 1171 if (FieldDecl *FD = I->getMember()) 1172 Inits.insert(FD); 1173 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1174 Inits.insert(ID->chain_begin(), ID->chain_end()); 1175 } 1176 1177 bool Diagnosed = false; 1178 for (auto *I : RD->fields()) 1179 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1180 if (Diagnosed) 1181 return false; 1182 } 1183 } 1184 } else { 1185 if (ReturnStmts.empty()) { 1186 // C++1y doesn't require constexpr functions to contain a 'return' 1187 // statement. We still do, unless the return type might be void, because 1188 // otherwise if there's no return statement, the function cannot 1189 // be used in a core constant expression. 1190 bool OK = getLangOpts().CPlusPlus14 && 1191 (Dcl->getReturnType()->isVoidType() || 1192 Dcl->getReturnType()->isDependentType()); 1193 Diag(Dcl->getLocation(), 1194 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1195 : diag::err_constexpr_body_no_return); 1196 return OK; 1197 } 1198 if (ReturnStmts.size() > 1) { 1199 Diag(ReturnStmts.back(), 1200 getLangOpts().CPlusPlus14 1201 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1202 : diag::ext_constexpr_body_multiple_return); 1203 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1204 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1205 } 1206 } 1207 1208 // C++11 [dcl.constexpr]p5: 1209 // if no function argument values exist such that the function invocation 1210 // substitution would produce a constant expression, the program is 1211 // ill-formed; no diagnostic required. 1212 // C++11 [dcl.constexpr]p3: 1213 // - every constructor call and implicit conversion used in initializing the 1214 // return value shall be one of those allowed in a constant expression. 1215 // C++11 [dcl.constexpr]p4: 1216 // - every constructor involved in initializing non-static data members and 1217 // base class sub-objects shall be a constexpr constructor. 1218 SmallVector<PartialDiagnosticAt, 8> Diags; 1219 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1220 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1221 << isa<CXXConstructorDecl>(Dcl); 1222 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1223 Diag(Diags[I].first, Diags[I].second); 1224 // Don't return false here: we allow this for compatibility in 1225 // system headers. 1226 } 1227 1228 return true; 1229 } 1230 1231 /// isCurrentClassName - Determine whether the identifier II is the 1232 /// name of the class type currently being defined. In the case of 1233 /// nested classes, this will only return true if II is the name of 1234 /// the innermost class. 1235 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1236 const CXXScopeSpec *SS) { 1237 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1238 1239 CXXRecordDecl *CurDecl; 1240 if (SS && SS->isSet() && !SS->isInvalid()) { 1241 DeclContext *DC = computeDeclContext(*SS, true); 1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1243 } else 1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1245 1246 if (CurDecl && CurDecl->getIdentifier()) 1247 return &II == CurDecl->getIdentifier(); 1248 return false; 1249 } 1250 1251 /// \brief Determine whether the identifier II is a typo for the name of 1252 /// the class type currently being defined. If so, update it to the identifier 1253 /// that should have been used. 1254 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1255 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1256 1257 if (!getLangOpts().SpellChecking) 1258 return false; 1259 1260 CXXRecordDecl *CurDecl; 1261 if (SS && SS->isSet() && !SS->isInvalid()) { 1262 DeclContext *DC = computeDeclContext(*SS, true); 1263 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1264 } else 1265 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1266 1267 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1268 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1269 < II->getLength()) { 1270 II = CurDecl->getIdentifier(); 1271 return true; 1272 } 1273 1274 return false; 1275 } 1276 1277 /// \brief Determine whether the given class is a base class of the given 1278 /// class, including looking at dependent bases. 1279 static bool findCircularInheritance(const CXXRecordDecl *Class, 1280 const CXXRecordDecl *Current) { 1281 SmallVector<const CXXRecordDecl*, 8> Queue; 1282 1283 Class = Class->getCanonicalDecl(); 1284 while (true) { 1285 for (const auto &I : Current->bases()) { 1286 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1287 if (!Base) 1288 continue; 1289 1290 Base = Base->getDefinition(); 1291 if (!Base) 1292 continue; 1293 1294 if (Base->getCanonicalDecl() == Class) 1295 return true; 1296 1297 Queue.push_back(Base); 1298 } 1299 1300 if (Queue.empty()) 1301 return false; 1302 1303 Current = Queue.pop_back_val(); 1304 } 1305 1306 return false; 1307 } 1308 1309 /// \brief Perform propagation of DLL attributes from a derived class to a 1310 /// templated base class for MS compatibility. 1311 static void propagateDLLAttrToBaseClassTemplate( 1312 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1313 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1314 if (getDLLAttr( 1315 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1316 // If the base class template has a DLL attribute, don't try to change it. 1317 return; 1318 } 1319 1320 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1321 // If the base class is not already specialized, we can do the propagation. 1322 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1323 NewAttr->setInherited(true); 1324 BaseTemplateSpec->addAttr(NewAttr); 1325 return; 1326 } 1327 1328 bool DifferentAttribute = false; 1329 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1330 if (!SpecializationAttr->isInherited()) { 1331 // The template has previously been specialized or instantiated with an 1332 // explicit attribute. We should not try to change it. 1333 return; 1334 } 1335 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1336 // The specialization already has the right attribute. 1337 return; 1338 } 1339 DifferentAttribute = true; 1340 } 1341 1342 // The template was previously instantiated or explicitly specialized without 1343 // a dll attribute, or the template was previously instantiated with a 1344 // different inherited attribute. It's too late for us to change the 1345 // attribute, so warn that this is unsupported. 1346 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1347 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1348 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1349 if (BaseTemplateSpec->isExplicitSpecialization()) { 1350 S.Diag(BaseTemplateSpec->getLocation(), 1351 diag::note_template_class_explicit_specialization_was_here) 1352 << BaseTemplateSpec; 1353 } else { 1354 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1355 diag::note_template_class_instantiation_was_here) 1356 << BaseTemplateSpec; 1357 } 1358 } 1359 1360 /// \brief Check the validity of a C++ base class specifier. 1361 /// 1362 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1363 /// and returns NULL otherwise. 1364 CXXBaseSpecifier * 1365 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1366 SourceRange SpecifierRange, 1367 bool Virtual, AccessSpecifier Access, 1368 TypeSourceInfo *TInfo, 1369 SourceLocation EllipsisLoc) { 1370 QualType BaseType = TInfo->getType(); 1371 1372 // C++ [class.union]p1: 1373 // A union shall not have base classes. 1374 if (Class->isUnion()) { 1375 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1376 << SpecifierRange; 1377 return nullptr; 1378 } 1379 1380 if (EllipsisLoc.isValid() && 1381 !TInfo->getType()->containsUnexpandedParameterPack()) { 1382 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1383 << TInfo->getTypeLoc().getSourceRange(); 1384 EllipsisLoc = SourceLocation(); 1385 } 1386 1387 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1388 1389 if (BaseType->isDependentType()) { 1390 // Make sure that we don't have circular inheritance among our dependent 1391 // bases. For non-dependent bases, the check for completeness below handles 1392 // this. 1393 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1394 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1395 ((BaseDecl = BaseDecl->getDefinition()) && 1396 findCircularInheritance(Class, BaseDecl))) { 1397 Diag(BaseLoc, diag::err_circular_inheritance) 1398 << BaseType << Context.getTypeDeclType(Class); 1399 1400 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1401 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1402 << BaseType; 1403 1404 return nullptr; 1405 } 1406 } 1407 1408 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1409 Class->getTagKind() == TTK_Class, 1410 Access, TInfo, EllipsisLoc); 1411 } 1412 1413 // Base specifiers must be record types. 1414 if (!BaseType->isRecordType()) { 1415 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1416 return nullptr; 1417 } 1418 1419 // C++ [class.union]p1: 1420 // A union shall not be used as a base class. 1421 if (BaseType->isUnionType()) { 1422 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1423 return nullptr; 1424 } 1425 1426 // For the MS ABI, propagate DLL attributes to base class templates. 1427 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1428 if (Attr *ClassAttr = getDLLAttr(Class)) { 1429 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1430 BaseType->getAsCXXRecordDecl())) { 1431 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1432 BaseTemplate, BaseLoc); 1433 } 1434 } 1435 } 1436 1437 // C++ [class.derived]p2: 1438 // The class-name in a base-specifier shall not be an incompletely 1439 // defined class. 1440 if (RequireCompleteType(BaseLoc, BaseType, 1441 diag::err_incomplete_base_class, SpecifierRange)) { 1442 Class->setInvalidDecl(); 1443 return nullptr; 1444 } 1445 1446 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1447 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1448 assert(BaseDecl && "Record type has no declaration"); 1449 BaseDecl = BaseDecl->getDefinition(); 1450 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1451 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1452 assert(CXXBaseDecl && "Base type is not a C++ type"); 1453 1454 // A class which contains a flexible array member is not suitable for use as a 1455 // base class: 1456 // - If the layout determines that a base comes before another base, 1457 // the flexible array member would index into the subsequent base. 1458 // - If the layout determines that base comes before the derived class, 1459 // the flexible array member would index into the derived class. 1460 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1461 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1462 << CXXBaseDecl->getDeclName(); 1463 return nullptr; 1464 } 1465 1466 // C++ [class]p3: 1467 // If a class is marked final and it appears as a base-type-specifier in 1468 // base-clause, the program is ill-formed. 1469 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1470 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1471 << CXXBaseDecl->getDeclName() 1472 << FA->isSpelledAsSealed(); 1473 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1474 << CXXBaseDecl->getDeclName() << FA->getRange(); 1475 return nullptr; 1476 } 1477 1478 if (BaseDecl->isInvalidDecl()) 1479 Class->setInvalidDecl(); 1480 1481 // Create the base specifier. 1482 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1483 Class->getTagKind() == TTK_Class, 1484 Access, TInfo, EllipsisLoc); 1485 } 1486 1487 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1488 /// one entry in the base class list of a class specifier, for 1489 /// example: 1490 /// class foo : public bar, virtual private baz { 1491 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1492 BaseResult 1493 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1494 ParsedAttributes &Attributes, 1495 bool Virtual, AccessSpecifier Access, 1496 ParsedType basetype, SourceLocation BaseLoc, 1497 SourceLocation EllipsisLoc) { 1498 if (!classdecl) 1499 return true; 1500 1501 AdjustDeclIfTemplate(classdecl); 1502 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1503 if (!Class) 1504 return true; 1505 1506 // We haven't yet attached the base specifiers. 1507 Class->setIsParsingBaseSpecifiers(); 1508 1509 // We do not support any C++11 attributes on base-specifiers yet. 1510 // Diagnose any attributes we see. 1511 if (!Attributes.empty()) { 1512 for (AttributeList *Attr = Attributes.getList(); Attr; 1513 Attr = Attr->getNext()) { 1514 if (Attr->isInvalid() || 1515 Attr->getKind() == AttributeList::IgnoredAttribute) 1516 continue; 1517 Diag(Attr->getLoc(), 1518 Attr->getKind() == AttributeList::UnknownAttribute 1519 ? diag::warn_unknown_attribute_ignored 1520 : diag::err_base_specifier_attribute) 1521 << Attr->getName(); 1522 } 1523 } 1524 1525 TypeSourceInfo *TInfo = nullptr; 1526 GetTypeFromParser(basetype, &TInfo); 1527 1528 if (EllipsisLoc.isInvalid() && 1529 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1530 UPPC_BaseType)) 1531 return true; 1532 1533 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1534 Virtual, Access, TInfo, 1535 EllipsisLoc)) 1536 return BaseSpec; 1537 else 1538 Class->setInvalidDecl(); 1539 1540 return true; 1541 } 1542 1543 /// \brief Performs the actual work of attaching the given base class 1544 /// specifiers to a C++ class. 1545 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1546 unsigned NumBases) { 1547 if (NumBases == 0) 1548 return false; 1549 1550 // Used to keep track of which base types we have already seen, so 1551 // that we can properly diagnose redundant direct base types. Note 1552 // that the key is always the unqualified canonical type of the base 1553 // class. 1554 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1555 1556 // Copy non-redundant base specifiers into permanent storage. 1557 unsigned NumGoodBases = 0; 1558 bool Invalid = false; 1559 for (unsigned idx = 0; idx < NumBases; ++idx) { 1560 QualType NewBaseType 1561 = Context.getCanonicalType(Bases[idx]->getType()); 1562 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1563 1564 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1565 if (KnownBase) { 1566 // C++ [class.mi]p3: 1567 // A class shall not be specified as a direct base class of a 1568 // derived class more than once. 1569 Diag(Bases[idx]->getLocStart(), 1570 diag::err_duplicate_base_class) 1571 << KnownBase->getType() 1572 << Bases[idx]->getSourceRange(); 1573 1574 // Delete the duplicate base class specifier; we're going to 1575 // overwrite its pointer later. 1576 Context.Deallocate(Bases[idx]); 1577 1578 Invalid = true; 1579 } else { 1580 // Okay, add this new base class. 1581 KnownBase = Bases[idx]; 1582 Bases[NumGoodBases++] = Bases[idx]; 1583 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1584 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1585 if (Class->isInterface() && 1586 (!RD->isInterface() || 1587 KnownBase->getAccessSpecifier() != AS_public)) { 1588 // The Microsoft extension __interface does not permit bases that 1589 // are not themselves public interfaces. 1590 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1591 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1592 << RD->getSourceRange(); 1593 Invalid = true; 1594 } 1595 if (RD->hasAttr<WeakAttr>()) 1596 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1597 } 1598 } 1599 } 1600 1601 // Attach the remaining base class specifiers to the derived class. 1602 Class->setBases(Bases, NumGoodBases); 1603 1604 // Delete the remaining (good) base class specifiers, since their 1605 // data has been copied into the CXXRecordDecl. 1606 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1607 Context.Deallocate(Bases[idx]); 1608 1609 return Invalid; 1610 } 1611 1612 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1613 /// class, after checking whether there are any duplicate base 1614 /// classes. 1615 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1616 unsigned NumBases) { 1617 if (!ClassDecl || !Bases || !NumBases) 1618 return; 1619 1620 AdjustDeclIfTemplate(ClassDecl); 1621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1622 } 1623 1624 /// \brief Determine whether the type \p Derived is a C++ class that is 1625 /// derived from the type \p Base. 1626 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1627 if (!getLangOpts().CPlusPlus) 1628 return false; 1629 1630 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1631 if (!DerivedRD) 1632 return false; 1633 1634 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1635 if (!BaseRD) 1636 return false; 1637 1638 // If either the base or the derived type is invalid, don't try to 1639 // check whether one is derived from the other. 1640 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1641 return false; 1642 1643 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1644 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1645 } 1646 1647 /// \brief Determine whether the type \p Derived is a C++ class that is 1648 /// derived from the type \p Base. 1649 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1650 if (!getLangOpts().CPlusPlus) 1651 return false; 1652 1653 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1654 if (!DerivedRD) 1655 return false; 1656 1657 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1658 if (!BaseRD) 1659 return false; 1660 1661 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1662 } 1663 1664 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1665 CXXCastPath &BasePathArray) { 1666 assert(BasePathArray.empty() && "Base path array must be empty!"); 1667 assert(Paths.isRecordingPaths() && "Must record paths!"); 1668 1669 const CXXBasePath &Path = Paths.front(); 1670 1671 // We first go backward and check if we have a virtual base. 1672 // FIXME: It would be better if CXXBasePath had the base specifier for 1673 // the nearest virtual base. 1674 unsigned Start = 0; 1675 for (unsigned I = Path.size(); I != 0; --I) { 1676 if (Path[I - 1].Base->isVirtual()) { 1677 Start = I - 1; 1678 break; 1679 } 1680 } 1681 1682 // Now add all bases. 1683 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1684 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1685 } 1686 1687 /// \brief Determine whether the given base path includes a virtual 1688 /// base class. 1689 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1690 for (CXXCastPath::const_iterator B = BasePath.begin(), 1691 BEnd = BasePath.end(); 1692 B != BEnd; ++B) 1693 if ((*B)->isVirtual()) 1694 return true; 1695 1696 return false; 1697 } 1698 1699 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1700 /// conversion (where Derived and Base are class types) is 1701 /// well-formed, meaning that the conversion is unambiguous (and 1702 /// that all of the base classes are accessible). Returns true 1703 /// and emits a diagnostic if the code is ill-formed, returns false 1704 /// otherwise. Loc is the location where this routine should point to 1705 /// if there is an error, and Range is the source range to highlight 1706 /// if there is an error. 1707 bool 1708 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1709 unsigned InaccessibleBaseID, 1710 unsigned AmbigiousBaseConvID, 1711 SourceLocation Loc, SourceRange Range, 1712 DeclarationName Name, 1713 CXXCastPath *BasePath) { 1714 // First, determine whether the path from Derived to Base is 1715 // ambiguous. This is slightly more expensive than checking whether 1716 // the Derived to Base conversion exists, because here we need to 1717 // explore multiple paths to determine if there is an ambiguity. 1718 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1719 /*DetectVirtual=*/false); 1720 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1721 assert(DerivationOkay && 1722 "Can only be used with a derived-to-base conversion"); 1723 (void)DerivationOkay; 1724 1725 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1726 if (InaccessibleBaseID) { 1727 // Check that the base class can be accessed. 1728 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1729 InaccessibleBaseID)) { 1730 case AR_inaccessible: 1731 return true; 1732 case AR_accessible: 1733 case AR_dependent: 1734 case AR_delayed: 1735 break; 1736 } 1737 } 1738 1739 // Build a base path if necessary. 1740 if (BasePath) 1741 BuildBasePathArray(Paths, *BasePath); 1742 return false; 1743 } 1744 1745 if (AmbigiousBaseConvID) { 1746 // We know that the derived-to-base conversion is ambiguous, and 1747 // we're going to produce a diagnostic. Perform the derived-to-base 1748 // search just one more time to compute all of the possible paths so 1749 // that we can print them out. This is more expensive than any of 1750 // the previous derived-to-base checks we've done, but at this point 1751 // performance isn't as much of an issue. 1752 Paths.clear(); 1753 Paths.setRecordingPaths(true); 1754 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1755 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1756 (void)StillOkay; 1757 1758 // Build up a textual representation of the ambiguous paths, e.g., 1759 // D -> B -> A, that will be used to illustrate the ambiguous 1760 // conversions in the diagnostic. We only print one of the paths 1761 // to each base class subobject. 1762 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1763 1764 Diag(Loc, AmbigiousBaseConvID) 1765 << Derived << Base << PathDisplayStr << Range << Name; 1766 } 1767 return true; 1768 } 1769 1770 bool 1771 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1772 SourceLocation Loc, SourceRange Range, 1773 CXXCastPath *BasePath, 1774 bool IgnoreAccess) { 1775 return CheckDerivedToBaseConversion(Derived, Base, 1776 IgnoreAccess ? 0 1777 : diag::err_upcast_to_inaccessible_base, 1778 diag::err_ambiguous_derived_to_base_conv, 1779 Loc, Range, DeclarationName(), 1780 BasePath); 1781 } 1782 1783 1784 /// @brief Builds a string representing ambiguous paths from a 1785 /// specific derived class to different subobjects of the same base 1786 /// class. 1787 /// 1788 /// This function builds a string that can be used in error messages 1789 /// to show the different paths that one can take through the 1790 /// inheritance hierarchy to go from the derived class to different 1791 /// subobjects of a base class. The result looks something like this: 1792 /// @code 1793 /// struct D -> struct B -> struct A 1794 /// struct D -> struct C -> struct A 1795 /// @endcode 1796 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1797 std::string PathDisplayStr; 1798 std::set<unsigned> DisplayedPaths; 1799 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1800 Path != Paths.end(); ++Path) { 1801 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1802 // We haven't displayed a path to this particular base 1803 // class subobject yet. 1804 PathDisplayStr += "\n "; 1805 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1806 for (CXXBasePath::const_iterator Element = Path->begin(); 1807 Element != Path->end(); ++Element) 1808 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1809 } 1810 } 1811 1812 return PathDisplayStr; 1813 } 1814 1815 //===----------------------------------------------------------------------===// 1816 // C++ class member Handling 1817 //===----------------------------------------------------------------------===// 1818 1819 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1820 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1821 SourceLocation ASLoc, 1822 SourceLocation ColonLoc, 1823 AttributeList *Attrs) { 1824 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1825 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1826 ASLoc, ColonLoc); 1827 CurContext->addHiddenDecl(ASDecl); 1828 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1829 } 1830 1831 /// CheckOverrideControl - Check C++11 override control semantics. 1832 void Sema::CheckOverrideControl(NamedDecl *D) { 1833 if (D->isInvalidDecl()) 1834 return; 1835 1836 // We only care about "override" and "final" declarations. 1837 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1838 return; 1839 1840 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1841 1842 // We can't check dependent instance methods. 1843 if (MD && MD->isInstance() && 1844 (MD->getParent()->hasAnyDependentBases() || 1845 MD->getType()->isDependentType())) 1846 return; 1847 1848 if (MD && !MD->isVirtual()) { 1849 // If we have a non-virtual method, check if if hides a virtual method. 1850 // (In that case, it's most likely the method has the wrong type.) 1851 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1852 FindHiddenVirtualMethods(MD, OverloadedMethods); 1853 1854 if (!OverloadedMethods.empty()) { 1855 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1856 Diag(OA->getLocation(), 1857 diag::override_keyword_hides_virtual_member_function) 1858 << "override" << (OverloadedMethods.size() > 1); 1859 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1860 Diag(FA->getLocation(), 1861 diag::override_keyword_hides_virtual_member_function) 1862 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1863 << (OverloadedMethods.size() > 1); 1864 } 1865 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1866 MD->setInvalidDecl(); 1867 return; 1868 } 1869 // Fall through into the general case diagnostic. 1870 // FIXME: We might want to attempt typo correction here. 1871 } 1872 1873 if (!MD || !MD->isVirtual()) { 1874 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1875 Diag(OA->getLocation(), 1876 diag::override_keyword_only_allowed_on_virtual_member_functions) 1877 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1878 D->dropAttr<OverrideAttr>(); 1879 } 1880 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1881 Diag(FA->getLocation(), 1882 diag::override_keyword_only_allowed_on_virtual_member_functions) 1883 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1884 << FixItHint::CreateRemoval(FA->getLocation()); 1885 D->dropAttr<FinalAttr>(); 1886 } 1887 return; 1888 } 1889 1890 // C++11 [class.virtual]p5: 1891 // If a function is marked with the virt-specifier override and 1892 // does not override a member function of a base class, the program is 1893 // ill-formed. 1894 bool HasOverriddenMethods = 1895 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1896 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1897 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1898 << MD->getDeclName(); 1899 } 1900 1901 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1902 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1903 return; 1904 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1905 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1906 isa<CXXDestructorDecl>(MD)) 1907 return; 1908 1909 SourceLocation Loc = MD->getLocation(); 1910 SourceLocation SpellingLoc = Loc; 1911 if (getSourceManager().isMacroArgExpansion(Loc)) 1912 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1913 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1914 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1915 return; 1916 1917 if (MD->size_overridden_methods() > 0) { 1918 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1919 << MD->getDeclName(); 1920 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1921 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1922 } 1923 } 1924 1925 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1926 /// function overrides a virtual member function marked 'final', according to 1927 /// C++11 [class.virtual]p4. 1928 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1929 const CXXMethodDecl *Old) { 1930 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1931 if (!FA) 1932 return false; 1933 1934 Diag(New->getLocation(), diag::err_final_function_overridden) 1935 << New->getDeclName() 1936 << FA->isSpelledAsSealed(); 1937 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1938 return true; 1939 } 1940 1941 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1942 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1943 // FIXME: Destruction of ObjC lifetime types has side-effects. 1944 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1945 return !RD->isCompleteDefinition() || 1946 !RD->hasTrivialDefaultConstructor() || 1947 !RD->hasTrivialDestructor(); 1948 return false; 1949 } 1950 1951 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1952 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1953 if (it->isDeclspecPropertyAttribute()) 1954 return it; 1955 return nullptr; 1956 } 1957 1958 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1959 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1960 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1961 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1962 /// present (but parsing it has been deferred). 1963 NamedDecl * 1964 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1965 MultiTemplateParamsArg TemplateParameterLists, 1966 Expr *BW, const VirtSpecifiers &VS, 1967 InClassInitStyle InitStyle) { 1968 const DeclSpec &DS = D.getDeclSpec(); 1969 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1970 DeclarationName Name = NameInfo.getName(); 1971 SourceLocation Loc = NameInfo.getLoc(); 1972 1973 // For anonymous bitfields, the location should point to the type. 1974 if (Loc.isInvalid()) 1975 Loc = D.getLocStart(); 1976 1977 Expr *BitWidth = static_cast<Expr*>(BW); 1978 1979 assert(isa<CXXRecordDecl>(CurContext)); 1980 assert(!DS.isFriendSpecified()); 1981 1982 bool isFunc = D.isDeclarationOfFunction(); 1983 1984 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1985 // The Microsoft extension __interface only permits public member functions 1986 // and prohibits constructors, destructors, operators, non-public member 1987 // functions, static methods and data members. 1988 unsigned InvalidDecl; 1989 bool ShowDeclName = true; 1990 if (!isFunc) 1991 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1992 else if (AS != AS_public) 1993 InvalidDecl = 2; 1994 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1995 InvalidDecl = 3; 1996 else switch (Name.getNameKind()) { 1997 case DeclarationName::CXXConstructorName: 1998 InvalidDecl = 4; 1999 ShowDeclName = false; 2000 break; 2001 2002 case DeclarationName::CXXDestructorName: 2003 InvalidDecl = 5; 2004 ShowDeclName = false; 2005 break; 2006 2007 case DeclarationName::CXXOperatorName: 2008 case DeclarationName::CXXConversionFunctionName: 2009 InvalidDecl = 6; 2010 break; 2011 2012 default: 2013 InvalidDecl = 0; 2014 break; 2015 } 2016 2017 if (InvalidDecl) { 2018 if (ShowDeclName) 2019 Diag(Loc, diag::err_invalid_member_in_interface) 2020 << (InvalidDecl-1) << Name; 2021 else 2022 Diag(Loc, diag::err_invalid_member_in_interface) 2023 << (InvalidDecl-1) << ""; 2024 return nullptr; 2025 } 2026 } 2027 2028 // C++ 9.2p6: A member shall not be declared to have automatic storage 2029 // duration (auto, register) or with the extern storage-class-specifier. 2030 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2031 // data members and cannot be applied to names declared const or static, 2032 // and cannot be applied to reference members. 2033 switch (DS.getStorageClassSpec()) { 2034 case DeclSpec::SCS_unspecified: 2035 case DeclSpec::SCS_typedef: 2036 case DeclSpec::SCS_static: 2037 break; 2038 case DeclSpec::SCS_mutable: 2039 if (isFunc) { 2040 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2041 2042 // FIXME: It would be nicer if the keyword was ignored only for this 2043 // declarator. Otherwise we could get follow-up errors. 2044 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2045 } 2046 break; 2047 default: 2048 Diag(DS.getStorageClassSpecLoc(), 2049 diag::err_storageclass_invalid_for_member); 2050 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2051 break; 2052 } 2053 2054 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2055 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2056 !isFunc); 2057 2058 if (DS.isConstexprSpecified() && isInstField) { 2059 SemaDiagnosticBuilder B = 2060 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2061 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2062 if (InitStyle == ICIS_NoInit) { 2063 B << 0 << 0; 2064 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2065 B << FixItHint::CreateRemoval(ConstexprLoc); 2066 else { 2067 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2068 D.getMutableDeclSpec().ClearConstexprSpec(); 2069 const char *PrevSpec; 2070 unsigned DiagID; 2071 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2072 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2073 (void)Failed; 2074 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2075 } 2076 } else { 2077 B << 1; 2078 const char *PrevSpec; 2079 unsigned DiagID; 2080 if (D.getMutableDeclSpec().SetStorageClassSpec( 2081 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2082 Context.getPrintingPolicy())) { 2083 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2084 "This is the only DeclSpec that should fail to be applied"); 2085 B << 1; 2086 } else { 2087 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2088 isInstField = false; 2089 } 2090 } 2091 } 2092 2093 NamedDecl *Member; 2094 if (isInstField) { 2095 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2096 2097 // Data members must have identifiers for names. 2098 if (!Name.isIdentifier()) { 2099 Diag(Loc, diag::err_bad_variable_name) 2100 << Name; 2101 return nullptr; 2102 } 2103 2104 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2105 2106 // Member field could not be with "template" keyword. 2107 // So TemplateParameterLists should be empty in this case. 2108 if (TemplateParameterLists.size()) { 2109 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2110 if (TemplateParams->size()) { 2111 // There is no such thing as a member field template. 2112 Diag(D.getIdentifierLoc(), diag::err_template_member) 2113 << II 2114 << SourceRange(TemplateParams->getTemplateLoc(), 2115 TemplateParams->getRAngleLoc()); 2116 } else { 2117 // There is an extraneous 'template<>' for this member. 2118 Diag(TemplateParams->getTemplateLoc(), 2119 diag::err_template_member_noparams) 2120 << II 2121 << SourceRange(TemplateParams->getTemplateLoc(), 2122 TemplateParams->getRAngleLoc()); 2123 } 2124 return nullptr; 2125 } 2126 2127 if (SS.isSet() && !SS.isInvalid()) { 2128 // The user provided a superfluous scope specifier inside a class 2129 // definition: 2130 // 2131 // class X { 2132 // int X::member; 2133 // }; 2134 if (DeclContext *DC = computeDeclContext(SS, false)) 2135 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2136 else 2137 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2138 << Name << SS.getRange(); 2139 2140 SS.clear(); 2141 } 2142 2143 AttributeList *MSPropertyAttr = 2144 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2145 if (MSPropertyAttr) { 2146 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2147 BitWidth, InitStyle, AS, MSPropertyAttr); 2148 if (!Member) 2149 return nullptr; 2150 isInstField = false; 2151 } else { 2152 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2153 BitWidth, InitStyle, AS); 2154 assert(Member && "HandleField never returns null"); 2155 } 2156 } else { 2157 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2158 2159 Member = HandleDeclarator(S, D, TemplateParameterLists); 2160 if (!Member) 2161 return nullptr; 2162 2163 // Non-instance-fields can't have a bitfield. 2164 if (BitWidth) { 2165 if (Member->isInvalidDecl()) { 2166 // don't emit another diagnostic. 2167 } else if (isa<VarDecl>(Member)) { 2168 // C++ 9.6p3: A bit-field shall not be a static member. 2169 // "static member 'A' cannot be a bit-field" 2170 Diag(Loc, diag::err_static_not_bitfield) 2171 << Name << BitWidth->getSourceRange(); 2172 } else if (isa<TypedefDecl>(Member)) { 2173 // "typedef member 'x' cannot be a bit-field" 2174 Diag(Loc, diag::err_typedef_not_bitfield) 2175 << Name << BitWidth->getSourceRange(); 2176 } else { 2177 // A function typedef ("typedef int f(); f a;"). 2178 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2179 Diag(Loc, diag::err_not_integral_type_bitfield) 2180 << Name << cast<ValueDecl>(Member)->getType() 2181 << BitWidth->getSourceRange(); 2182 } 2183 2184 BitWidth = nullptr; 2185 Member->setInvalidDecl(); 2186 } 2187 2188 Member->setAccess(AS); 2189 2190 // If we have declared a member function template or static data member 2191 // template, set the access of the templated declaration as well. 2192 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2193 FunTmpl->getTemplatedDecl()->setAccess(AS); 2194 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2195 VarTmpl->getTemplatedDecl()->setAccess(AS); 2196 } 2197 2198 if (VS.isOverrideSpecified()) 2199 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2200 if (VS.isFinalSpecified()) 2201 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2202 VS.isFinalSpelledSealed())); 2203 2204 if (VS.getLastLocation().isValid()) { 2205 // Update the end location of a method that has a virt-specifiers. 2206 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2207 MD->setRangeEnd(VS.getLastLocation()); 2208 } 2209 2210 CheckOverrideControl(Member); 2211 2212 assert((Name || isInstField) && "No identifier for non-field ?"); 2213 2214 if (isInstField) { 2215 FieldDecl *FD = cast<FieldDecl>(Member); 2216 FieldCollector->Add(FD); 2217 2218 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2219 // Remember all explicit private FieldDecls that have a name, no side 2220 // effects and are not part of a dependent type declaration. 2221 if (!FD->isImplicit() && FD->getDeclName() && 2222 FD->getAccess() == AS_private && 2223 !FD->hasAttr<UnusedAttr>() && 2224 !FD->getParent()->isDependentContext() && 2225 !InitializationHasSideEffects(*FD)) 2226 UnusedPrivateFields.insert(FD); 2227 } 2228 } 2229 2230 return Member; 2231 } 2232 2233 namespace { 2234 class UninitializedFieldVisitor 2235 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2236 Sema &S; 2237 // List of Decls to generate a warning on. Also remove Decls that become 2238 // initialized. 2239 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2240 // Vector of decls to be removed from the Decl set prior to visiting the 2241 // nodes. These Decls may have been initialized in the prior initializer. 2242 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2243 // If non-null, add a note to the warning pointing back to the constructor. 2244 const CXXConstructorDecl *Constructor; 2245 // Variables to hold state when processing an initializer list. When 2246 // InitList is true, special case initialization of FieldDecls matching 2247 // InitListFieldDecl. 2248 bool InitList; 2249 FieldDecl *InitListFieldDecl; 2250 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2251 2252 public: 2253 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2254 UninitializedFieldVisitor(Sema &S, 2255 llvm::SmallPtrSetImpl<ValueDecl*> &Decls) 2256 : Inherited(S.Context), S(S), Decls(Decls), Constructor(nullptr), 2257 InitList(false), InitListFieldDecl(nullptr) {} 2258 2259 // Returns true if the use of ME is not an uninitialized use. 2260 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2261 bool CheckReferenceOnly) { 2262 llvm::SmallVector<FieldDecl*, 4> Fields; 2263 bool ReferenceField = false; 2264 while (ME) { 2265 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2266 if (!FD) 2267 return false; 2268 Fields.push_back(FD); 2269 if (FD->getType()->isReferenceType()) 2270 ReferenceField = true; 2271 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2272 } 2273 2274 // Binding a reference to an unintialized field is not an 2275 // uninitialized use. 2276 if (CheckReferenceOnly && !ReferenceField) 2277 return true; 2278 2279 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2280 // Discard the first field since it is the field decl that is being 2281 // initialized. 2282 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2283 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2284 } 2285 2286 for (auto UsedIter = UsedFieldIndex.begin(), 2287 UsedEnd = UsedFieldIndex.end(), 2288 OrigIter = InitFieldIndex.begin(), 2289 OrigEnd = InitFieldIndex.end(); 2290 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2291 if (*UsedIter < *OrigIter) 2292 return true; 2293 if (*UsedIter > *OrigIter) 2294 break; 2295 } 2296 2297 return false; 2298 } 2299 2300 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2301 bool AddressOf) { 2302 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2303 return; 2304 2305 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2306 // or union. 2307 MemberExpr *FieldME = ME; 2308 2309 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2310 2311 Expr *Base = ME; 2312 while (MemberExpr *SubME = dyn_cast<MemberExpr>(Base)) { 2313 2314 if (isa<VarDecl>(SubME->getMemberDecl())) 2315 return; 2316 2317 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2318 if (!FD->isAnonymousStructOrUnion()) 2319 FieldME = SubME; 2320 2321 if (!FieldME->getType().isPODType(S.Context)) 2322 AllPODFields = false; 2323 2324 Base = SubME->getBase()->IgnoreParenImpCasts(); 2325 } 2326 2327 if (!isa<CXXThisExpr>(Base)) 2328 return; 2329 2330 if (AddressOf && AllPODFields) 2331 return; 2332 2333 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2334 2335 if (!Decls.count(FoundVD)) 2336 return; 2337 2338 const bool IsReference = FoundVD->getType()->isReferenceType(); 2339 2340 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2341 // Special checking for initializer lists. 2342 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2343 return; 2344 } 2345 } else { 2346 // Prevent double warnings on use of unbounded references. 2347 if (CheckReferenceOnly && !IsReference) 2348 return; 2349 } 2350 2351 unsigned diag = IsReference 2352 ? diag::warn_reference_field_is_uninit 2353 : diag::warn_field_is_uninit; 2354 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2355 if (Constructor) 2356 S.Diag(Constructor->getLocation(), 2357 diag::note_uninit_in_this_constructor) 2358 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2359 2360 } 2361 2362 void HandleValue(Expr *E, bool AddressOf) { 2363 E = E->IgnoreParens(); 2364 2365 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2366 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2367 AddressOf /*AddressOf*/); 2368 return; 2369 } 2370 2371 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2372 Visit(CO->getCond()); 2373 HandleValue(CO->getTrueExpr(), AddressOf); 2374 HandleValue(CO->getFalseExpr(), AddressOf); 2375 return; 2376 } 2377 2378 if (BinaryConditionalOperator *BCO = 2379 dyn_cast<BinaryConditionalOperator>(E)) { 2380 Visit(BCO->getCond()); 2381 HandleValue(BCO->getFalseExpr(), AddressOf); 2382 return; 2383 } 2384 2385 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2386 HandleValue(OVE->getSourceExpr(), AddressOf); 2387 return; 2388 } 2389 2390 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2391 switch (BO->getOpcode()) { 2392 default: 2393 break; 2394 case(BO_PtrMemD): 2395 case(BO_PtrMemI): 2396 HandleValue(BO->getLHS(), AddressOf); 2397 Visit(BO->getRHS()); 2398 return; 2399 case(BO_Comma): 2400 Visit(BO->getLHS()); 2401 HandleValue(BO->getRHS(), AddressOf); 2402 return; 2403 } 2404 } 2405 2406 Visit(E); 2407 } 2408 2409 void CheckInitListExpr(InitListExpr *ILE) { 2410 InitFieldIndex.push_back(0); 2411 for (auto Child : ILE->children()) { 2412 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2413 CheckInitListExpr(SubList); 2414 } else { 2415 Visit(Child); 2416 } 2417 ++InitFieldIndex.back(); 2418 } 2419 InitFieldIndex.pop_back(); 2420 } 2421 2422 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2423 FieldDecl *Field) { 2424 // Remove Decls that may have been initialized in the previous 2425 // initializer. 2426 for (ValueDecl* VD : DeclsToRemove) 2427 Decls.erase(VD); 2428 DeclsToRemove.clear(); 2429 2430 Constructor = FieldConstructor; 2431 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2432 2433 if (ILE && Field) { 2434 InitList = true; 2435 InitListFieldDecl = Field; 2436 InitFieldIndex.clear(); 2437 CheckInitListExpr(ILE); 2438 } else { 2439 InitList = false; 2440 Visit(E); 2441 } 2442 2443 if (Field) 2444 Decls.erase(Field); 2445 } 2446 2447 void VisitMemberExpr(MemberExpr *ME) { 2448 // All uses of unbounded reference fields will warn. 2449 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2450 } 2451 2452 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2453 if (E->getCastKind() == CK_LValueToRValue) { 2454 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2455 return; 2456 } 2457 2458 Inherited::VisitImplicitCastExpr(E); 2459 } 2460 2461 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2462 if (E->getConstructor()->isCopyConstructor()) { 2463 Expr *ArgExpr = E->getArg(0); 2464 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2465 if (ILE->getNumInits() == 1) 2466 ArgExpr = ILE->getInit(0); 2467 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2468 if (ICE->getCastKind() == CK_NoOp) 2469 ArgExpr = ICE->getSubExpr(); 2470 HandleValue(ArgExpr, false /*AddressOf*/); 2471 return; 2472 } 2473 Inherited::VisitCXXConstructExpr(E); 2474 } 2475 2476 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2477 Expr *Callee = E->getCallee(); 2478 if (isa<MemberExpr>(Callee)) { 2479 HandleValue(Callee, false /*AddressOf*/); 2480 for (auto Arg : E->arguments()) 2481 Visit(Arg); 2482 return; 2483 } 2484 2485 Inherited::VisitCXXMemberCallExpr(E); 2486 } 2487 2488 void VisitCallExpr(CallExpr *E) { 2489 // Treat std::move as a use. 2490 if (E->getNumArgs() == 1) { 2491 if (FunctionDecl *FD = E->getDirectCallee()) { 2492 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) { 2493 HandleValue(E->getArg(0), false /*AddressOf*/); 2494 return; 2495 } 2496 } 2497 } 2498 2499 Inherited::VisitCallExpr(E); 2500 } 2501 2502 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2503 Expr *Callee = E->getCallee(); 2504 2505 if (isa<UnresolvedLookupExpr>(Callee)) 2506 return Inherited::VisitCXXOperatorCallExpr(E); 2507 2508 Visit(Callee); 2509 for (auto Arg : E->arguments()) 2510 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2511 } 2512 2513 void VisitBinaryOperator(BinaryOperator *E) { 2514 // If a field assignment is detected, remove the field from the 2515 // uninitiailized field set. 2516 if (E->getOpcode() == BO_Assign) 2517 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2518 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2519 if (!FD->getType()->isReferenceType()) 2520 DeclsToRemove.push_back(FD); 2521 2522 if (E->isCompoundAssignmentOp()) { 2523 HandleValue(E->getLHS(), false /*AddressOf*/); 2524 Visit(E->getRHS()); 2525 return; 2526 } 2527 2528 Inherited::VisitBinaryOperator(E); 2529 } 2530 2531 void VisitUnaryOperator(UnaryOperator *E) { 2532 if (E->isIncrementDecrementOp()) { 2533 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2534 return; 2535 } 2536 if (E->getOpcode() == UO_AddrOf) { 2537 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2538 HandleValue(ME->getBase(), true /*AddressOf*/); 2539 return; 2540 } 2541 } 2542 2543 Inherited::VisitUnaryOperator(E); 2544 } 2545 }; 2546 2547 // Diagnose value-uses of fields to initialize themselves, e.g. 2548 // foo(foo) 2549 // where foo is not also a parameter to the constructor. 2550 // Also diagnose across field uninitialized use such as 2551 // x(y), y(x) 2552 // TODO: implement -Wuninitialized and fold this into that framework. 2553 static void DiagnoseUninitializedFields( 2554 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2555 2556 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2557 Constructor->getLocation())) { 2558 return; 2559 } 2560 2561 if (Constructor->isInvalidDecl()) 2562 return; 2563 2564 const CXXRecordDecl *RD = Constructor->getParent(); 2565 2566 if (RD->getDescribedClassTemplate()) 2567 return; 2568 2569 // Holds fields that are uninitialized. 2570 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2571 2572 // At the beginning, all fields are uninitialized. 2573 for (auto *I : RD->decls()) { 2574 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2575 UninitializedFields.insert(FD); 2576 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2577 UninitializedFields.insert(IFD->getAnonField()); 2578 } 2579 } 2580 2581 if (UninitializedFields.empty()) 2582 return; 2583 2584 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2585 UninitializedFields); 2586 2587 for (const auto *FieldInit : Constructor->inits()) { 2588 if (UninitializedFields.empty()) 2589 break; 2590 2591 Expr *InitExpr = FieldInit->getInit(); 2592 if (!InitExpr) 2593 continue; 2594 2595 if (CXXDefaultInitExpr *Default = 2596 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2597 InitExpr = Default->getExpr(); 2598 if (!InitExpr) 2599 continue; 2600 // In class initializers will point to the constructor. 2601 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2602 FieldInit->getAnyMember()); 2603 } else { 2604 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2605 FieldInit->getAnyMember()); 2606 } 2607 } 2608 } 2609 } // namespace 2610 2611 /// \brief Enter a new C++ default initializer scope. After calling this, the 2612 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2613 /// parsing or instantiating the initializer failed. 2614 void Sema::ActOnStartCXXInClassMemberInitializer() { 2615 // Create a synthetic function scope to represent the call to the constructor 2616 // that notionally surrounds a use of this initializer. 2617 PushFunctionScope(); 2618 } 2619 2620 /// \brief This is invoked after parsing an in-class initializer for a 2621 /// non-static C++ class member, and after instantiating an in-class initializer 2622 /// in a class template. Such actions are deferred until the class is complete. 2623 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2624 SourceLocation InitLoc, 2625 Expr *InitExpr) { 2626 // Pop the notional constructor scope we created earlier. 2627 PopFunctionScopeInfo(nullptr, D); 2628 2629 FieldDecl *FD = cast<FieldDecl>(D); 2630 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2631 "must set init style when field is created"); 2632 2633 if (!InitExpr) { 2634 FD->setInvalidDecl(); 2635 FD->removeInClassInitializer(); 2636 return; 2637 } 2638 2639 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2640 FD->setInvalidDecl(); 2641 FD->removeInClassInitializer(); 2642 return; 2643 } 2644 2645 ExprResult Init = InitExpr; 2646 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2647 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2648 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2649 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2650 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2651 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2652 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2653 if (Init.isInvalid()) { 2654 FD->setInvalidDecl(); 2655 return; 2656 } 2657 } 2658 2659 // C++11 [class.base.init]p7: 2660 // The initialization of each base and member constitutes a 2661 // full-expression. 2662 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2663 if (Init.isInvalid()) { 2664 FD->setInvalidDecl(); 2665 return; 2666 } 2667 2668 InitExpr = Init.get(); 2669 2670 FD->setInClassInitializer(InitExpr); 2671 } 2672 2673 /// \brief Find the direct and/or virtual base specifiers that 2674 /// correspond to the given base type, for use in base initialization 2675 /// within a constructor. 2676 static bool FindBaseInitializer(Sema &SemaRef, 2677 CXXRecordDecl *ClassDecl, 2678 QualType BaseType, 2679 const CXXBaseSpecifier *&DirectBaseSpec, 2680 const CXXBaseSpecifier *&VirtualBaseSpec) { 2681 // First, check for a direct base class. 2682 DirectBaseSpec = nullptr; 2683 for (const auto &Base : ClassDecl->bases()) { 2684 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2685 // We found a direct base of this type. That's what we're 2686 // initializing. 2687 DirectBaseSpec = &Base; 2688 break; 2689 } 2690 } 2691 2692 // Check for a virtual base class. 2693 // FIXME: We might be able to short-circuit this if we know in advance that 2694 // there are no virtual bases. 2695 VirtualBaseSpec = nullptr; 2696 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2697 // We haven't found a base yet; search the class hierarchy for a 2698 // virtual base class. 2699 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2700 /*DetectVirtual=*/false); 2701 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2702 BaseType, Paths)) { 2703 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2704 Path != Paths.end(); ++Path) { 2705 if (Path->back().Base->isVirtual()) { 2706 VirtualBaseSpec = Path->back().Base; 2707 break; 2708 } 2709 } 2710 } 2711 } 2712 2713 return DirectBaseSpec || VirtualBaseSpec; 2714 } 2715 2716 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2717 MemInitResult 2718 Sema::ActOnMemInitializer(Decl *ConstructorD, 2719 Scope *S, 2720 CXXScopeSpec &SS, 2721 IdentifierInfo *MemberOrBase, 2722 ParsedType TemplateTypeTy, 2723 const DeclSpec &DS, 2724 SourceLocation IdLoc, 2725 Expr *InitList, 2726 SourceLocation EllipsisLoc) { 2727 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2728 DS, IdLoc, InitList, 2729 EllipsisLoc); 2730 } 2731 2732 /// \brief Handle a C++ member initializer using parentheses syntax. 2733 MemInitResult 2734 Sema::ActOnMemInitializer(Decl *ConstructorD, 2735 Scope *S, 2736 CXXScopeSpec &SS, 2737 IdentifierInfo *MemberOrBase, 2738 ParsedType TemplateTypeTy, 2739 const DeclSpec &DS, 2740 SourceLocation IdLoc, 2741 SourceLocation LParenLoc, 2742 ArrayRef<Expr *> Args, 2743 SourceLocation RParenLoc, 2744 SourceLocation EllipsisLoc) { 2745 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2746 Args, RParenLoc); 2747 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2748 DS, IdLoc, List, EllipsisLoc); 2749 } 2750 2751 namespace { 2752 2753 // Callback to only accept typo corrections that can be a valid C++ member 2754 // intializer: either a non-static field member or a base class. 2755 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2756 public: 2757 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2758 : ClassDecl(ClassDecl) {} 2759 2760 bool ValidateCandidate(const TypoCorrection &candidate) override { 2761 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2762 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2763 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2764 return isa<TypeDecl>(ND); 2765 } 2766 return false; 2767 } 2768 2769 private: 2770 CXXRecordDecl *ClassDecl; 2771 }; 2772 2773 } 2774 2775 /// \brief Handle a C++ member initializer. 2776 MemInitResult 2777 Sema::BuildMemInitializer(Decl *ConstructorD, 2778 Scope *S, 2779 CXXScopeSpec &SS, 2780 IdentifierInfo *MemberOrBase, 2781 ParsedType TemplateTypeTy, 2782 const DeclSpec &DS, 2783 SourceLocation IdLoc, 2784 Expr *Init, 2785 SourceLocation EllipsisLoc) { 2786 if (!ConstructorD) 2787 return true; 2788 2789 AdjustDeclIfTemplate(ConstructorD); 2790 2791 CXXConstructorDecl *Constructor 2792 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2793 if (!Constructor) { 2794 // The user wrote a constructor initializer on a function that is 2795 // not a C++ constructor. Ignore the error for now, because we may 2796 // have more member initializers coming; we'll diagnose it just 2797 // once in ActOnMemInitializers. 2798 return true; 2799 } 2800 2801 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2802 2803 // C++ [class.base.init]p2: 2804 // Names in a mem-initializer-id are looked up in the scope of the 2805 // constructor's class and, if not found in that scope, are looked 2806 // up in the scope containing the constructor's definition. 2807 // [Note: if the constructor's class contains a member with the 2808 // same name as a direct or virtual base class of the class, a 2809 // mem-initializer-id naming the member or base class and composed 2810 // of a single identifier refers to the class member. A 2811 // mem-initializer-id for the hidden base class may be specified 2812 // using a qualified name. ] 2813 if (!SS.getScopeRep() && !TemplateTypeTy) { 2814 // Look for a member, first. 2815 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2816 if (!Result.empty()) { 2817 ValueDecl *Member; 2818 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2819 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2820 if (EllipsisLoc.isValid()) 2821 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2822 << MemberOrBase 2823 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2824 2825 return BuildMemberInitializer(Member, Init, IdLoc); 2826 } 2827 } 2828 } 2829 // It didn't name a member, so see if it names a class. 2830 QualType BaseType; 2831 TypeSourceInfo *TInfo = nullptr; 2832 2833 if (TemplateTypeTy) { 2834 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2835 } else if (DS.getTypeSpecType() == TST_decltype) { 2836 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2837 } else { 2838 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2839 LookupParsedName(R, S, &SS); 2840 2841 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2842 if (!TyD) { 2843 if (R.isAmbiguous()) return true; 2844 2845 // We don't want access-control diagnostics here. 2846 R.suppressDiagnostics(); 2847 2848 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2849 bool NotUnknownSpecialization = false; 2850 DeclContext *DC = computeDeclContext(SS, false); 2851 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2852 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2853 2854 if (!NotUnknownSpecialization) { 2855 // When the scope specifier can refer to a member of an unknown 2856 // specialization, we take it as a type name. 2857 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2858 SS.getWithLocInContext(Context), 2859 *MemberOrBase, IdLoc); 2860 if (BaseType.isNull()) 2861 return true; 2862 2863 R.clear(); 2864 R.setLookupName(MemberOrBase); 2865 } 2866 } 2867 2868 // If no results were found, try to correct typos. 2869 TypoCorrection Corr; 2870 if (R.empty() && BaseType.isNull() && 2871 (Corr = CorrectTypo( 2872 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2873 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2874 CTK_ErrorRecovery, ClassDecl))) { 2875 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2876 // We have found a non-static data member with a similar 2877 // name to what was typed; complain and initialize that 2878 // member. 2879 diagnoseTypo(Corr, 2880 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2881 << MemberOrBase << true); 2882 return BuildMemberInitializer(Member, Init, IdLoc); 2883 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2884 const CXXBaseSpecifier *DirectBaseSpec; 2885 const CXXBaseSpecifier *VirtualBaseSpec; 2886 if (FindBaseInitializer(*this, ClassDecl, 2887 Context.getTypeDeclType(Type), 2888 DirectBaseSpec, VirtualBaseSpec)) { 2889 // We have found a direct or virtual base class with a 2890 // similar name to what was typed; complain and initialize 2891 // that base class. 2892 diagnoseTypo(Corr, 2893 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2894 << MemberOrBase << false, 2895 PDiag() /*Suppress note, we provide our own.*/); 2896 2897 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2898 : VirtualBaseSpec; 2899 Diag(BaseSpec->getLocStart(), 2900 diag::note_base_class_specified_here) 2901 << BaseSpec->getType() 2902 << BaseSpec->getSourceRange(); 2903 2904 TyD = Type; 2905 } 2906 } 2907 } 2908 2909 if (!TyD && BaseType.isNull()) { 2910 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2911 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2912 return true; 2913 } 2914 } 2915 2916 if (BaseType.isNull()) { 2917 BaseType = Context.getTypeDeclType(TyD); 2918 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 2919 if (SS.isSet()) 2920 // FIXME: preserve source range information 2921 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2922 BaseType); 2923 } 2924 } 2925 2926 if (!TInfo) 2927 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2928 2929 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2930 } 2931 2932 /// Checks a member initializer expression for cases where reference (or 2933 /// pointer) members are bound to by-value parameters (or their addresses). 2934 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2935 Expr *Init, 2936 SourceLocation IdLoc) { 2937 QualType MemberTy = Member->getType(); 2938 2939 // We only handle pointers and references currently. 2940 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2941 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2942 return; 2943 2944 const bool IsPointer = MemberTy->isPointerType(); 2945 if (IsPointer) { 2946 if (const UnaryOperator *Op 2947 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2948 // The only case we're worried about with pointers requires taking the 2949 // address. 2950 if (Op->getOpcode() != UO_AddrOf) 2951 return; 2952 2953 Init = Op->getSubExpr(); 2954 } else { 2955 // We only handle address-of expression initializers for pointers. 2956 return; 2957 } 2958 } 2959 2960 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2961 // We only warn when referring to a non-reference parameter declaration. 2962 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2963 if (!Parameter || Parameter->getType()->isReferenceType()) 2964 return; 2965 2966 S.Diag(Init->getExprLoc(), 2967 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2968 : diag::warn_bind_ref_member_to_parameter) 2969 << Member << Parameter << Init->getSourceRange(); 2970 } else { 2971 // Other initializers are fine. 2972 return; 2973 } 2974 2975 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2976 << (unsigned)IsPointer; 2977 } 2978 2979 MemInitResult 2980 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2981 SourceLocation IdLoc) { 2982 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2983 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2984 assert((DirectMember || IndirectMember) && 2985 "Member must be a FieldDecl or IndirectFieldDecl"); 2986 2987 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2988 return true; 2989 2990 if (Member->isInvalidDecl()) 2991 return true; 2992 2993 MultiExprArg Args; 2994 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2995 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2996 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2997 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2998 } else { 2999 // Template instantiation doesn't reconstruct ParenListExprs for us. 3000 Args = Init; 3001 } 3002 3003 SourceRange InitRange = Init->getSourceRange(); 3004 3005 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3006 // Can't check initialization for a member of dependent type or when 3007 // any of the arguments are type-dependent expressions. 3008 DiscardCleanupsInEvaluationContext(); 3009 } else { 3010 bool InitList = false; 3011 if (isa<InitListExpr>(Init)) { 3012 InitList = true; 3013 Args = Init; 3014 } 3015 3016 // Initialize the member. 3017 InitializedEntity MemberEntity = 3018 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3019 : InitializedEntity::InitializeMember(IndirectMember, 3020 nullptr); 3021 InitializationKind Kind = 3022 InitList ? InitializationKind::CreateDirectList(IdLoc) 3023 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3024 InitRange.getEnd()); 3025 3026 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3027 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3028 nullptr); 3029 if (MemberInit.isInvalid()) 3030 return true; 3031 3032 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3033 3034 // C++11 [class.base.init]p7: 3035 // The initialization of each base and member constitutes a 3036 // full-expression. 3037 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3038 if (MemberInit.isInvalid()) 3039 return true; 3040 3041 Init = MemberInit.get(); 3042 } 3043 3044 if (DirectMember) { 3045 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3046 InitRange.getBegin(), Init, 3047 InitRange.getEnd()); 3048 } else { 3049 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3050 InitRange.getBegin(), Init, 3051 InitRange.getEnd()); 3052 } 3053 } 3054 3055 MemInitResult 3056 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3057 CXXRecordDecl *ClassDecl) { 3058 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3059 if (!LangOpts.CPlusPlus11) 3060 return Diag(NameLoc, diag::err_delegating_ctor) 3061 << TInfo->getTypeLoc().getLocalSourceRange(); 3062 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3063 3064 bool InitList = true; 3065 MultiExprArg Args = Init; 3066 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3067 InitList = false; 3068 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3069 } 3070 3071 SourceRange InitRange = Init->getSourceRange(); 3072 // Initialize the object. 3073 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3074 QualType(ClassDecl->getTypeForDecl(), 0)); 3075 InitializationKind Kind = 3076 InitList ? InitializationKind::CreateDirectList(NameLoc) 3077 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3078 InitRange.getEnd()); 3079 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3080 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3081 Args, nullptr); 3082 if (DelegationInit.isInvalid()) 3083 return true; 3084 3085 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3086 "Delegating constructor with no target?"); 3087 3088 // C++11 [class.base.init]p7: 3089 // The initialization of each base and member constitutes a 3090 // full-expression. 3091 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3092 InitRange.getBegin()); 3093 if (DelegationInit.isInvalid()) 3094 return true; 3095 3096 // If we are in a dependent context, template instantiation will 3097 // perform this type-checking again. Just save the arguments that we 3098 // received in a ParenListExpr. 3099 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3100 // of the information that we have about the base 3101 // initializer. However, deconstructing the ASTs is a dicey process, 3102 // and this approach is far more likely to get the corner cases right. 3103 if (CurContext->isDependentContext()) 3104 DelegationInit = Init; 3105 3106 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3107 DelegationInit.getAs<Expr>(), 3108 InitRange.getEnd()); 3109 } 3110 3111 MemInitResult 3112 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3113 Expr *Init, CXXRecordDecl *ClassDecl, 3114 SourceLocation EllipsisLoc) { 3115 SourceLocation BaseLoc 3116 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3117 3118 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3119 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3120 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3121 3122 // C++ [class.base.init]p2: 3123 // [...] Unless the mem-initializer-id names a nonstatic data 3124 // member of the constructor's class or a direct or virtual base 3125 // of that class, the mem-initializer is ill-formed. A 3126 // mem-initializer-list can initialize a base class using any 3127 // name that denotes that base class type. 3128 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3129 3130 SourceRange InitRange = Init->getSourceRange(); 3131 if (EllipsisLoc.isValid()) { 3132 // This is a pack expansion. 3133 if (!BaseType->containsUnexpandedParameterPack()) { 3134 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3135 << SourceRange(BaseLoc, InitRange.getEnd()); 3136 3137 EllipsisLoc = SourceLocation(); 3138 } 3139 } else { 3140 // Check for any unexpanded parameter packs. 3141 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3142 return true; 3143 3144 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3145 return true; 3146 } 3147 3148 // Check for direct and virtual base classes. 3149 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3150 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3151 if (!Dependent) { 3152 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3153 BaseType)) 3154 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3155 3156 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3157 VirtualBaseSpec); 3158 3159 // C++ [base.class.init]p2: 3160 // Unless the mem-initializer-id names a nonstatic data member of the 3161 // constructor's class or a direct or virtual base of that class, the 3162 // mem-initializer is ill-formed. 3163 if (!DirectBaseSpec && !VirtualBaseSpec) { 3164 // If the class has any dependent bases, then it's possible that 3165 // one of those types will resolve to the same type as 3166 // BaseType. Therefore, just treat this as a dependent base 3167 // class initialization. FIXME: Should we try to check the 3168 // initialization anyway? It seems odd. 3169 if (ClassDecl->hasAnyDependentBases()) 3170 Dependent = true; 3171 else 3172 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3173 << BaseType << Context.getTypeDeclType(ClassDecl) 3174 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3175 } 3176 } 3177 3178 if (Dependent) { 3179 DiscardCleanupsInEvaluationContext(); 3180 3181 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3182 /*IsVirtual=*/false, 3183 InitRange.getBegin(), Init, 3184 InitRange.getEnd(), EllipsisLoc); 3185 } 3186 3187 // C++ [base.class.init]p2: 3188 // If a mem-initializer-id is ambiguous because it designates both 3189 // a direct non-virtual base class and an inherited virtual base 3190 // class, the mem-initializer is ill-formed. 3191 if (DirectBaseSpec && VirtualBaseSpec) 3192 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3193 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3194 3195 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3196 if (!BaseSpec) 3197 BaseSpec = VirtualBaseSpec; 3198 3199 // Initialize the base. 3200 bool InitList = true; 3201 MultiExprArg Args = Init; 3202 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3203 InitList = false; 3204 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3205 } 3206 3207 InitializedEntity BaseEntity = 3208 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3209 InitializationKind Kind = 3210 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3211 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3212 InitRange.getEnd()); 3213 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3214 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3215 if (BaseInit.isInvalid()) 3216 return true; 3217 3218 // C++11 [class.base.init]p7: 3219 // The initialization of each base and member constitutes a 3220 // full-expression. 3221 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3222 if (BaseInit.isInvalid()) 3223 return true; 3224 3225 // If we are in a dependent context, template instantiation will 3226 // perform this type-checking again. Just save the arguments that we 3227 // received in a ParenListExpr. 3228 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3229 // of the information that we have about the base 3230 // initializer. However, deconstructing the ASTs is a dicey process, 3231 // and this approach is far more likely to get the corner cases right. 3232 if (CurContext->isDependentContext()) 3233 BaseInit = Init; 3234 3235 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3236 BaseSpec->isVirtual(), 3237 InitRange.getBegin(), 3238 BaseInit.getAs<Expr>(), 3239 InitRange.getEnd(), EllipsisLoc); 3240 } 3241 3242 // Create a static_cast\<T&&>(expr). 3243 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3244 if (T.isNull()) T = E->getType(); 3245 QualType TargetType = SemaRef.BuildReferenceType( 3246 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3247 SourceLocation ExprLoc = E->getLocStart(); 3248 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3249 TargetType, ExprLoc); 3250 3251 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3252 SourceRange(ExprLoc, ExprLoc), 3253 E->getSourceRange()).get(); 3254 } 3255 3256 /// ImplicitInitializerKind - How an implicit base or member initializer should 3257 /// initialize its base or member. 3258 enum ImplicitInitializerKind { 3259 IIK_Default, 3260 IIK_Copy, 3261 IIK_Move, 3262 IIK_Inherit 3263 }; 3264 3265 static bool 3266 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3267 ImplicitInitializerKind ImplicitInitKind, 3268 CXXBaseSpecifier *BaseSpec, 3269 bool IsInheritedVirtualBase, 3270 CXXCtorInitializer *&CXXBaseInit) { 3271 InitializedEntity InitEntity 3272 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3273 IsInheritedVirtualBase); 3274 3275 ExprResult BaseInit; 3276 3277 switch (ImplicitInitKind) { 3278 case IIK_Inherit: { 3279 const CXXRecordDecl *Inherited = 3280 Constructor->getInheritedConstructor()->getParent(); 3281 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3282 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3283 // C++11 [class.inhctor]p8: 3284 // Each expression in the expression-list is of the form 3285 // static_cast<T&&>(p), where p is the name of the corresponding 3286 // constructor parameter and T is the declared type of p. 3287 SmallVector<Expr*, 16> Args; 3288 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3289 ParmVarDecl *PD = Constructor->getParamDecl(I); 3290 ExprResult ArgExpr = 3291 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3292 VK_LValue, SourceLocation()); 3293 if (ArgExpr.isInvalid()) 3294 return true; 3295 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3296 } 3297 3298 InitializationKind InitKind = InitializationKind::CreateDirect( 3299 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3300 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3301 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3302 break; 3303 } 3304 } 3305 // Fall through. 3306 case IIK_Default: { 3307 InitializationKind InitKind 3308 = InitializationKind::CreateDefault(Constructor->getLocation()); 3309 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3310 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3311 break; 3312 } 3313 3314 case IIK_Move: 3315 case IIK_Copy: { 3316 bool Moving = ImplicitInitKind == IIK_Move; 3317 ParmVarDecl *Param = Constructor->getParamDecl(0); 3318 QualType ParamType = Param->getType().getNonReferenceType(); 3319 3320 Expr *CopyCtorArg = 3321 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3322 SourceLocation(), Param, false, 3323 Constructor->getLocation(), ParamType, 3324 VK_LValue, nullptr); 3325 3326 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3327 3328 // Cast to the base class to avoid ambiguities. 3329 QualType ArgTy = 3330 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3331 ParamType.getQualifiers()); 3332 3333 if (Moving) { 3334 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3335 } 3336 3337 CXXCastPath BasePath; 3338 BasePath.push_back(BaseSpec); 3339 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3340 CK_UncheckedDerivedToBase, 3341 Moving ? VK_XValue : VK_LValue, 3342 &BasePath).get(); 3343 3344 InitializationKind InitKind 3345 = InitializationKind::CreateDirect(Constructor->getLocation(), 3346 SourceLocation(), SourceLocation()); 3347 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3348 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3349 break; 3350 } 3351 } 3352 3353 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3354 if (BaseInit.isInvalid()) 3355 return true; 3356 3357 CXXBaseInit = 3358 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3359 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3360 SourceLocation()), 3361 BaseSpec->isVirtual(), 3362 SourceLocation(), 3363 BaseInit.getAs<Expr>(), 3364 SourceLocation(), 3365 SourceLocation()); 3366 3367 return false; 3368 } 3369 3370 static bool RefersToRValueRef(Expr *MemRef) { 3371 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3372 return Referenced->getType()->isRValueReferenceType(); 3373 } 3374 3375 static bool 3376 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3377 ImplicitInitializerKind ImplicitInitKind, 3378 FieldDecl *Field, IndirectFieldDecl *Indirect, 3379 CXXCtorInitializer *&CXXMemberInit) { 3380 if (Field->isInvalidDecl()) 3381 return true; 3382 3383 SourceLocation Loc = Constructor->getLocation(); 3384 3385 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3386 bool Moving = ImplicitInitKind == IIK_Move; 3387 ParmVarDecl *Param = Constructor->getParamDecl(0); 3388 QualType ParamType = Param->getType().getNonReferenceType(); 3389 3390 // Suppress copying zero-width bitfields. 3391 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3392 return false; 3393 3394 Expr *MemberExprBase = 3395 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3396 SourceLocation(), Param, false, 3397 Loc, ParamType, VK_LValue, nullptr); 3398 3399 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3400 3401 if (Moving) { 3402 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3403 } 3404 3405 // Build a reference to this field within the parameter. 3406 CXXScopeSpec SS; 3407 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3408 Sema::LookupMemberName); 3409 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3410 : cast<ValueDecl>(Field), AS_public); 3411 MemberLookup.resolveKind(); 3412 ExprResult CtorArg 3413 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3414 ParamType, Loc, 3415 /*IsArrow=*/false, 3416 SS, 3417 /*TemplateKWLoc=*/SourceLocation(), 3418 /*FirstQualifierInScope=*/nullptr, 3419 MemberLookup, 3420 /*TemplateArgs=*/nullptr); 3421 if (CtorArg.isInvalid()) 3422 return true; 3423 3424 // C++11 [class.copy]p15: 3425 // - if a member m has rvalue reference type T&&, it is direct-initialized 3426 // with static_cast<T&&>(x.m); 3427 if (RefersToRValueRef(CtorArg.get())) { 3428 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3429 } 3430 3431 // When the field we are copying is an array, create index variables for 3432 // each dimension of the array. We use these index variables to subscript 3433 // the source array, and other clients (e.g., CodeGen) will perform the 3434 // necessary iteration with these index variables. 3435 SmallVector<VarDecl *, 4> IndexVariables; 3436 QualType BaseType = Field->getType(); 3437 QualType SizeType = SemaRef.Context.getSizeType(); 3438 bool InitializingArray = false; 3439 while (const ConstantArrayType *Array 3440 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3441 InitializingArray = true; 3442 // Create the iteration variable for this array index. 3443 IdentifierInfo *IterationVarName = nullptr; 3444 { 3445 SmallString<8> Str; 3446 llvm::raw_svector_ostream OS(Str); 3447 OS << "__i" << IndexVariables.size(); 3448 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3449 } 3450 VarDecl *IterationVar 3451 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3452 IterationVarName, SizeType, 3453 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3454 SC_None); 3455 IndexVariables.push_back(IterationVar); 3456 3457 // Create a reference to the iteration variable. 3458 ExprResult IterationVarRef 3459 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3460 assert(!IterationVarRef.isInvalid() && 3461 "Reference to invented variable cannot fail!"); 3462 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3463 assert(!IterationVarRef.isInvalid() && 3464 "Conversion of invented variable cannot fail!"); 3465 3466 // Subscript the array with this iteration variable. 3467 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3468 IterationVarRef.get(), 3469 Loc); 3470 if (CtorArg.isInvalid()) 3471 return true; 3472 3473 BaseType = Array->getElementType(); 3474 } 3475 3476 // The array subscript expression is an lvalue, which is wrong for moving. 3477 if (Moving && InitializingArray) 3478 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3479 3480 // Construct the entity that we will be initializing. For an array, this 3481 // will be first element in the array, which may require several levels 3482 // of array-subscript entities. 3483 SmallVector<InitializedEntity, 4> Entities; 3484 Entities.reserve(1 + IndexVariables.size()); 3485 if (Indirect) 3486 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3487 else 3488 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3489 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3490 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3491 0, 3492 Entities.back())); 3493 3494 // Direct-initialize to use the copy constructor. 3495 InitializationKind InitKind = 3496 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3497 3498 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3499 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3500 3501 ExprResult MemberInit 3502 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3503 MultiExprArg(&CtorArgE, 1)); 3504 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3505 if (MemberInit.isInvalid()) 3506 return true; 3507 3508 if (Indirect) { 3509 assert(IndexVariables.size() == 0 && 3510 "Indirect field improperly initialized"); 3511 CXXMemberInit 3512 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3513 Loc, Loc, 3514 MemberInit.getAs<Expr>(), 3515 Loc); 3516 } else 3517 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3518 Loc, MemberInit.getAs<Expr>(), 3519 Loc, 3520 IndexVariables.data(), 3521 IndexVariables.size()); 3522 return false; 3523 } 3524 3525 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3526 "Unhandled implicit init kind!"); 3527 3528 QualType FieldBaseElementType = 3529 SemaRef.Context.getBaseElementType(Field->getType()); 3530 3531 if (FieldBaseElementType->isRecordType()) { 3532 InitializedEntity InitEntity 3533 = Indirect? InitializedEntity::InitializeMember(Indirect) 3534 : InitializedEntity::InitializeMember(Field); 3535 InitializationKind InitKind = 3536 InitializationKind::CreateDefault(Loc); 3537 3538 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3539 ExprResult MemberInit = 3540 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3541 3542 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3543 if (MemberInit.isInvalid()) 3544 return true; 3545 3546 if (Indirect) 3547 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3548 Indirect, Loc, 3549 Loc, 3550 MemberInit.get(), 3551 Loc); 3552 else 3553 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3554 Field, Loc, Loc, 3555 MemberInit.get(), 3556 Loc); 3557 return false; 3558 } 3559 3560 if (!Field->getParent()->isUnion()) { 3561 if (FieldBaseElementType->isReferenceType()) { 3562 SemaRef.Diag(Constructor->getLocation(), 3563 diag::err_uninitialized_member_in_ctor) 3564 << (int)Constructor->isImplicit() 3565 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3566 << 0 << Field->getDeclName(); 3567 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3568 return true; 3569 } 3570 3571 if (FieldBaseElementType.isConstQualified()) { 3572 SemaRef.Diag(Constructor->getLocation(), 3573 diag::err_uninitialized_member_in_ctor) 3574 << (int)Constructor->isImplicit() 3575 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3576 << 1 << Field->getDeclName(); 3577 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3578 return true; 3579 } 3580 } 3581 3582 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3583 FieldBaseElementType->isObjCRetainableType() && 3584 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3585 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3586 // ARC: 3587 // Default-initialize Objective-C pointers to NULL. 3588 CXXMemberInit 3589 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3590 Loc, Loc, 3591 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3592 Loc); 3593 return false; 3594 } 3595 3596 // Nothing to initialize. 3597 CXXMemberInit = nullptr; 3598 return false; 3599 } 3600 3601 namespace { 3602 struct BaseAndFieldInfo { 3603 Sema &S; 3604 CXXConstructorDecl *Ctor; 3605 bool AnyErrorsInInits; 3606 ImplicitInitializerKind IIK; 3607 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3608 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3609 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3610 3611 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3612 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3613 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3614 if (Generated && Ctor->isCopyConstructor()) 3615 IIK = IIK_Copy; 3616 else if (Generated && Ctor->isMoveConstructor()) 3617 IIK = IIK_Move; 3618 else if (Ctor->getInheritedConstructor()) 3619 IIK = IIK_Inherit; 3620 else 3621 IIK = IIK_Default; 3622 } 3623 3624 bool isImplicitCopyOrMove() const { 3625 switch (IIK) { 3626 case IIK_Copy: 3627 case IIK_Move: 3628 return true; 3629 3630 case IIK_Default: 3631 case IIK_Inherit: 3632 return false; 3633 } 3634 3635 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3636 } 3637 3638 bool addFieldInitializer(CXXCtorInitializer *Init) { 3639 AllToInit.push_back(Init); 3640 3641 // Check whether this initializer makes the field "used". 3642 if (Init->getInit()->HasSideEffects(S.Context)) 3643 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3644 3645 return false; 3646 } 3647 3648 bool isInactiveUnionMember(FieldDecl *Field) { 3649 RecordDecl *Record = Field->getParent(); 3650 if (!Record->isUnion()) 3651 return false; 3652 3653 if (FieldDecl *Active = 3654 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3655 return Active != Field->getCanonicalDecl(); 3656 3657 // In an implicit copy or move constructor, ignore any in-class initializer. 3658 if (isImplicitCopyOrMove()) 3659 return true; 3660 3661 // If there's no explicit initialization, the field is active only if it 3662 // has an in-class initializer... 3663 if (Field->hasInClassInitializer()) 3664 return false; 3665 // ... or it's an anonymous struct or union whose class has an in-class 3666 // initializer. 3667 if (!Field->isAnonymousStructOrUnion()) 3668 return true; 3669 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3670 return !FieldRD->hasInClassInitializer(); 3671 } 3672 3673 /// \brief Determine whether the given field is, or is within, a union member 3674 /// that is inactive (because there was an initializer given for a different 3675 /// member of the union, or because the union was not initialized at all). 3676 bool isWithinInactiveUnionMember(FieldDecl *Field, 3677 IndirectFieldDecl *Indirect) { 3678 if (!Indirect) 3679 return isInactiveUnionMember(Field); 3680 3681 for (auto *C : Indirect->chain()) { 3682 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3683 if (Field && isInactiveUnionMember(Field)) 3684 return true; 3685 } 3686 return false; 3687 } 3688 }; 3689 } 3690 3691 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3692 /// array type. 3693 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3694 if (T->isIncompleteArrayType()) 3695 return true; 3696 3697 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3698 if (!ArrayT->getSize()) 3699 return true; 3700 3701 T = ArrayT->getElementType(); 3702 } 3703 3704 return false; 3705 } 3706 3707 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3708 FieldDecl *Field, 3709 IndirectFieldDecl *Indirect = nullptr) { 3710 if (Field->isInvalidDecl()) 3711 return false; 3712 3713 // Overwhelmingly common case: we have a direct initializer for this field. 3714 if (CXXCtorInitializer *Init = 3715 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3716 return Info.addFieldInitializer(Init); 3717 3718 // C++11 [class.base.init]p8: 3719 // if the entity is a non-static data member that has a 3720 // brace-or-equal-initializer and either 3721 // -- the constructor's class is a union and no other variant member of that 3722 // union is designated by a mem-initializer-id or 3723 // -- the constructor's class is not a union, and, if the entity is a member 3724 // of an anonymous union, no other member of that union is designated by 3725 // a mem-initializer-id, 3726 // the entity is initialized as specified in [dcl.init]. 3727 // 3728 // We also apply the same rules to handle anonymous structs within anonymous 3729 // unions. 3730 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3731 return false; 3732 3733 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3734 ExprResult DIE = 3735 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3736 if (DIE.isInvalid()) 3737 return true; 3738 CXXCtorInitializer *Init; 3739 if (Indirect) 3740 Init = new (SemaRef.Context) 3741 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3742 SourceLocation(), DIE.get(), SourceLocation()); 3743 else 3744 Init = new (SemaRef.Context) 3745 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3746 SourceLocation(), DIE.get(), SourceLocation()); 3747 return Info.addFieldInitializer(Init); 3748 } 3749 3750 // Don't initialize incomplete or zero-length arrays. 3751 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3752 return false; 3753 3754 // Don't try to build an implicit initializer if there were semantic 3755 // errors in any of the initializers (and therefore we might be 3756 // missing some that the user actually wrote). 3757 if (Info.AnyErrorsInInits) 3758 return false; 3759 3760 CXXCtorInitializer *Init = nullptr; 3761 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3762 Indirect, Init)) 3763 return true; 3764 3765 if (!Init) 3766 return false; 3767 3768 return Info.addFieldInitializer(Init); 3769 } 3770 3771 bool 3772 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3773 CXXCtorInitializer *Initializer) { 3774 assert(Initializer->isDelegatingInitializer()); 3775 Constructor->setNumCtorInitializers(1); 3776 CXXCtorInitializer **initializer = 3777 new (Context) CXXCtorInitializer*[1]; 3778 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3779 Constructor->setCtorInitializers(initializer); 3780 3781 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3782 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3783 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3784 } 3785 3786 DelegatingCtorDecls.push_back(Constructor); 3787 3788 DiagnoseUninitializedFields(*this, Constructor); 3789 3790 return false; 3791 } 3792 3793 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3794 ArrayRef<CXXCtorInitializer *> Initializers) { 3795 if (Constructor->isDependentContext()) { 3796 // Just store the initializers as written, they will be checked during 3797 // instantiation. 3798 if (!Initializers.empty()) { 3799 Constructor->setNumCtorInitializers(Initializers.size()); 3800 CXXCtorInitializer **baseOrMemberInitializers = 3801 new (Context) CXXCtorInitializer*[Initializers.size()]; 3802 memcpy(baseOrMemberInitializers, Initializers.data(), 3803 Initializers.size() * sizeof(CXXCtorInitializer*)); 3804 Constructor->setCtorInitializers(baseOrMemberInitializers); 3805 } 3806 3807 // Let template instantiation know whether we had errors. 3808 if (AnyErrors) 3809 Constructor->setInvalidDecl(); 3810 3811 return false; 3812 } 3813 3814 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3815 3816 // We need to build the initializer AST according to order of construction 3817 // and not what user specified in the Initializers list. 3818 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3819 if (!ClassDecl) 3820 return true; 3821 3822 bool HadError = false; 3823 3824 for (unsigned i = 0; i < Initializers.size(); i++) { 3825 CXXCtorInitializer *Member = Initializers[i]; 3826 3827 if (Member->isBaseInitializer()) 3828 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3829 else { 3830 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3831 3832 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3833 for (auto *C : F->chain()) { 3834 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3835 if (FD && FD->getParent()->isUnion()) 3836 Info.ActiveUnionMember.insert(std::make_pair( 3837 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3838 } 3839 } else if (FieldDecl *FD = Member->getMember()) { 3840 if (FD->getParent()->isUnion()) 3841 Info.ActiveUnionMember.insert(std::make_pair( 3842 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3843 } 3844 } 3845 } 3846 3847 // Keep track of the direct virtual bases. 3848 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3849 for (auto &I : ClassDecl->bases()) { 3850 if (I.isVirtual()) 3851 DirectVBases.insert(&I); 3852 } 3853 3854 // Push virtual bases before others. 3855 for (auto &VBase : ClassDecl->vbases()) { 3856 if (CXXCtorInitializer *Value 3857 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3858 // [class.base.init]p7, per DR257: 3859 // A mem-initializer where the mem-initializer-id names a virtual base 3860 // class is ignored during execution of a constructor of any class that 3861 // is not the most derived class. 3862 if (ClassDecl->isAbstract()) { 3863 // FIXME: Provide a fixit to remove the base specifier. This requires 3864 // tracking the location of the associated comma for a base specifier. 3865 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3866 << VBase.getType() << ClassDecl; 3867 DiagnoseAbstractType(ClassDecl); 3868 } 3869 3870 Info.AllToInit.push_back(Value); 3871 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3872 // [class.base.init]p8, per DR257: 3873 // If a given [...] base class is not named by a mem-initializer-id 3874 // [...] and the entity is not a virtual base class of an abstract 3875 // class, then [...] the entity is default-initialized. 3876 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3877 CXXCtorInitializer *CXXBaseInit; 3878 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3879 &VBase, IsInheritedVirtualBase, 3880 CXXBaseInit)) { 3881 HadError = true; 3882 continue; 3883 } 3884 3885 Info.AllToInit.push_back(CXXBaseInit); 3886 } 3887 } 3888 3889 // Non-virtual bases. 3890 for (auto &Base : ClassDecl->bases()) { 3891 // Virtuals are in the virtual base list and already constructed. 3892 if (Base.isVirtual()) 3893 continue; 3894 3895 if (CXXCtorInitializer *Value 3896 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3897 Info.AllToInit.push_back(Value); 3898 } else if (!AnyErrors) { 3899 CXXCtorInitializer *CXXBaseInit; 3900 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3901 &Base, /*IsInheritedVirtualBase=*/false, 3902 CXXBaseInit)) { 3903 HadError = true; 3904 continue; 3905 } 3906 3907 Info.AllToInit.push_back(CXXBaseInit); 3908 } 3909 } 3910 3911 // Fields. 3912 for (auto *Mem : ClassDecl->decls()) { 3913 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3914 // C++ [class.bit]p2: 3915 // A declaration for a bit-field that omits the identifier declares an 3916 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3917 // initialized. 3918 if (F->isUnnamedBitfield()) 3919 continue; 3920 3921 // If we're not generating the implicit copy/move constructor, then we'll 3922 // handle anonymous struct/union fields based on their individual 3923 // indirect fields. 3924 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3925 continue; 3926 3927 if (CollectFieldInitializer(*this, Info, F)) 3928 HadError = true; 3929 continue; 3930 } 3931 3932 // Beyond this point, we only consider default initialization. 3933 if (Info.isImplicitCopyOrMove()) 3934 continue; 3935 3936 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3937 if (F->getType()->isIncompleteArrayType()) { 3938 assert(ClassDecl->hasFlexibleArrayMember() && 3939 "Incomplete array type is not valid"); 3940 continue; 3941 } 3942 3943 // Initialize each field of an anonymous struct individually. 3944 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3945 HadError = true; 3946 3947 continue; 3948 } 3949 } 3950 3951 unsigned NumInitializers = Info.AllToInit.size(); 3952 if (NumInitializers > 0) { 3953 Constructor->setNumCtorInitializers(NumInitializers); 3954 CXXCtorInitializer **baseOrMemberInitializers = 3955 new (Context) CXXCtorInitializer*[NumInitializers]; 3956 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3957 NumInitializers * sizeof(CXXCtorInitializer*)); 3958 Constructor->setCtorInitializers(baseOrMemberInitializers); 3959 3960 // Constructors implicitly reference the base and member 3961 // destructors. 3962 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3963 Constructor->getParent()); 3964 } 3965 3966 return HadError; 3967 } 3968 3969 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3970 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3971 const RecordDecl *RD = RT->getDecl(); 3972 if (RD->isAnonymousStructOrUnion()) { 3973 for (auto *Field : RD->fields()) 3974 PopulateKeysForFields(Field, IdealInits); 3975 return; 3976 } 3977 } 3978 IdealInits.push_back(Field->getCanonicalDecl()); 3979 } 3980 3981 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3982 return Context.getCanonicalType(BaseType).getTypePtr(); 3983 } 3984 3985 static const void *GetKeyForMember(ASTContext &Context, 3986 CXXCtorInitializer *Member) { 3987 if (!Member->isAnyMemberInitializer()) 3988 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3989 3990 return Member->getAnyMember()->getCanonicalDecl(); 3991 } 3992 3993 static void DiagnoseBaseOrMemInitializerOrder( 3994 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3995 ArrayRef<CXXCtorInitializer *> Inits) { 3996 if (Constructor->getDeclContext()->isDependentContext()) 3997 return; 3998 3999 // Don't check initializers order unless the warning is enabled at the 4000 // location of at least one initializer. 4001 bool ShouldCheckOrder = false; 4002 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4003 CXXCtorInitializer *Init = Inits[InitIndex]; 4004 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4005 Init->getSourceLocation())) { 4006 ShouldCheckOrder = true; 4007 break; 4008 } 4009 } 4010 if (!ShouldCheckOrder) 4011 return; 4012 4013 // Build the list of bases and members in the order that they'll 4014 // actually be initialized. The explicit initializers should be in 4015 // this same order but may be missing things. 4016 SmallVector<const void*, 32> IdealInitKeys; 4017 4018 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4019 4020 // 1. Virtual bases. 4021 for (const auto &VBase : ClassDecl->vbases()) 4022 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4023 4024 // 2. Non-virtual bases. 4025 for (const auto &Base : ClassDecl->bases()) { 4026 if (Base.isVirtual()) 4027 continue; 4028 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4029 } 4030 4031 // 3. Direct fields. 4032 for (auto *Field : ClassDecl->fields()) { 4033 if (Field->isUnnamedBitfield()) 4034 continue; 4035 4036 PopulateKeysForFields(Field, IdealInitKeys); 4037 } 4038 4039 unsigned NumIdealInits = IdealInitKeys.size(); 4040 unsigned IdealIndex = 0; 4041 4042 CXXCtorInitializer *PrevInit = nullptr; 4043 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4044 CXXCtorInitializer *Init = Inits[InitIndex]; 4045 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4046 4047 // Scan forward to try to find this initializer in the idealized 4048 // initializers list. 4049 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4050 if (InitKey == IdealInitKeys[IdealIndex]) 4051 break; 4052 4053 // If we didn't find this initializer, it must be because we 4054 // scanned past it on a previous iteration. That can only 4055 // happen if we're out of order; emit a warning. 4056 if (IdealIndex == NumIdealInits && PrevInit) { 4057 Sema::SemaDiagnosticBuilder D = 4058 SemaRef.Diag(PrevInit->getSourceLocation(), 4059 diag::warn_initializer_out_of_order); 4060 4061 if (PrevInit->isAnyMemberInitializer()) 4062 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4063 else 4064 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4065 4066 if (Init->isAnyMemberInitializer()) 4067 D << 0 << Init->getAnyMember()->getDeclName(); 4068 else 4069 D << 1 << Init->getTypeSourceInfo()->getType(); 4070 4071 // Move back to the initializer's location in the ideal list. 4072 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4073 if (InitKey == IdealInitKeys[IdealIndex]) 4074 break; 4075 4076 assert(IdealIndex != NumIdealInits && 4077 "initializer not found in initializer list"); 4078 } 4079 4080 PrevInit = Init; 4081 } 4082 } 4083 4084 namespace { 4085 bool CheckRedundantInit(Sema &S, 4086 CXXCtorInitializer *Init, 4087 CXXCtorInitializer *&PrevInit) { 4088 if (!PrevInit) { 4089 PrevInit = Init; 4090 return false; 4091 } 4092 4093 if (FieldDecl *Field = Init->getAnyMember()) 4094 S.Diag(Init->getSourceLocation(), 4095 diag::err_multiple_mem_initialization) 4096 << Field->getDeclName() 4097 << Init->getSourceRange(); 4098 else { 4099 const Type *BaseClass = Init->getBaseClass(); 4100 assert(BaseClass && "neither field nor base"); 4101 S.Diag(Init->getSourceLocation(), 4102 diag::err_multiple_base_initialization) 4103 << QualType(BaseClass, 0) 4104 << Init->getSourceRange(); 4105 } 4106 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4107 << 0 << PrevInit->getSourceRange(); 4108 4109 return true; 4110 } 4111 4112 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4113 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4114 4115 bool CheckRedundantUnionInit(Sema &S, 4116 CXXCtorInitializer *Init, 4117 RedundantUnionMap &Unions) { 4118 FieldDecl *Field = Init->getAnyMember(); 4119 RecordDecl *Parent = Field->getParent(); 4120 NamedDecl *Child = Field; 4121 4122 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4123 if (Parent->isUnion()) { 4124 UnionEntry &En = Unions[Parent]; 4125 if (En.first && En.first != Child) { 4126 S.Diag(Init->getSourceLocation(), 4127 diag::err_multiple_mem_union_initialization) 4128 << Field->getDeclName() 4129 << Init->getSourceRange(); 4130 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4131 << 0 << En.second->getSourceRange(); 4132 return true; 4133 } 4134 if (!En.first) { 4135 En.first = Child; 4136 En.second = Init; 4137 } 4138 if (!Parent->isAnonymousStructOrUnion()) 4139 return false; 4140 } 4141 4142 Child = Parent; 4143 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4144 } 4145 4146 return false; 4147 } 4148 } 4149 4150 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4151 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4152 SourceLocation ColonLoc, 4153 ArrayRef<CXXCtorInitializer*> MemInits, 4154 bool AnyErrors) { 4155 if (!ConstructorDecl) 4156 return; 4157 4158 AdjustDeclIfTemplate(ConstructorDecl); 4159 4160 CXXConstructorDecl *Constructor 4161 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4162 4163 if (!Constructor) { 4164 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4165 return; 4166 } 4167 4168 // Mapping for the duplicate initializers check. 4169 // For member initializers, this is keyed with a FieldDecl*. 4170 // For base initializers, this is keyed with a Type*. 4171 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4172 4173 // Mapping for the inconsistent anonymous-union initializers check. 4174 RedundantUnionMap MemberUnions; 4175 4176 bool HadError = false; 4177 for (unsigned i = 0; i < MemInits.size(); i++) { 4178 CXXCtorInitializer *Init = MemInits[i]; 4179 4180 // Set the source order index. 4181 Init->setSourceOrder(i); 4182 4183 if (Init->isAnyMemberInitializer()) { 4184 const void *Key = GetKeyForMember(Context, Init); 4185 if (CheckRedundantInit(*this, Init, Members[Key]) || 4186 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4187 HadError = true; 4188 } else if (Init->isBaseInitializer()) { 4189 const void *Key = GetKeyForMember(Context, Init); 4190 if (CheckRedundantInit(*this, Init, Members[Key])) 4191 HadError = true; 4192 } else { 4193 assert(Init->isDelegatingInitializer()); 4194 // This must be the only initializer 4195 if (MemInits.size() != 1) { 4196 Diag(Init->getSourceLocation(), 4197 diag::err_delegating_initializer_alone) 4198 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4199 // We will treat this as being the only initializer. 4200 } 4201 SetDelegatingInitializer(Constructor, MemInits[i]); 4202 // Return immediately as the initializer is set. 4203 return; 4204 } 4205 } 4206 4207 if (HadError) 4208 return; 4209 4210 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4211 4212 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4213 4214 DiagnoseUninitializedFields(*this, Constructor); 4215 } 4216 4217 void 4218 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4219 CXXRecordDecl *ClassDecl) { 4220 // Ignore dependent contexts. Also ignore unions, since their members never 4221 // have destructors implicitly called. 4222 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4223 return; 4224 4225 // FIXME: all the access-control diagnostics are positioned on the 4226 // field/base declaration. That's probably good; that said, the 4227 // user might reasonably want to know why the destructor is being 4228 // emitted, and we currently don't say. 4229 4230 // Non-static data members. 4231 for (auto *Field : ClassDecl->fields()) { 4232 if (Field->isInvalidDecl()) 4233 continue; 4234 4235 // Don't destroy incomplete or zero-length arrays. 4236 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4237 continue; 4238 4239 QualType FieldType = Context.getBaseElementType(Field->getType()); 4240 4241 const RecordType* RT = FieldType->getAs<RecordType>(); 4242 if (!RT) 4243 continue; 4244 4245 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4246 if (FieldClassDecl->isInvalidDecl()) 4247 continue; 4248 if (FieldClassDecl->hasIrrelevantDestructor()) 4249 continue; 4250 // The destructor for an implicit anonymous union member is never invoked. 4251 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4252 continue; 4253 4254 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4255 assert(Dtor && "No dtor found for FieldClassDecl!"); 4256 CheckDestructorAccess(Field->getLocation(), Dtor, 4257 PDiag(diag::err_access_dtor_field) 4258 << Field->getDeclName() 4259 << FieldType); 4260 4261 MarkFunctionReferenced(Location, Dtor); 4262 DiagnoseUseOfDecl(Dtor, Location); 4263 } 4264 4265 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4266 4267 // Bases. 4268 for (const auto &Base : ClassDecl->bases()) { 4269 // Bases are always records in a well-formed non-dependent class. 4270 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4271 4272 // Remember direct virtual bases. 4273 if (Base.isVirtual()) 4274 DirectVirtualBases.insert(RT); 4275 4276 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4277 // If our base class is invalid, we probably can't get its dtor anyway. 4278 if (BaseClassDecl->isInvalidDecl()) 4279 continue; 4280 if (BaseClassDecl->hasIrrelevantDestructor()) 4281 continue; 4282 4283 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4284 assert(Dtor && "No dtor found for BaseClassDecl!"); 4285 4286 // FIXME: caret should be on the start of the class name 4287 CheckDestructorAccess(Base.getLocStart(), Dtor, 4288 PDiag(diag::err_access_dtor_base) 4289 << Base.getType() 4290 << Base.getSourceRange(), 4291 Context.getTypeDeclType(ClassDecl)); 4292 4293 MarkFunctionReferenced(Location, Dtor); 4294 DiagnoseUseOfDecl(Dtor, Location); 4295 } 4296 4297 // Virtual bases. 4298 for (const auto &VBase : ClassDecl->vbases()) { 4299 // Bases are always records in a well-formed non-dependent class. 4300 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4301 4302 // Ignore direct virtual bases. 4303 if (DirectVirtualBases.count(RT)) 4304 continue; 4305 4306 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4307 // If our base class is invalid, we probably can't get its dtor anyway. 4308 if (BaseClassDecl->isInvalidDecl()) 4309 continue; 4310 if (BaseClassDecl->hasIrrelevantDestructor()) 4311 continue; 4312 4313 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4314 assert(Dtor && "No dtor found for BaseClassDecl!"); 4315 if (CheckDestructorAccess( 4316 ClassDecl->getLocation(), Dtor, 4317 PDiag(diag::err_access_dtor_vbase) 4318 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4319 Context.getTypeDeclType(ClassDecl)) == 4320 AR_accessible) { 4321 CheckDerivedToBaseConversion( 4322 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4323 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4324 SourceRange(), DeclarationName(), nullptr); 4325 } 4326 4327 MarkFunctionReferenced(Location, Dtor); 4328 DiagnoseUseOfDecl(Dtor, Location); 4329 } 4330 } 4331 4332 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4333 if (!CDtorDecl) 4334 return; 4335 4336 if (CXXConstructorDecl *Constructor 4337 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4338 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4339 DiagnoseUninitializedFields(*this, Constructor); 4340 } 4341 } 4342 4343 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4344 unsigned DiagID, AbstractDiagSelID SelID) { 4345 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4346 unsigned DiagID; 4347 AbstractDiagSelID SelID; 4348 4349 public: 4350 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4351 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4352 4353 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4354 if (Suppressed) return; 4355 if (SelID == -1) 4356 S.Diag(Loc, DiagID) << T; 4357 else 4358 S.Diag(Loc, DiagID) << SelID << T; 4359 } 4360 } Diagnoser(DiagID, SelID); 4361 4362 return RequireNonAbstractType(Loc, T, Diagnoser); 4363 } 4364 4365 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4366 TypeDiagnoser &Diagnoser) { 4367 if (!getLangOpts().CPlusPlus) 4368 return false; 4369 4370 if (const ArrayType *AT = Context.getAsArrayType(T)) 4371 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4372 4373 if (const PointerType *PT = T->getAs<PointerType>()) { 4374 // Find the innermost pointer type. 4375 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4376 PT = T; 4377 4378 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4379 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4380 } 4381 4382 const RecordType *RT = T->getAs<RecordType>(); 4383 if (!RT) 4384 return false; 4385 4386 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4387 4388 // We can't answer whether something is abstract until it has a 4389 // definition. If it's currently being defined, we'll walk back 4390 // over all the declarations when we have a full definition. 4391 const CXXRecordDecl *Def = RD->getDefinition(); 4392 if (!Def || Def->isBeingDefined()) 4393 return false; 4394 4395 if (!RD->isAbstract()) 4396 return false; 4397 4398 Diagnoser.diagnose(*this, Loc, T); 4399 DiagnoseAbstractType(RD); 4400 4401 return true; 4402 } 4403 4404 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4405 // Check if we've already emitted the list of pure virtual functions 4406 // for this class. 4407 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4408 return; 4409 4410 // If the diagnostic is suppressed, don't emit the notes. We're only 4411 // going to emit them once, so try to attach them to a diagnostic we're 4412 // actually going to show. 4413 if (Diags.isLastDiagnosticIgnored()) 4414 return; 4415 4416 CXXFinalOverriderMap FinalOverriders; 4417 RD->getFinalOverriders(FinalOverriders); 4418 4419 // Keep a set of seen pure methods so we won't diagnose the same method 4420 // more than once. 4421 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4422 4423 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4424 MEnd = FinalOverriders.end(); 4425 M != MEnd; 4426 ++M) { 4427 for (OverridingMethods::iterator SO = M->second.begin(), 4428 SOEnd = M->second.end(); 4429 SO != SOEnd; ++SO) { 4430 // C++ [class.abstract]p4: 4431 // A class is abstract if it contains or inherits at least one 4432 // pure virtual function for which the final overrider is pure 4433 // virtual. 4434 4435 // 4436 if (SO->second.size() != 1) 4437 continue; 4438 4439 if (!SO->second.front().Method->isPure()) 4440 continue; 4441 4442 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4443 continue; 4444 4445 Diag(SO->second.front().Method->getLocation(), 4446 diag::note_pure_virtual_function) 4447 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4448 } 4449 } 4450 4451 if (!PureVirtualClassDiagSet) 4452 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4453 PureVirtualClassDiagSet->insert(RD); 4454 } 4455 4456 namespace { 4457 struct AbstractUsageInfo { 4458 Sema &S; 4459 CXXRecordDecl *Record; 4460 CanQualType AbstractType; 4461 bool Invalid; 4462 4463 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4464 : S(S), Record(Record), 4465 AbstractType(S.Context.getCanonicalType( 4466 S.Context.getTypeDeclType(Record))), 4467 Invalid(false) {} 4468 4469 void DiagnoseAbstractType() { 4470 if (Invalid) return; 4471 S.DiagnoseAbstractType(Record); 4472 Invalid = true; 4473 } 4474 4475 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4476 }; 4477 4478 struct CheckAbstractUsage { 4479 AbstractUsageInfo &Info; 4480 const NamedDecl *Ctx; 4481 4482 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4483 : Info(Info), Ctx(Ctx) {} 4484 4485 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4486 switch (TL.getTypeLocClass()) { 4487 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4488 #define TYPELOC(CLASS, PARENT) \ 4489 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4490 #include "clang/AST/TypeLocNodes.def" 4491 } 4492 } 4493 4494 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4495 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4496 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4497 if (!TL.getParam(I)) 4498 continue; 4499 4500 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4501 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4502 } 4503 } 4504 4505 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4506 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4507 } 4508 4509 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4510 // Visit the type parameters from a permissive context. 4511 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4512 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4513 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4514 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4515 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4516 // TODO: other template argument types? 4517 } 4518 } 4519 4520 // Visit pointee types from a permissive context. 4521 #define CheckPolymorphic(Type) \ 4522 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4523 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4524 } 4525 CheckPolymorphic(PointerTypeLoc) 4526 CheckPolymorphic(ReferenceTypeLoc) 4527 CheckPolymorphic(MemberPointerTypeLoc) 4528 CheckPolymorphic(BlockPointerTypeLoc) 4529 CheckPolymorphic(AtomicTypeLoc) 4530 4531 /// Handle all the types we haven't given a more specific 4532 /// implementation for above. 4533 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4534 // Every other kind of type that we haven't called out already 4535 // that has an inner type is either (1) sugar or (2) contains that 4536 // inner type in some way as a subobject. 4537 if (TypeLoc Next = TL.getNextTypeLoc()) 4538 return Visit(Next, Sel); 4539 4540 // If there's no inner type and we're in a permissive context, 4541 // don't diagnose. 4542 if (Sel == Sema::AbstractNone) return; 4543 4544 // Check whether the type matches the abstract type. 4545 QualType T = TL.getType(); 4546 if (T->isArrayType()) { 4547 Sel = Sema::AbstractArrayType; 4548 T = Info.S.Context.getBaseElementType(T); 4549 } 4550 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4551 if (CT != Info.AbstractType) return; 4552 4553 // It matched; do some magic. 4554 if (Sel == Sema::AbstractArrayType) { 4555 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4556 << T << TL.getSourceRange(); 4557 } else { 4558 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4559 << Sel << T << TL.getSourceRange(); 4560 } 4561 Info.DiagnoseAbstractType(); 4562 } 4563 }; 4564 4565 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4566 Sema::AbstractDiagSelID Sel) { 4567 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4568 } 4569 4570 } 4571 4572 /// Check for invalid uses of an abstract type in a method declaration. 4573 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4574 CXXMethodDecl *MD) { 4575 // No need to do the check on definitions, which require that 4576 // the return/param types be complete. 4577 if (MD->doesThisDeclarationHaveABody()) 4578 return; 4579 4580 // For safety's sake, just ignore it if we don't have type source 4581 // information. This should never happen for non-implicit methods, 4582 // but... 4583 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4584 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4585 } 4586 4587 /// Check for invalid uses of an abstract type within a class definition. 4588 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4589 CXXRecordDecl *RD) { 4590 for (auto *D : RD->decls()) { 4591 if (D->isImplicit()) continue; 4592 4593 // Methods and method templates. 4594 if (isa<CXXMethodDecl>(D)) { 4595 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4596 } else if (isa<FunctionTemplateDecl>(D)) { 4597 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4598 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4599 4600 // Fields and static variables. 4601 } else if (isa<FieldDecl>(D)) { 4602 FieldDecl *FD = cast<FieldDecl>(D); 4603 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4604 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4605 } else if (isa<VarDecl>(D)) { 4606 VarDecl *VD = cast<VarDecl>(D); 4607 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4608 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4609 4610 // Nested classes and class templates. 4611 } else if (isa<CXXRecordDecl>(D)) { 4612 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4613 } else if (isa<ClassTemplateDecl>(D)) { 4614 CheckAbstractClassUsage(Info, 4615 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4616 } 4617 } 4618 } 4619 4620 /// \brief Check class-level dllimport/dllexport attribute. 4621 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4622 Attr *ClassAttr = getDLLAttr(Class); 4623 4624 // MSVC inherits DLL attributes to partial class template specializations. 4625 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4626 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4627 if (Attr *TemplateAttr = 4628 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4629 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext())); 4630 A->setInherited(true); 4631 ClassAttr = A; 4632 } 4633 } 4634 } 4635 4636 if (!ClassAttr) 4637 return; 4638 4639 if (!Class->isExternallyVisible()) { 4640 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4641 << Class << ClassAttr; 4642 return; 4643 } 4644 4645 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4646 !ClassAttr->isInherited()) { 4647 // Diagnose dll attributes on members of class with dll attribute. 4648 for (Decl *Member : Class->decls()) { 4649 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4650 continue; 4651 InheritableAttr *MemberAttr = getDLLAttr(Member); 4652 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4653 continue; 4654 4655 S.Diag(MemberAttr->getLocation(), 4656 diag::err_attribute_dll_member_of_dll_class) 4657 << MemberAttr << ClassAttr; 4658 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4659 Member->setInvalidDecl(); 4660 } 4661 } 4662 4663 if (Class->getDescribedClassTemplate()) 4664 // Don't inherit dll attribute until the template is instantiated. 4665 return; 4666 4667 // The class is either imported or exported. 4668 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4669 const bool ClassImported = !ClassExported; 4670 4671 // Force declaration of implicit members so they can inherit the attribute. 4672 S.ForceDeclarationOfImplicitMembers(Class); 4673 4674 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4675 // seem to be true in practice? 4676 4677 TemplateSpecializationKind TSK = 4678 Class->getTemplateSpecializationKind(); 4679 4680 for (Decl *Member : Class->decls()) { 4681 VarDecl *VD = dyn_cast<VarDecl>(Member); 4682 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4683 4684 // Only methods and static fields inherit the attributes. 4685 if (!VD && !MD) 4686 continue; 4687 4688 if (MD) { 4689 // Don't process deleted methods. 4690 if (MD->isDeleted()) 4691 continue; 4692 4693 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) { 4694 // Current MSVC versions don't export the move assignment operators, so 4695 // don't attempt to import them if we have a definition. 4696 continue; 4697 } 4698 4699 if (MD->isInlined() && ClassImported && 4700 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4701 // MinGW does not import inline functions. 4702 continue; 4703 } 4704 } 4705 4706 if (!getDLLAttr(Member)) { 4707 auto *NewAttr = 4708 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4709 NewAttr->setInherited(true); 4710 Member->addAttr(NewAttr); 4711 } 4712 4713 if (MD && ClassExported) { 4714 if (MD->isUserProvided()) { 4715 // Instantiate non-default methods.. 4716 4717 // .. except for certain kinds of template specializations. 4718 if (TSK == TSK_ExplicitInstantiationDeclaration) 4719 continue; 4720 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4721 continue; 4722 4723 S.MarkFunctionReferenced(Class->getLocation(), MD); 4724 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4725 MD->isCopyAssignmentOperator() || 4726 MD->isMoveAssignmentOperator()) { 4727 // Instantiate non-trivial or explicitly defaulted methods, and the 4728 // copy assignment / move assignment operators. 4729 S.MarkFunctionReferenced(Class->getLocation(), MD); 4730 // Resolve its exception specification; CodeGen needs it. 4731 auto *FPT = MD->getType()->getAs<FunctionProtoType>(); 4732 S.ResolveExceptionSpec(Class->getLocation(), FPT); 4733 S.ActOnFinishInlineMethodDef(MD); 4734 } 4735 } 4736 } 4737 } 4738 4739 /// \brief Perform semantic checks on a class definition that has been 4740 /// completing, introducing implicitly-declared members, checking for 4741 /// abstract types, etc. 4742 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4743 if (!Record) 4744 return; 4745 4746 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4747 AbstractUsageInfo Info(*this, Record); 4748 CheckAbstractClassUsage(Info, Record); 4749 } 4750 4751 // If this is not an aggregate type and has no user-declared constructor, 4752 // complain about any non-static data members of reference or const scalar 4753 // type, since they will never get initializers. 4754 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4755 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4756 !Record->isLambda()) { 4757 bool Complained = false; 4758 for (const auto *F : Record->fields()) { 4759 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4760 continue; 4761 4762 if (F->getType()->isReferenceType() || 4763 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4764 if (!Complained) { 4765 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4766 << Record->getTagKind() << Record; 4767 Complained = true; 4768 } 4769 4770 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4771 << F->getType()->isReferenceType() 4772 << F->getDeclName(); 4773 } 4774 } 4775 } 4776 4777 if (Record->isDynamicClass() && !Record->isDependentType()) 4778 DynamicClasses.push_back(Record); 4779 4780 if (Record->getIdentifier()) { 4781 // C++ [class.mem]p13: 4782 // If T is the name of a class, then each of the following shall have a 4783 // name different from T: 4784 // - every member of every anonymous union that is a member of class T. 4785 // 4786 // C++ [class.mem]p14: 4787 // In addition, if class T has a user-declared constructor (12.1), every 4788 // non-static data member of class T shall have a name different from T. 4789 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4790 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4791 ++I) { 4792 NamedDecl *D = *I; 4793 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4794 isa<IndirectFieldDecl>(D)) { 4795 Diag(D->getLocation(), diag::err_member_name_of_class) 4796 << D->getDeclName(); 4797 break; 4798 } 4799 } 4800 } 4801 4802 // Warn if the class has virtual methods but non-virtual public destructor. 4803 if (Record->isPolymorphic() && !Record->isDependentType()) { 4804 CXXDestructorDecl *dtor = Record->getDestructor(); 4805 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4806 !Record->hasAttr<FinalAttr>()) 4807 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4808 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4809 } 4810 4811 if (Record->isAbstract()) { 4812 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4813 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4814 << FA->isSpelledAsSealed(); 4815 DiagnoseAbstractType(Record); 4816 } 4817 } 4818 4819 bool HasMethodWithOverrideControl = false, 4820 HasOverridingMethodWithoutOverrideControl = false; 4821 if (!Record->isDependentType()) { 4822 for (auto *M : Record->methods()) { 4823 // See if a method overloads virtual methods in a base 4824 // class without overriding any. 4825 if (!M->isStatic()) 4826 DiagnoseHiddenVirtualMethods(M); 4827 if (M->hasAttr<OverrideAttr>()) 4828 HasMethodWithOverrideControl = true; 4829 else if (M->size_overridden_methods() > 0) 4830 HasOverridingMethodWithoutOverrideControl = true; 4831 // Check whether the explicitly-defaulted special members are valid. 4832 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4833 CheckExplicitlyDefaultedSpecialMember(M); 4834 4835 // For an explicitly defaulted or deleted special member, we defer 4836 // determining triviality until the class is complete. That time is now! 4837 if (!M->isImplicit() && !M->isUserProvided()) { 4838 CXXSpecialMember CSM = getSpecialMember(M); 4839 if (CSM != CXXInvalid) { 4840 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4841 4842 // Inform the class that we've finished declaring this member. 4843 Record->finishedDefaultedOrDeletedMember(M); 4844 } 4845 } 4846 } 4847 } 4848 4849 if (HasMethodWithOverrideControl && 4850 HasOverridingMethodWithoutOverrideControl) { 4851 // At least one method has the 'override' control declared. 4852 // Diagnose all other overridden methods which do not have 'override' specified on them. 4853 for (auto *M : Record->methods()) 4854 DiagnoseAbsenceOfOverrideControl(M); 4855 } 4856 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4857 // function that is not a constructor declares that member function to be 4858 // const. [...] The class of which that function is a member shall be 4859 // a literal type. 4860 // 4861 // If the class has virtual bases, any constexpr members will already have 4862 // been diagnosed by the checks performed on the member declaration, so 4863 // suppress this (less useful) diagnostic. 4864 // 4865 // We delay this until we know whether an explicitly-defaulted (or deleted) 4866 // destructor for the class is trivial. 4867 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4868 !Record->isLiteral() && !Record->getNumVBases()) { 4869 for (const auto *M : Record->methods()) { 4870 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4871 switch (Record->getTemplateSpecializationKind()) { 4872 case TSK_ImplicitInstantiation: 4873 case TSK_ExplicitInstantiationDeclaration: 4874 case TSK_ExplicitInstantiationDefinition: 4875 // If a template instantiates to a non-literal type, but its members 4876 // instantiate to constexpr functions, the template is technically 4877 // ill-formed, but we allow it for sanity. 4878 continue; 4879 4880 case TSK_Undeclared: 4881 case TSK_ExplicitSpecialization: 4882 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4883 diag::err_constexpr_method_non_literal); 4884 break; 4885 } 4886 4887 // Only produce one error per class. 4888 break; 4889 } 4890 } 4891 } 4892 4893 // ms_struct is a request to use the same ABI rules as MSVC. Check 4894 // whether this class uses any C++ features that are implemented 4895 // completely differently in MSVC, and if so, emit a diagnostic. 4896 // That diagnostic defaults to an error, but we allow projects to 4897 // map it down to a warning (or ignore it). It's a fairly common 4898 // practice among users of the ms_struct pragma to mass-annotate 4899 // headers, sweeping up a bunch of types that the project doesn't 4900 // really rely on MSVC-compatible layout for. We must therefore 4901 // support "ms_struct except for C++ stuff" as a secondary ABI. 4902 if (Record->isMsStruct(Context) && 4903 (Record->isPolymorphic() || Record->getNumBases())) { 4904 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4905 } 4906 4907 // Declare inheriting constructors. We do this eagerly here because: 4908 // - The standard requires an eager diagnostic for conflicting inheriting 4909 // constructors from different classes. 4910 // - The lazy declaration of the other implicit constructors is so as to not 4911 // waste space and performance on classes that are not meant to be 4912 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4913 // have inheriting constructors. 4914 DeclareInheritingConstructors(Record); 4915 4916 checkDLLAttribute(*this, Record); 4917 } 4918 4919 /// Look up the special member function that would be called by a special 4920 /// member function for a subobject of class type. 4921 /// 4922 /// \param Class The class type of the subobject. 4923 /// \param CSM The kind of special member function. 4924 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4925 /// \param ConstRHS True if this is a copy operation with a const object 4926 /// on its RHS, that is, if the argument to the outer special member 4927 /// function is 'const' and this is not a field marked 'mutable'. 4928 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4929 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4930 unsigned FieldQuals, bool ConstRHS) { 4931 unsigned LHSQuals = 0; 4932 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4933 LHSQuals = FieldQuals; 4934 4935 unsigned RHSQuals = FieldQuals; 4936 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4937 RHSQuals = 0; 4938 else if (ConstRHS) 4939 RHSQuals |= Qualifiers::Const; 4940 4941 return S.LookupSpecialMember(Class, CSM, 4942 RHSQuals & Qualifiers::Const, 4943 RHSQuals & Qualifiers::Volatile, 4944 false, 4945 LHSQuals & Qualifiers::Const, 4946 LHSQuals & Qualifiers::Volatile); 4947 } 4948 4949 /// Is the special member function which would be selected to perform the 4950 /// specified operation on the specified class type a constexpr constructor? 4951 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4952 Sema::CXXSpecialMember CSM, 4953 unsigned Quals, bool ConstRHS) { 4954 Sema::SpecialMemberOverloadResult *SMOR = 4955 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4956 if (!SMOR || !SMOR->getMethod()) 4957 // A constructor we wouldn't select can't be "involved in initializing" 4958 // anything. 4959 return true; 4960 return SMOR->getMethod()->isConstexpr(); 4961 } 4962 4963 /// Determine whether the specified special member function would be constexpr 4964 /// if it were implicitly defined. 4965 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4966 Sema::CXXSpecialMember CSM, 4967 bool ConstArg) { 4968 if (!S.getLangOpts().CPlusPlus11) 4969 return false; 4970 4971 // C++11 [dcl.constexpr]p4: 4972 // In the definition of a constexpr constructor [...] 4973 bool Ctor = true; 4974 switch (CSM) { 4975 case Sema::CXXDefaultConstructor: 4976 // Since default constructor lookup is essentially trivial (and cannot 4977 // involve, for instance, template instantiation), we compute whether a 4978 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4979 // 4980 // This is important for performance; we need to know whether the default 4981 // constructor is constexpr to determine whether the type is a literal type. 4982 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4983 4984 case Sema::CXXCopyConstructor: 4985 case Sema::CXXMoveConstructor: 4986 // For copy or move constructors, we need to perform overload resolution. 4987 break; 4988 4989 case Sema::CXXCopyAssignment: 4990 case Sema::CXXMoveAssignment: 4991 if (!S.getLangOpts().CPlusPlus14) 4992 return false; 4993 // In C++1y, we need to perform overload resolution. 4994 Ctor = false; 4995 break; 4996 4997 case Sema::CXXDestructor: 4998 case Sema::CXXInvalid: 4999 return false; 5000 } 5001 5002 // -- if the class is a non-empty union, or for each non-empty anonymous 5003 // union member of a non-union class, exactly one non-static data member 5004 // shall be initialized; [DR1359] 5005 // 5006 // If we squint, this is guaranteed, since exactly one non-static data member 5007 // will be initialized (if the constructor isn't deleted), we just don't know 5008 // which one. 5009 if (Ctor && ClassDecl->isUnion()) 5010 return true; 5011 5012 // -- the class shall not have any virtual base classes; 5013 if (Ctor && ClassDecl->getNumVBases()) 5014 return false; 5015 5016 // C++1y [class.copy]p26: 5017 // -- [the class] is a literal type, and 5018 if (!Ctor && !ClassDecl->isLiteral()) 5019 return false; 5020 5021 // -- every constructor involved in initializing [...] base class 5022 // sub-objects shall be a constexpr constructor; 5023 // -- the assignment operator selected to copy/move each direct base 5024 // class is a constexpr function, and 5025 for (const auto &B : ClassDecl->bases()) { 5026 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5027 if (!BaseType) continue; 5028 5029 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5030 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5031 return false; 5032 } 5033 5034 // -- every constructor involved in initializing non-static data members 5035 // [...] shall be a constexpr constructor; 5036 // -- every non-static data member and base class sub-object shall be 5037 // initialized 5038 // -- for each non-static data member of X that is of class type (or array 5039 // thereof), the assignment operator selected to copy/move that member is 5040 // a constexpr function 5041 for (const auto *F : ClassDecl->fields()) { 5042 if (F->isInvalidDecl()) 5043 continue; 5044 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5045 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5046 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5047 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5048 BaseType.getCVRQualifiers(), 5049 ConstArg && !F->isMutable())) 5050 return false; 5051 } 5052 } 5053 5054 // All OK, it's constexpr! 5055 return true; 5056 } 5057 5058 static Sema::ImplicitExceptionSpecification 5059 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5060 switch (S.getSpecialMember(MD)) { 5061 case Sema::CXXDefaultConstructor: 5062 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5063 case Sema::CXXCopyConstructor: 5064 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5065 case Sema::CXXCopyAssignment: 5066 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5067 case Sema::CXXMoveConstructor: 5068 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5069 case Sema::CXXMoveAssignment: 5070 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5071 case Sema::CXXDestructor: 5072 return S.ComputeDefaultedDtorExceptionSpec(MD); 5073 case Sema::CXXInvalid: 5074 break; 5075 } 5076 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5077 "only special members have implicit exception specs"); 5078 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5079 } 5080 5081 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5082 CXXMethodDecl *MD) { 5083 FunctionProtoType::ExtProtoInfo EPI; 5084 5085 // Build an exception specification pointing back at this member. 5086 EPI.ExceptionSpec.Type = EST_Unevaluated; 5087 EPI.ExceptionSpec.SourceDecl = MD; 5088 5089 // Set the calling convention to the default for C++ instance methods. 5090 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5091 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5092 /*IsCXXMethod=*/true)); 5093 return EPI; 5094 } 5095 5096 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5097 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5098 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5099 return; 5100 5101 // Evaluate the exception specification. 5102 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5103 5104 // Update the type of the special member to use it. 5105 UpdateExceptionSpec(MD, ESI); 5106 5107 // A user-provided destructor can be defined outside the class. When that 5108 // happens, be sure to update the exception specification on both 5109 // declarations. 5110 const FunctionProtoType *CanonicalFPT = 5111 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5112 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5113 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5114 } 5115 5116 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5117 CXXRecordDecl *RD = MD->getParent(); 5118 CXXSpecialMember CSM = getSpecialMember(MD); 5119 5120 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5121 "not an explicitly-defaulted special member"); 5122 5123 // Whether this was the first-declared instance of the constructor. 5124 // This affects whether we implicitly add an exception spec and constexpr. 5125 bool First = MD == MD->getCanonicalDecl(); 5126 5127 bool HadError = false; 5128 5129 // C++11 [dcl.fct.def.default]p1: 5130 // A function that is explicitly defaulted shall 5131 // -- be a special member function (checked elsewhere), 5132 // -- have the same type (except for ref-qualifiers, and except that a 5133 // copy operation can take a non-const reference) as an implicit 5134 // declaration, and 5135 // -- not have default arguments. 5136 unsigned ExpectedParams = 1; 5137 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5138 ExpectedParams = 0; 5139 if (MD->getNumParams() != ExpectedParams) { 5140 // This also checks for default arguments: a copy or move constructor with a 5141 // default argument is classified as a default constructor, and assignment 5142 // operations and destructors can't have default arguments. 5143 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5144 << CSM << MD->getSourceRange(); 5145 HadError = true; 5146 } else if (MD->isVariadic()) { 5147 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5148 << CSM << MD->getSourceRange(); 5149 HadError = true; 5150 } 5151 5152 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5153 5154 bool CanHaveConstParam = false; 5155 if (CSM == CXXCopyConstructor) 5156 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5157 else if (CSM == CXXCopyAssignment) 5158 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5159 5160 QualType ReturnType = Context.VoidTy; 5161 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5162 // Check for return type matching. 5163 ReturnType = Type->getReturnType(); 5164 QualType ExpectedReturnType = 5165 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5166 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5167 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5168 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5169 HadError = true; 5170 } 5171 5172 // A defaulted special member cannot have cv-qualifiers. 5173 if (Type->getTypeQuals()) { 5174 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5175 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5176 HadError = true; 5177 } 5178 } 5179 5180 // Check for parameter type matching. 5181 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5182 bool HasConstParam = false; 5183 if (ExpectedParams && ArgType->isReferenceType()) { 5184 // Argument must be reference to possibly-const T. 5185 QualType ReferentType = ArgType->getPointeeType(); 5186 HasConstParam = ReferentType.isConstQualified(); 5187 5188 if (ReferentType.isVolatileQualified()) { 5189 Diag(MD->getLocation(), 5190 diag::err_defaulted_special_member_volatile_param) << CSM; 5191 HadError = true; 5192 } 5193 5194 if (HasConstParam && !CanHaveConstParam) { 5195 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5196 Diag(MD->getLocation(), 5197 diag::err_defaulted_special_member_copy_const_param) 5198 << (CSM == CXXCopyAssignment); 5199 // FIXME: Explain why this special member can't be const. 5200 } else { 5201 Diag(MD->getLocation(), 5202 diag::err_defaulted_special_member_move_const_param) 5203 << (CSM == CXXMoveAssignment); 5204 } 5205 HadError = true; 5206 } 5207 } else if (ExpectedParams) { 5208 // A copy assignment operator can take its argument by value, but a 5209 // defaulted one cannot. 5210 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5211 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5212 HadError = true; 5213 } 5214 5215 // C++11 [dcl.fct.def.default]p2: 5216 // An explicitly-defaulted function may be declared constexpr only if it 5217 // would have been implicitly declared as constexpr, 5218 // Do not apply this rule to members of class templates, since core issue 1358 5219 // makes such functions always instantiate to constexpr functions. For 5220 // functions which cannot be constexpr (for non-constructors in C++11 and for 5221 // destructors in C++1y), this is checked elsewhere. 5222 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5223 HasConstParam); 5224 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5225 : isa<CXXConstructorDecl>(MD)) && 5226 MD->isConstexpr() && !Constexpr && 5227 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5228 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5229 // FIXME: Explain why the special member can't be constexpr. 5230 HadError = true; 5231 } 5232 5233 // and may have an explicit exception-specification only if it is compatible 5234 // with the exception-specification on the implicit declaration. 5235 if (Type->hasExceptionSpec()) { 5236 // Delay the check if this is the first declaration of the special member, 5237 // since we may not have parsed some necessary in-class initializers yet. 5238 if (First) { 5239 // If the exception specification needs to be instantiated, do so now, 5240 // before we clobber it with an EST_Unevaluated specification below. 5241 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5242 InstantiateExceptionSpec(MD->getLocStart(), MD); 5243 Type = MD->getType()->getAs<FunctionProtoType>(); 5244 } 5245 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5246 } else 5247 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5248 } 5249 5250 // If a function is explicitly defaulted on its first declaration, 5251 if (First) { 5252 // -- it is implicitly considered to be constexpr if the implicit 5253 // definition would be, 5254 MD->setConstexpr(Constexpr); 5255 5256 // -- it is implicitly considered to have the same exception-specification 5257 // as if it had been implicitly declared, 5258 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5259 EPI.ExceptionSpec.Type = EST_Unevaluated; 5260 EPI.ExceptionSpec.SourceDecl = MD; 5261 MD->setType(Context.getFunctionType(ReturnType, 5262 llvm::makeArrayRef(&ArgType, 5263 ExpectedParams), 5264 EPI)); 5265 } 5266 5267 if (ShouldDeleteSpecialMember(MD, CSM)) { 5268 if (First) { 5269 SetDeclDeleted(MD, MD->getLocation()); 5270 } else { 5271 // C++11 [dcl.fct.def.default]p4: 5272 // [For a] user-provided explicitly-defaulted function [...] if such a 5273 // function is implicitly defined as deleted, the program is ill-formed. 5274 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5275 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5276 HadError = true; 5277 } 5278 } 5279 5280 if (HadError) 5281 MD->setInvalidDecl(); 5282 } 5283 5284 /// Check whether the exception specification provided for an 5285 /// explicitly-defaulted special member matches the exception specification 5286 /// that would have been generated for an implicit special member, per 5287 /// C++11 [dcl.fct.def.default]p2. 5288 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5289 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5290 // If the exception specification was explicitly specified but hadn't been 5291 // parsed when the method was defaulted, grab it now. 5292 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5293 SpecifiedType = 5294 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5295 5296 // Compute the implicit exception specification. 5297 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5298 /*IsCXXMethod=*/true); 5299 FunctionProtoType::ExtProtoInfo EPI(CC); 5300 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5301 .getExceptionSpec(); 5302 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5303 Context.getFunctionType(Context.VoidTy, None, EPI)); 5304 5305 // Ensure that it matches. 5306 CheckEquivalentExceptionSpec( 5307 PDiag(diag::err_incorrect_defaulted_exception_spec) 5308 << getSpecialMember(MD), PDiag(), 5309 ImplicitType, SourceLocation(), 5310 SpecifiedType, MD->getLocation()); 5311 } 5312 5313 void Sema::CheckDelayedMemberExceptionSpecs() { 5314 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 5315 2> Checks; 5316 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 5317 5318 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 5319 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5320 5321 // Perform any deferred checking of exception specifications for virtual 5322 // destructors. 5323 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 5324 const CXXDestructorDecl *Dtor = Checks[i].first; 5325 assert(!Dtor->getParent()->isDependentType() && 5326 "Should not ever add destructors of templates into the list."); 5327 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 5328 } 5329 5330 // Check that any explicitly-defaulted methods have exception specifications 5331 // compatible with their implicit exception specifications. 5332 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 5333 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 5334 Specs[I].second); 5335 } 5336 5337 namespace { 5338 struct SpecialMemberDeletionInfo { 5339 Sema &S; 5340 CXXMethodDecl *MD; 5341 Sema::CXXSpecialMember CSM; 5342 bool Diagnose; 5343 5344 // Properties of the special member, computed for convenience. 5345 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5346 SourceLocation Loc; 5347 5348 bool AllFieldsAreConst; 5349 5350 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5351 Sema::CXXSpecialMember CSM, bool Diagnose) 5352 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5353 IsConstructor(false), IsAssignment(false), IsMove(false), 5354 ConstArg(false), Loc(MD->getLocation()), 5355 AllFieldsAreConst(true) { 5356 switch (CSM) { 5357 case Sema::CXXDefaultConstructor: 5358 case Sema::CXXCopyConstructor: 5359 IsConstructor = true; 5360 break; 5361 case Sema::CXXMoveConstructor: 5362 IsConstructor = true; 5363 IsMove = true; 5364 break; 5365 case Sema::CXXCopyAssignment: 5366 IsAssignment = true; 5367 break; 5368 case Sema::CXXMoveAssignment: 5369 IsAssignment = true; 5370 IsMove = true; 5371 break; 5372 case Sema::CXXDestructor: 5373 break; 5374 case Sema::CXXInvalid: 5375 llvm_unreachable("invalid special member kind"); 5376 } 5377 5378 if (MD->getNumParams()) { 5379 if (const ReferenceType *RT = 5380 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5381 ConstArg = RT->getPointeeType().isConstQualified(); 5382 } 5383 } 5384 5385 bool inUnion() const { return MD->getParent()->isUnion(); } 5386 5387 /// Look up the corresponding special member in the given class. 5388 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5389 unsigned Quals, bool IsMutable) { 5390 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5391 ConstArg && !IsMutable); 5392 } 5393 5394 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5395 5396 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5397 bool shouldDeleteForField(FieldDecl *FD); 5398 bool shouldDeleteForAllConstMembers(); 5399 5400 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5401 unsigned Quals); 5402 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5403 Sema::SpecialMemberOverloadResult *SMOR, 5404 bool IsDtorCallInCtor); 5405 5406 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5407 }; 5408 } 5409 5410 /// Is the given special member inaccessible when used on the given 5411 /// sub-object. 5412 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5413 CXXMethodDecl *target) { 5414 /// If we're operating on a base class, the object type is the 5415 /// type of this special member. 5416 QualType objectTy; 5417 AccessSpecifier access = target->getAccess(); 5418 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5419 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5420 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5421 5422 // If we're operating on a field, the object type is the type of the field. 5423 } else { 5424 objectTy = S.Context.getTypeDeclType(target->getParent()); 5425 } 5426 5427 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5428 } 5429 5430 /// Check whether we should delete a special member due to the implicit 5431 /// definition containing a call to a special member of a subobject. 5432 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5433 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5434 bool IsDtorCallInCtor) { 5435 CXXMethodDecl *Decl = SMOR->getMethod(); 5436 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5437 5438 int DiagKind = -1; 5439 5440 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5441 DiagKind = !Decl ? 0 : 1; 5442 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5443 DiagKind = 2; 5444 else if (!isAccessible(Subobj, Decl)) 5445 DiagKind = 3; 5446 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5447 !Decl->isTrivial()) { 5448 // A member of a union must have a trivial corresponding special member. 5449 // As a weird special case, a destructor call from a union's constructor 5450 // must be accessible and non-deleted, but need not be trivial. Such a 5451 // destructor is never actually called, but is semantically checked as 5452 // if it were. 5453 DiagKind = 4; 5454 } 5455 5456 if (DiagKind == -1) 5457 return false; 5458 5459 if (Diagnose) { 5460 if (Field) { 5461 S.Diag(Field->getLocation(), 5462 diag::note_deleted_special_member_class_subobject) 5463 << CSM << MD->getParent() << /*IsField*/true 5464 << Field << DiagKind << IsDtorCallInCtor; 5465 } else { 5466 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5467 S.Diag(Base->getLocStart(), 5468 diag::note_deleted_special_member_class_subobject) 5469 << CSM << MD->getParent() << /*IsField*/false 5470 << Base->getType() << DiagKind << IsDtorCallInCtor; 5471 } 5472 5473 if (DiagKind == 1) 5474 S.NoteDeletedFunction(Decl); 5475 // FIXME: Explain inaccessibility if DiagKind == 3. 5476 } 5477 5478 return true; 5479 } 5480 5481 /// Check whether we should delete a special member function due to having a 5482 /// direct or virtual base class or non-static data member of class type M. 5483 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5484 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5485 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5486 bool IsMutable = Field && Field->isMutable(); 5487 5488 // C++11 [class.ctor]p5: 5489 // -- any direct or virtual base class, or non-static data member with no 5490 // brace-or-equal-initializer, has class type M (or array thereof) and 5491 // either M has no default constructor or overload resolution as applied 5492 // to M's default constructor results in an ambiguity or in a function 5493 // that is deleted or inaccessible 5494 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5495 // -- a direct or virtual base class B that cannot be copied/moved because 5496 // overload resolution, as applied to B's corresponding special member, 5497 // results in an ambiguity or a function that is deleted or inaccessible 5498 // from the defaulted special member 5499 // C++11 [class.dtor]p5: 5500 // -- any direct or virtual base class [...] has a type with a destructor 5501 // that is deleted or inaccessible 5502 if (!(CSM == Sema::CXXDefaultConstructor && 5503 Field && Field->hasInClassInitializer()) && 5504 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5505 false)) 5506 return true; 5507 5508 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5509 // -- any direct or virtual base class or non-static data member has a 5510 // type with a destructor that is deleted or inaccessible 5511 if (IsConstructor) { 5512 Sema::SpecialMemberOverloadResult *SMOR = 5513 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5514 false, false, false, false, false); 5515 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5516 return true; 5517 } 5518 5519 return false; 5520 } 5521 5522 /// Check whether we should delete a special member function due to the class 5523 /// having a particular direct or virtual base class. 5524 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5525 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5526 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5527 } 5528 5529 /// Check whether we should delete a special member function due to the class 5530 /// having a particular non-static data member. 5531 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5532 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5533 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5534 5535 if (CSM == Sema::CXXDefaultConstructor) { 5536 // For a default constructor, all references must be initialized in-class 5537 // and, if a union, it must have a non-const member. 5538 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5539 if (Diagnose) 5540 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5541 << MD->getParent() << FD << FieldType << /*Reference*/0; 5542 return true; 5543 } 5544 // C++11 [class.ctor]p5: any non-variant non-static data member of 5545 // const-qualified type (or array thereof) with no 5546 // brace-or-equal-initializer does not have a user-provided default 5547 // constructor. 5548 if (!inUnion() && FieldType.isConstQualified() && 5549 !FD->hasInClassInitializer() && 5550 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5551 if (Diagnose) 5552 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5553 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5554 return true; 5555 } 5556 5557 if (inUnion() && !FieldType.isConstQualified()) 5558 AllFieldsAreConst = false; 5559 } else if (CSM == Sema::CXXCopyConstructor) { 5560 // For a copy constructor, data members must not be of rvalue reference 5561 // type. 5562 if (FieldType->isRValueReferenceType()) { 5563 if (Diagnose) 5564 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5565 << MD->getParent() << FD << FieldType; 5566 return true; 5567 } 5568 } else if (IsAssignment) { 5569 // For an assignment operator, data members must not be of reference type. 5570 if (FieldType->isReferenceType()) { 5571 if (Diagnose) 5572 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5573 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5574 return true; 5575 } 5576 if (!FieldRecord && FieldType.isConstQualified()) { 5577 // C++11 [class.copy]p23: 5578 // -- a non-static data member of const non-class type (or array thereof) 5579 if (Diagnose) 5580 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5581 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5582 return true; 5583 } 5584 } 5585 5586 if (FieldRecord) { 5587 // Some additional restrictions exist on the variant members. 5588 if (!inUnion() && FieldRecord->isUnion() && 5589 FieldRecord->isAnonymousStructOrUnion()) { 5590 bool AllVariantFieldsAreConst = true; 5591 5592 // FIXME: Handle anonymous unions declared within anonymous unions. 5593 for (auto *UI : FieldRecord->fields()) { 5594 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5595 5596 if (!UnionFieldType.isConstQualified()) 5597 AllVariantFieldsAreConst = false; 5598 5599 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5600 if (UnionFieldRecord && 5601 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5602 UnionFieldType.getCVRQualifiers())) 5603 return true; 5604 } 5605 5606 // At least one member in each anonymous union must be non-const 5607 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5608 !FieldRecord->field_empty()) { 5609 if (Diagnose) 5610 S.Diag(FieldRecord->getLocation(), 5611 diag::note_deleted_default_ctor_all_const) 5612 << MD->getParent() << /*anonymous union*/1; 5613 return true; 5614 } 5615 5616 // Don't check the implicit member of the anonymous union type. 5617 // This is technically non-conformant, but sanity demands it. 5618 return false; 5619 } 5620 5621 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5622 FieldType.getCVRQualifiers())) 5623 return true; 5624 } 5625 5626 return false; 5627 } 5628 5629 /// C++11 [class.ctor] p5: 5630 /// A defaulted default constructor for a class X is defined as deleted if 5631 /// X is a union and all of its variant members are of const-qualified type. 5632 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5633 // This is a silly definition, because it gives an empty union a deleted 5634 // default constructor. Don't do that. 5635 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5636 !MD->getParent()->field_empty()) { 5637 if (Diagnose) 5638 S.Diag(MD->getParent()->getLocation(), 5639 diag::note_deleted_default_ctor_all_const) 5640 << MD->getParent() << /*not anonymous union*/0; 5641 return true; 5642 } 5643 return false; 5644 } 5645 5646 /// Determine whether a defaulted special member function should be defined as 5647 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5648 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5649 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5650 bool Diagnose) { 5651 if (MD->isInvalidDecl()) 5652 return false; 5653 CXXRecordDecl *RD = MD->getParent(); 5654 assert(!RD->isDependentType() && "do deletion after instantiation"); 5655 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5656 return false; 5657 5658 // C++11 [expr.lambda.prim]p19: 5659 // The closure type associated with a lambda-expression has a 5660 // deleted (8.4.3) default constructor and a deleted copy 5661 // assignment operator. 5662 if (RD->isLambda() && 5663 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5664 if (Diagnose) 5665 Diag(RD->getLocation(), diag::note_lambda_decl); 5666 return true; 5667 } 5668 5669 // For an anonymous struct or union, the copy and assignment special members 5670 // will never be used, so skip the check. For an anonymous union declared at 5671 // namespace scope, the constructor and destructor are used. 5672 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5673 RD->isAnonymousStructOrUnion()) 5674 return false; 5675 5676 // C++11 [class.copy]p7, p18: 5677 // If the class definition declares a move constructor or move assignment 5678 // operator, an implicitly declared copy constructor or copy assignment 5679 // operator is defined as deleted. 5680 if (MD->isImplicit() && 5681 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5682 CXXMethodDecl *UserDeclaredMove = nullptr; 5683 5684 // In Microsoft mode, a user-declared move only causes the deletion of the 5685 // corresponding copy operation, not both copy operations. 5686 if (RD->hasUserDeclaredMoveConstructor() && 5687 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5688 if (!Diagnose) return true; 5689 5690 // Find any user-declared move constructor. 5691 for (auto *I : RD->ctors()) { 5692 if (I->isMoveConstructor()) { 5693 UserDeclaredMove = I; 5694 break; 5695 } 5696 } 5697 assert(UserDeclaredMove); 5698 } else if (RD->hasUserDeclaredMoveAssignment() && 5699 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5700 if (!Diagnose) return true; 5701 5702 // Find any user-declared move assignment operator. 5703 for (auto *I : RD->methods()) { 5704 if (I->isMoveAssignmentOperator()) { 5705 UserDeclaredMove = I; 5706 break; 5707 } 5708 } 5709 assert(UserDeclaredMove); 5710 } 5711 5712 if (UserDeclaredMove) { 5713 Diag(UserDeclaredMove->getLocation(), 5714 diag::note_deleted_copy_user_declared_move) 5715 << (CSM == CXXCopyAssignment) << RD 5716 << UserDeclaredMove->isMoveAssignmentOperator(); 5717 return true; 5718 } 5719 } 5720 5721 // Do access control from the special member function 5722 ContextRAII MethodContext(*this, MD); 5723 5724 // C++11 [class.dtor]p5: 5725 // -- for a virtual destructor, lookup of the non-array deallocation function 5726 // results in an ambiguity or in a function that is deleted or inaccessible 5727 if (CSM == CXXDestructor && MD->isVirtual()) { 5728 FunctionDecl *OperatorDelete = nullptr; 5729 DeclarationName Name = 5730 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5731 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5732 OperatorDelete, false)) { 5733 if (Diagnose) 5734 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5735 return true; 5736 } 5737 } 5738 5739 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5740 5741 for (auto &BI : RD->bases()) 5742 if (!BI.isVirtual() && 5743 SMI.shouldDeleteForBase(&BI)) 5744 return true; 5745 5746 // Per DR1611, do not consider virtual bases of constructors of abstract 5747 // classes, since we are not going to construct them. 5748 if (!RD->isAbstract() || !SMI.IsConstructor) { 5749 for (auto &BI : RD->vbases()) 5750 if (SMI.shouldDeleteForBase(&BI)) 5751 return true; 5752 } 5753 5754 for (auto *FI : RD->fields()) 5755 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5756 SMI.shouldDeleteForField(FI)) 5757 return true; 5758 5759 if (SMI.shouldDeleteForAllConstMembers()) 5760 return true; 5761 5762 if (getLangOpts().CUDA) { 5763 // We should delete the special member in CUDA mode if target inference 5764 // failed. 5765 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5766 Diagnose); 5767 } 5768 5769 return false; 5770 } 5771 5772 /// Perform lookup for a special member of the specified kind, and determine 5773 /// whether it is trivial. If the triviality can be determined without the 5774 /// lookup, skip it. This is intended for use when determining whether a 5775 /// special member of a containing object is trivial, and thus does not ever 5776 /// perform overload resolution for default constructors. 5777 /// 5778 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5779 /// member that was most likely to be intended to be trivial, if any. 5780 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5781 Sema::CXXSpecialMember CSM, unsigned Quals, 5782 bool ConstRHS, CXXMethodDecl **Selected) { 5783 if (Selected) 5784 *Selected = nullptr; 5785 5786 switch (CSM) { 5787 case Sema::CXXInvalid: 5788 llvm_unreachable("not a special member"); 5789 5790 case Sema::CXXDefaultConstructor: 5791 // C++11 [class.ctor]p5: 5792 // A default constructor is trivial if: 5793 // - all the [direct subobjects] have trivial default constructors 5794 // 5795 // Note, no overload resolution is performed in this case. 5796 if (RD->hasTrivialDefaultConstructor()) 5797 return true; 5798 5799 if (Selected) { 5800 // If there's a default constructor which could have been trivial, dig it 5801 // out. Otherwise, if there's any user-provided default constructor, point 5802 // to that as an example of why there's not a trivial one. 5803 CXXConstructorDecl *DefCtor = nullptr; 5804 if (RD->needsImplicitDefaultConstructor()) 5805 S.DeclareImplicitDefaultConstructor(RD); 5806 for (auto *CI : RD->ctors()) { 5807 if (!CI->isDefaultConstructor()) 5808 continue; 5809 DefCtor = CI; 5810 if (!DefCtor->isUserProvided()) 5811 break; 5812 } 5813 5814 *Selected = DefCtor; 5815 } 5816 5817 return false; 5818 5819 case Sema::CXXDestructor: 5820 // C++11 [class.dtor]p5: 5821 // A destructor is trivial if: 5822 // - all the direct [subobjects] have trivial destructors 5823 if (RD->hasTrivialDestructor()) 5824 return true; 5825 5826 if (Selected) { 5827 if (RD->needsImplicitDestructor()) 5828 S.DeclareImplicitDestructor(RD); 5829 *Selected = RD->getDestructor(); 5830 } 5831 5832 return false; 5833 5834 case Sema::CXXCopyConstructor: 5835 // C++11 [class.copy]p12: 5836 // A copy constructor is trivial if: 5837 // - the constructor selected to copy each direct [subobject] is trivial 5838 if (RD->hasTrivialCopyConstructor()) { 5839 if (Quals == Qualifiers::Const) 5840 // We must either select the trivial copy constructor or reach an 5841 // ambiguity; no need to actually perform overload resolution. 5842 return true; 5843 } else if (!Selected) { 5844 return false; 5845 } 5846 // In C++98, we are not supposed to perform overload resolution here, but we 5847 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5848 // cases like B as having a non-trivial copy constructor: 5849 // struct A { template<typename T> A(T&); }; 5850 // struct B { mutable A a; }; 5851 goto NeedOverloadResolution; 5852 5853 case Sema::CXXCopyAssignment: 5854 // C++11 [class.copy]p25: 5855 // A copy assignment operator is trivial if: 5856 // - the assignment operator selected to copy each direct [subobject] is 5857 // trivial 5858 if (RD->hasTrivialCopyAssignment()) { 5859 if (Quals == Qualifiers::Const) 5860 return true; 5861 } else if (!Selected) { 5862 return false; 5863 } 5864 // In C++98, we are not supposed to perform overload resolution here, but we 5865 // treat that as a language defect. 5866 goto NeedOverloadResolution; 5867 5868 case Sema::CXXMoveConstructor: 5869 case Sema::CXXMoveAssignment: 5870 NeedOverloadResolution: 5871 Sema::SpecialMemberOverloadResult *SMOR = 5872 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5873 5874 // The standard doesn't describe how to behave if the lookup is ambiguous. 5875 // We treat it as not making the member non-trivial, just like the standard 5876 // mandates for the default constructor. This should rarely matter, because 5877 // the member will also be deleted. 5878 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5879 return true; 5880 5881 if (!SMOR->getMethod()) { 5882 assert(SMOR->getKind() == 5883 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5884 return false; 5885 } 5886 5887 // We deliberately don't check if we found a deleted special member. We're 5888 // not supposed to! 5889 if (Selected) 5890 *Selected = SMOR->getMethod(); 5891 return SMOR->getMethod()->isTrivial(); 5892 } 5893 5894 llvm_unreachable("unknown special method kind"); 5895 } 5896 5897 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5898 for (auto *CI : RD->ctors()) 5899 if (!CI->isImplicit()) 5900 return CI; 5901 5902 // Look for constructor templates. 5903 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5904 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5905 if (CXXConstructorDecl *CD = 5906 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5907 return CD; 5908 } 5909 5910 return nullptr; 5911 } 5912 5913 /// The kind of subobject we are checking for triviality. The values of this 5914 /// enumeration are used in diagnostics. 5915 enum TrivialSubobjectKind { 5916 /// The subobject is a base class. 5917 TSK_BaseClass, 5918 /// The subobject is a non-static data member. 5919 TSK_Field, 5920 /// The object is actually the complete object. 5921 TSK_CompleteObject 5922 }; 5923 5924 /// Check whether the special member selected for a given type would be trivial. 5925 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5926 QualType SubType, bool ConstRHS, 5927 Sema::CXXSpecialMember CSM, 5928 TrivialSubobjectKind Kind, 5929 bool Diagnose) { 5930 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5931 if (!SubRD) 5932 return true; 5933 5934 CXXMethodDecl *Selected; 5935 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5936 ConstRHS, Diagnose ? &Selected : nullptr)) 5937 return true; 5938 5939 if (Diagnose) { 5940 if (ConstRHS) 5941 SubType.addConst(); 5942 5943 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5944 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5945 << Kind << SubType.getUnqualifiedType(); 5946 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5947 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5948 } else if (!Selected) 5949 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5950 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5951 else if (Selected->isUserProvided()) { 5952 if (Kind == TSK_CompleteObject) 5953 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5954 << Kind << SubType.getUnqualifiedType() << CSM; 5955 else { 5956 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5957 << Kind << SubType.getUnqualifiedType() << CSM; 5958 S.Diag(Selected->getLocation(), diag::note_declared_at); 5959 } 5960 } else { 5961 if (Kind != TSK_CompleteObject) 5962 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5963 << Kind << SubType.getUnqualifiedType() << CSM; 5964 5965 // Explain why the defaulted or deleted special member isn't trivial. 5966 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5967 } 5968 } 5969 5970 return false; 5971 } 5972 5973 /// Check whether the members of a class type allow a special member to be 5974 /// trivial. 5975 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5976 Sema::CXXSpecialMember CSM, 5977 bool ConstArg, bool Diagnose) { 5978 for (const auto *FI : RD->fields()) { 5979 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5980 continue; 5981 5982 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5983 5984 // Pretend anonymous struct or union members are members of this class. 5985 if (FI->isAnonymousStructOrUnion()) { 5986 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5987 CSM, ConstArg, Diagnose)) 5988 return false; 5989 continue; 5990 } 5991 5992 // C++11 [class.ctor]p5: 5993 // A default constructor is trivial if [...] 5994 // -- no non-static data member of its class has a 5995 // brace-or-equal-initializer 5996 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5997 if (Diagnose) 5998 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5999 return false; 6000 } 6001 6002 // Objective C ARC 4.3.5: 6003 // [...] nontrivally ownership-qualified types are [...] not trivially 6004 // default constructible, copy constructible, move constructible, copy 6005 // assignable, move assignable, or destructible [...] 6006 if (S.getLangOpts().ObjCAutoRefCount && 6007 FieldType.hasNonTrivialObjCLifetime()) { 6008 if (Diagnose) 6009 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6010 << RD << FieldType.getObjCLifetime(); 6011 return false; 6012 } 6013 6014 bool ConstRHS = ConstArg && !FI->isMutable(); 6015 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6016 CSM, TSK_Field, Diagnose)) 6017 return false; 6018 } 6019 6020 return true; 6021 } 6022 6023 /// Diagnose why the specified class does not have a trivial special member of 6024 /// the given kind. 6025 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6026 QualType Ty = Context.getRecordType(RD); 6027 6028 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6029 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6030 TSK_CompleteObject, /*Diagnose*/true); 6031 } 6032 6033 /// Determine whether a defaulted or deleted special member function is trivial, 6034 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6035 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6036 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6037 bool Diagnose) { 6038 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6039 6040 CXXRecordDecl *RD = MD->getParent(); 6041 6042 bool ConstArg = false; 6043 6044 // C++11 [class.copy]p12, p25: [DR1593] 6045 // A [special member] is trivial if [...] its parameter-type-list is 6046 // equivalent to the parameter-type-list of an implicit declaration [...] 6047 switch (CSM) { 6048 case CXXDefaultConstructor: 6049 case CXXDestructor: 6050 // Trivial default constructors and destructors cannot have parameters. 6051 break; 6052 6053 case CXXCopyConstructor: 6054 case CXXCopyAssignment: { 6055 // Trivial copy operations always have const, non-volatile parameter types. 6056 ConstArg = true; 6057 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6058 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6059 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6060 if (Diagnose) 6061 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6062 << Param0->getSourceRange() << Param0->getType() 6063 << Context.getLValueReferenceType( 6064 Context.getRecordType(RD).withConst()); 6065 return false; 6066 } 6067 break; 6068 } 6069 6070 case CXXMoveConstructor: 6071 case CXXMoveAssignment: { 6072 // Trivial move operations always have non-cv-qualified parameters. 6073 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6074 const RValueReferenceType *RT = 6075 Param0->getType()->getAs<RValueReferenceType>(); 6076 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6077 if (Diagnose) 6078 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6079 << Param0->getSourceRange() << Param0->getType() 6080 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6081 return false; 6082 } 6083 break; 6084 } 6085 6086 case CXXInvalid: 6087 llvm_unreachable("not a special member"); 6088 } 6089 6090 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6091 if (Diagnose) 6092 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6093 diag::note_nontrivial_default_arg) 6094 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6095 return false; 6096 } 6097 if (MD->isVariadic()) { 6098 if (Diagnose) 6099 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6100 return false; 6101 } 6102 6103 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6104 // A copy/move [constructor or assignment operator] is trivial if 6105 // -- the [member] selected to copy/move each direct base class subobject 6106 // is trivial 6107 // 6108 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6109 // A [default constructor or destructor] is trivial if 6110 // -- all the direct base classes have trivial [default constructors or 6111 // destructors] 6112 for (const auto &BI : RD->bases()) 6113 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6114 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6115 return false; 6116 6117 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6118 // A copy/move [constructor or assignment operator] for a class X is 6119 // trivial if 6120 // -- for each non-static data member of X that is of class type (or array 6121 // thereof), the constructor selected to copy/move that member is 6122 // trivial 6123 // 6124 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6125 // A [default constructor or destructor] is trivial if 6126 // -- for all of the non-static data members of its class that are of class 6127 // type (or array thereof), each such class has a trivial [default 6128 // constructor or destructor] 6129 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6130 return false; 6131 6132 // C++11 [class.dtor]p5: 6133 // A destructor is trivial if [...] 6134 // -- the destructor is not virtual 6135 if (CSM == CXXDestructor && MD->isVirtual()) { 6136 if (Diagnose) 6137 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6138 return false; 6139 } 6140 6141 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6142 // A [special member] for class X is trivial if [...] 6143 // -- class X has no virtual functions and no virtual base classes 6144 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6145 if (!Diagnose) 6146 return false; 6147 6148 if (RD->getNumVBases()) { 6149 // Check for virtual bases. We already know that the corresponding 6150 // member in all bases is trivial, so vbases must all be direct. 6151 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6152 assert(BS.isVirtual()); 6153 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6154 return false; 6155 } 6156 6157 // Must have a virtual method. 6158 for (const auto *MI : RD->methods()) { 6159 if (MI->isVirtual()) { 6160 SourceLocation MLoc = MI->getLocStart(); 6161 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6162 return false; 6163 } 6164 } 6165 6166 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6167 } 6168 6169 // Looks like it's trivial! 6170 return true; 6171 } 6172 6173 /// \brief Data used with FindHiddenVirtualMethod 6174 namespace { 6175 struct FindHiddenVirtualMethodData { 6176 Sema *S; 6177 CXXMethodDecl *Method; 6178 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6179 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6180 }; 6181 } 6182 6183 /// \brief Check whether any most overriden method from MD in Methods 6184 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 6185 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6186 if (MD->size_overridden_methods() == 0) 6187 return Methods.count(MD->getCanonicalDecl()); 6188 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6189 E = MD->end_overridden_methods(); 6190 I != E; ++I) 6191 if (CheckMostOverridenMethods(*I, Methods)) 6192 return true; 6193 return false; 6194 } 6195 6196 /// \brief Member lookup function that determines whether a given C++ 6197 /// method overloads virtual methods in a base class without overriding any, 6198 /// to be used with CXXRecordDecl::lookupInBases(). 6199 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 6200 CXXBasePath &Path, 6201 void *UserData) { 6202 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6203 6204 FindHiddenVirtualMethodData &Data 6205 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 6206 6207 DeclarationName Name = Data.Method->getDeclName(); 6208 assert(Name.getNameKind() == DeclarationName::Identifier); 6209 6210 bool foundSameNameMethod = false; 6211 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6212 for (Path.Decls = BaseRecord->lookup(Name); 6213 !Path.Decls.empty(); 6214 Path.Decls = Path.Decls.slice(1)) { 6215 NamedDecl *D = Path.Decls.front(); 6216 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6217 MD = MD->getCanonicalDecl(); 6218 foundSameNameMethod = true; 6219 // Interested only in hidden virtual methods. 6220 if (!MD->isVirtual()) 6221 continue; 6222 // If the method we are checking overrides a method from its base 6223 // don't warn about the other overloaded methods. Clang deviates from GCC 6224 // by only diagnosing overloads of inherited virtual functions that do not 6225 // override any other virtual functions in the base. GCC's 6226 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6227 // function from a base class. These cases may be better served by a 6228 // warning (not specific to virtual functions) on call sites when the call 6229 // would select a different function from the base class, were it visible. 6230 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6231 if (!Data.S->IsOverload(Data.Method, MD, false)) 6232 return true; 6233 // Collect the overload only if its hidden. 6234 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 6235 overloadedMethods.push_back(MD); 6236 } 6237 } 6238 6239 if (foundSameNameMethod) 6240 Data.OverloadedMethods.append(overloadedMethods.begin(), 6241 overloadedMethods.end()); 6242 return foundSameNameMethod; 6243 } 6244 6245 /// \brief Add the most overriden methods from MD to Methods 6246 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6247 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6248 if (MD->size_overridden_methods() == 0) 6249 Methods.insert(MD->getCanonicalDecl()); 6250 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6251 E = MD->end_overridden_methods(); 6252 I != E; ++I) 6253 AddMostOverridenMethods(*I, Methods); 6254 } 6255 6256 /// \brief Check if a method overloads virtual methods in a base class without 6257 /// overriding any. 6258 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6259 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6260 if (!MD->getDeclName().isIdentifier()) 6261 return; 6262 6263 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6264 /*bool RecordPaths=*/false, 6265 /*bool DetectVirtual=*/false); 6266 FindHiddenVirtualMethodData Data; 6267 Data.Method = MD; 6268 Data.S = this; 6269 6270 // Keep the base methods that were overriden or introduced in the subclass 6271 // by 'using' in a set. A base method not in this set is hidden. 6272 CXXRecordDecl *DC = MD->getParent(); 6273 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6274 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6275 NamedDecl *ND = *I; 6276 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6277 ND = shad->getTargetDecl(); 6278 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6279 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6280 } 6281 6282 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6283 OverloadedMethods = Data.OverloadedMethods; 6284 } 6285 6286 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6287 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6288 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6289 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6290 PartialDiagnostic PD = PDiag( 6291 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6292 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6293 Diag(overloadedMD->getLocation(), PD); 6294 } 6295 } 6296 6297 /// \brief Diagnose methods which overload virtual methods in a base class 6298 /// without overriding any. 6299 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6300 if (MD->isInvalidDecl()) 6301 return; 6302 6303 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6304 return; 6305 6306 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6307 FindHiddenVirtualMethods(MD, OverloadedMethods); 6308 if (!OverloadedMethods.empty()) { 6309 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6310 << MD << (OverloadedMethods.size() > 1); 6311 6312 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6313 } 6314 } 6315 6316 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6317 Decl *TagDecl, 6318 SourceLocation LBrac, 6319 SourceLocation RBrac, 6320 AttributeList *AttrList) { 6321 if (!TagDecl) 6322 return; 6323 6324 AdjustDeclIfTemplate(TagDecl); 6325 6326 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6327 if (l->getKind() != AttributeList::AT_Visibility) 6328 continue; 6329 l->setInvalid(); 6330 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6331 l->getName(); 6332 } 6333 6334 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6335 // strict aliasing violation! 6336 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6337 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6338 6339 CheckCompletedCXXClass( 6340 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6341 } 6342 6343 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6344 /// special functions, such as the default constructor, copy 6345 /// constructor, or destructor, to the given C++ class (C++ 6346 /// [special]p1). This routine can only be executed just before the 6347 /// definition of the class is complete. 6348 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6349 if (!ClassDecl->hasUserDeclaredConstructor()) 6350 ++ASTContext::NumImplicitDefaultConstructors; 6351 6352 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6353 ++ASTContext::NumImplicitCopyConstructors; 6354 6355 // If the properties or semantics of the copy constructor couldn't be 6356 // determined while the class was being declared, force a declaration 6357 // of it now. 6358 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6359 DeclareImplicitCopyConstructor(ClassDecl); 6360 } 6361 6362 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6363 ++ASTContext::NumImplicitMoveConstructors; 6364 6365 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6366 DeclareImplicitMoveConstructor(ClassDecl); 6367 } 6368 6369 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6370 ++ASTContext::NumImplicitCopyAssignmentOperators; 6371 6372 // If we have a dynamic class, then the copy assignment operator may be 6373 // virtual, so we have to declare it immediately. This ensures that, e.g., 6374 // it shows up in the right place in the vtable and that we diagnose 6375 // problems with the implicit exception specification. 6376 if (ClassDecl->isDynamicClass() || 6377 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6378 DeclareImplicitCopyAssignment(ClassDecl); 6379 } 6380 6381 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6382 ++ASTContext::NumImplicitMoveAssignmentOperators; 6383 6384 // Likewise for the move assignment operator. 6385 if (ClassDecl->isDynamicClass() || 6386 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6387 DeclareImplicitMoveAssignment(ClassDecl); 6388 } 6389 6390 if (!ClassDecl->hasUserDeclaredDestructor()) { 6391 ++ASTContext::NumImplicitDestructors; 6392 6393 // If we have a dynamic class, then the destructor may be virtual, so we 6394 // have to declare the destructor immediately. This ensures that, e.g., it 6395 // shows up in the right place in the vtable and that we diagnose problems 6396 // with the implicit exception specification. 6397 if (ClassDecl->isDynamicClass() || 6398 ClassDecl->needsOverloadResolutionForDestructor()) 6399 DeclareImplicitDestructor(ClassDecl); 6400 } 6401 } 6402 6403 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6404 if (!D) 6405 return 0; 6406 6407 // The order of template parameters is not important here. All names 6408 // get added to the same scope. 6409 SmallVector<TemplateParameterList *, 4> ParameterLists; 6410 6411 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6412 D = TD->getTemplatedDecl(); 6413 6414 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6415 ParameterLists.push_back(PSD->getTemplateParameters()); 6416 6417 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6418 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6419 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6420 6421 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6422 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6423 ParameterLists.push_back(FTD->getTemplateParameters()); 6424 } 6425 } 6426 6427 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6428 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6429 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6430 6431 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6432 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6433 ParameterLists.push_back(CTD->getTemplateParameters()); 6434 } 6435 } 6436 6437 unsigned Count = 0; 6438 for (TemplateParameterList *Params : ParameterLists) { 6439 if (Params->size() > 0) 6440 // Ignore explicit specializations; they don't contribute to the template 6441 // depth. 6442 ++Count; 6443 for (NamedDecl *Param : *Params) { 6444 if (Param->getDeclName()) { 6445 S->AddDecl(Param); 6446 IdResolver.AddDecl(Param); 6447 } 6448 } 6449 } 6450 6451 return Count; 6452 } 6453 6454 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6455 if (!RecordD) return; 6456 AdjustDeclIfTemplate(RecordD); 6457 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6458 PushDeclContext(S, Record); 6459 } 6460 6461 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6462 if (!RecordD) return; 6463 PopDeclContext(); 6464 } 6465 6466 /// This is used to implement the constant expression evaluation part of the 6467 /// attribute enable_if extension. There is nothing in standard C++ which would 6468 /// require reentering parameters. 6469 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6470 if (!Param) 6471 return; 6472 6473 S->AddDecl(Param); 6474 if (Param->getDeclName()) 6475 IdResolver.AddDecl(Param); 6476 } 6477 6478 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6479 /// parsing a top-level (non-nested) C++ class, and we are now 6480 /// parsing those parts of the given Method declaration that could 6481 /// not be parsed earlier (C++ [class.mem]p2), such as default 6482 /// arguments. This action should enter the scope of the given 6483 /// Method declaration as if we had just parsed the qualified method 6484 /// name. However, it should not bring the parameters into scope; 6485 /// that will be performed by ActOnDelayedCXXMethodParameter. 6486 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6487 } 6488 6489 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6490 /// C++ method declaration. We're (re-)introducing the given 6491 /// function parameter into scope for use in parsing later parts of 6492 /// the method declaration. For example, we could see an 6493 /// ActOnParamDefaultArgument event for this parameter. 6494 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6495 if (!ParamD) 6496 return; 6497 6498 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6499 6500 // If this parameter has an unparsed default argument, clear it out 6501 // to make way for the parsed default argument. 6502 if (Param->hasUnparsedDefaultArg()) 6503 Param->setDefaultArg(nullptr); 6504 6505 S->AddDecl(Param); 6506 if (Param->getDeclName()) 6507 IdResolver.AddDecl(Param); 6508 } 6509 6510 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6511 /// processing the delayed method declaration for Method. The method 6512 /// declaration is now considered finished. There may be a separate 6513 /// ActOnStartOfFunctionDef action later (not necessarily 6514 /// immediately!) for this method, if it was also defined inside the 6515 /// class body. 6516 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6517 if (!MethodD) 6518 return; 6519 6520 AdjustDeclIfTemplate(MethodD); 6521 6522 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6523 6524 // Now that we have our default arguments, check the constructor 6525 // again. It could produce additional diagnostics or affect whether 6526 // the class has implicitly-declared destructors, among other 6527 // things. 6528 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6529 CheckConstructor(Constructor); 6530 6531 // Check the default arguments, which we may have added. 6532 if (!Method->isInvalidDecl()) 6533 CheckCXXDefaultArguments(Method); 6534 } 6535 6536 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6537 /// the well-formedness of the constructor declarator @p D with type @p 6538 /// R. If there are any errors in the declarator, this routine will 6539 /// emit diagnostics and set the invalid bit to true. In any case, the type 6540 /// will be updated to reflect a well-formed type for the constructor and 6541 /// returned. 6542 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6543 StorageClass &SC) { 6544 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6545 6546 // C++ [class.ctor]p3: 6547 // A constructor shall not be virtual (10.3) or static (9.4). A 6548 // constructor can be invoked for a const, volatile or const 6549 // volatile object. A constructor shall not be declared const, 6550 // volatile, or const volatile (9.3.2). 6551 if (isVirtual) { 6552 if (!D.isInvalidType()) 6553 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6554 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6555 << SourceRange(D.getIdentifierLoc()); 6556 D.setInvalidType(); 6557 } 6558 if (SC == SC_Static) { 6559 if (!D.isInvalidType()) 6560 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6561 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6562 << SourceRange(D.getIdentifierLoc()); 6563 D.setInvalidType(); 6564 SC = SC_None; 6565 } 6566 6567 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6568 diagnoseIgnoredQualifiers( 6569 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6570 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6571 D.getDeclSpec().getRestrictSpecLoc(), 6572 D.getDeclSpec().getAtomicSpecLoc()); 6573 D.setInvalidType(); 6574 } 6575 6576 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6577 if (FTI.TypeQuals != 0) { 6578 if (FTI.TypeQuals & Qualifiers::Const) 6579 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6580 << "const" << SourceRange(D.getIdentifierLoc()); 6581 if (FTI.TypeQuals & Qualifiers::Volatile) 6582 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6583 << "volatile" << SourceRange(D.getIdentifierLoc()); 6584 if (FTI.TypeQuals & Qualifiers::Restrict) 6585 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6586 << "restrict" << SourceRange(D.getIdentifierLoc()); 6587 D.setInvalidType(); 6588 } 6589 6590 // C++0x [class.ctor]p4: 6591 // A constructor shall not be declared with a ref-qualifier. 6592 if (FTI.hasRefQualifier()) { 6593 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6594 << FTI.RefQualifierIsLValueRef 6595 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6596 D.setInvalidType(); 6597 } 6598 6599 // Rebuild the function type "R" without any type qualifiers (in 6600 // case any of the errors above fired) and with "void" as the 6601 // return type, since constructors don't have return types. 6602 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6603 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6604 return R; 6605 6606 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6607 EPI.TypeQuals = 0; 6608 EPI.RefQualifier = RQ_None; 6609 6610 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6611 } 6612 6613 /// CheckConstructor - Checks a fully-formed constructor for 6614 /// well-formedness, issuing any diagnostics required. Returns true if 6615 /// the constructor declarator is invalid. 6616 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6617 CXXRecordDecl *ClassDecl 6618 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6619 if (!ClassDecl) 6620 return Constructor->setInvalidDecl(); 6621 6622 // C++ [class.copy]p3: 6623 // A declaration of a constructor for a class X is ill-formed if 6624 // its first parameter is of type (optionally cv-qualified) X and 6625 // either there are no other parameters or else all other 6626 // parameters have default arguments. 6627 if (!Constructor->isInvalidDecl() && 6628 ((Constructor->getNumParams() == 1) || 6629 (Constructor->getNumParams() > 1 && 6630 Constructor->getParamDecl(1)->hasDefaultArg())) && 6631 Constructor->getTemplateSpecializationKind() 6632 != TSK_ImplicitInstantiation) { 6633 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6634 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6635 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6636 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6637 const char *ConstRef 6638 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6639 : " const &"; 6640 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6641 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6642 6643 // FIXME: Rather that making the constructor invalid, we should endeavor 6644 // to fix the type. 6645 Constructor->setInvalidDecl(); 6646 } 6647 } 6648 } 6649 6650 /// CheckDestructor - Checks a fully-formed destructor definition for 6651 /// well-formedness, issuing any diagnostics required. Returns true 6652 /// on error. 6653 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6654 CXXRecordDecl *RD = Destructor->getParent(); 6655 6656 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6657 SourceLocation Loc; 6658 6659 if (!Destructor->isImplicit()) 6660 Loc = Destructor->getLocation(); 6661 else 6662 Loc = RD->getLocation(); 6663 6664 // If we have a virtual destructor, look up the deallocation function 6665 FunctionDecl *OperatorDelete = nullptr; 6666 DeclarationName Name = 6667 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6668 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6669 return true; 6670 // If there's no class-specific operator delete, look up the global 6671 // non-array delete. 6672 if (!OperatorDelete) 6673 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6674 6675 MarkFunctionReferenced(Loc, OperatorDelete); 6676 6677 Destructor->setOperatorDelete(OperatorDelete); 6678 } 6679 6680 return false; 6681 } 6682 6683 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6684 /// the well-formednes of the destructor declarator @p D with type @p 6685 /// R. If there are any errors in the declarator, this routine will 6686 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6687 /// will be updated to reflect a well-formed type for the destructor and 6688 /// returned. 6689 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6690 StorageClass& SC) { 6691 // C++ [class.dtor]p1: 6692 // [...] A typedef-name that names a class is a class-name 6693 // (7.1.3); however, a typedef-name that names a class shall not 6694 // be used as the identifier in the declarator for a destructor 6695 // declaration. 6696 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6697 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6698 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6699 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6700 else if (const TemplateSpecializationType *TST = 6701 DeclaratorType->getAs<TemplateSpecializationType>()) 6702 if (TST->isTypeAlias()) 6703 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6704 << DeclaratorType << 1; 6705 6706 // C++ [class.dtor]p2: 6707 // A destructor is used to destroy objects of its class type. A 6708 // destructor takes no parameters, and no return type can be 6709 // specified for it (not even void). The address of a destructor 6710 // shall not be taken. A destructor shall not be static. A 6711 // destructor can be invoked for a const, volatile or const 6712 // volatile object. A destructor shall not be declared const, 6713 // volatile or const volatile (9.3.2). 6714 if (SC == SC_Static) { 6715 if (!D.isInvalidType()) 6716 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6717 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6718 << SourceRange(D.getIdentifierLoc()) 6719 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6720 6721 SC = SC_None; 6722 } 6723 if (!D.isInvalidType()) { 6724 // Destructors don't have return types, but the parser will 6725 // happily parse something like: 6726 // 6727 // class X { 6728 // float ~X(); 6729 // }; 6730 // 6731 // The return type will be eliminated later. 6732 if (D.getDeclSpec().hasTypeSpecifier()) 6733 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6734 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6735 << SourceRange(D.getIdentifierLoc()); 6736 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6737 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6738 SourceLocation(), 6739 D.getDeclSpec().getConstSpecLoc(), 6740 D.getDeclSpec().getVolatileSpecLoc(), 6741 D.getDeclSpec().getRestrictSpecLoc(), 6742 D.getDeclSpec().getAtomicSpecLoc()); 6743 D.setInvalidType(); 6744 } 6745 } 6746 6747 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6748 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6749 if (FTI.TypeQuals & Qualifiers::Const) 6750 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6751 << "const" << SourceRange(D.getIdentifierLoc()); 6752 if (FTI.TypeQuals & Qualifiers::Volatile) 6753 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6754 << "volatile" << SourceRange(D.getIdentifierLoc()); 6755 if (FTI.TypeQuals & Qualifiers::Restrict) 6756 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6757 << "restrict" << SourceRange(D.getIdentifierLoc()); 6758 D.setInvalidType(); 6759 } 6760 6761 // C++0x [class.dtor]p2: 6762 // A destructor shall not be declared with a ref-qualifier. 6763 if (FTI.hasRefQualifier()) { 6764 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6765 << FTI.RefQualifierIsLValueRef 6766 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6767 D.setInvalidType(); 6768 } 6769 6770 // Make sure we don't have any parameters. 6771 if (FTIHasNonVoidParameters(FTI)) { 6772 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6773 6774 // Delete the parameters. 6775 FTI.freeParams(); 6776 D.setInvalidType(); 6777 } 6778 6779 // Make sure the destructor isn't variadic. 6780 if (FTI.isVariadic) { 6781 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6782 D.setInvalidType(); 6783 } 6784 6785 // Rebuild the function type "R" without any type qualifiers or 6786 // parameters (in case any of the errors above fired) and with 6787 // "void" as the return type, since destructors don't have return 6788 // types. 6789 if (!D.isInvalidType()) 6790 return R; 6791 6792 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6793 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6794 EPI.Variadic = false; 6795 EPI.TypeQuals = 0; 6796 EPI.RefQualifier = RQ_None; 6797 return Context.getFunctionType(Context.VoidTy, None, EPI); 6798 } 6799 6800 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6801 /// well-formednes of the conversion function declarator @p D with 6802 /// type @p R. If there are any errors in the declarator, this routine 6803 /// will emit diagnostics and return true. Otherwise, it will return 6804 /// false. Either way, the type @p R will be updated to reflect a 6805 /// well-formed type for the conversion operator. 6806 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6807 StorageClass& SC) { 6808 // C++ [class.conv.fct]p1: 6809 // Neither parameter types nor return type can be specified. The 6810 // type of a conversion function (8.3.5) is "function taking no 6811 // parameter returning conversion-type-id." 6812 if (SC == SC_Static) { 6813 if (!D.isInvalidType()) 6814 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6815 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6816 << D.getName().getSourceRange(); 6817 D.setInvalidType(); 6818 SC = SC_None; 6819 } 6820 6821 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6822 6823 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6824 // Conversion functions don't have return types, but the parser will 6825 // happily parse something like: 6826 // 6827 // class X { 6828 // float operator bool(); 6829 // }; 6830 // 6831 // The return type will be changed later anyway. 6832 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6833 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6834 << SourceRange(D.getIdentifierLoc()); 6835 D.setInvalidType(); 6836 } 6837 6838 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6839 6840 // Make sure we don't have any parameters. 6841 if (Proto->getNumParams() > 0) { 6842 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6843 6844 // Delete the parameters. 6845 D.getFunctionTypeInfo().freeParams(); 6846 D.setInvalidType(); 6847 } else if (Proto->isVariadic()) { 6848 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6849 D.setInvalidType(); 6850 } 6851 6852 // Diagnose "&operator bool()" and other such nonsense. This 6853 // is actually a gcc extension which we don't support. 6854 if (Proto->getReturnType() != ConvType) { 6855 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6856 << Proto->getReturnType(); 6857 D.setInvalidType(); 6858 ConvType = Proto->getReturnType(); 6859 } 6860 6861 // C++ [class.conv.fct]p4: 6862 // The conversion-type-id shall not represent a function type nor 6863 // an array type. 6864 if (ConvType->isArrayType()) { 6865 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6866 ConvType = Context.getPointerType(ConvType); 6867 D.setInvalidType(); 6868 } else if (ConvType->isFunctionType()) { 6869 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6870 ConvType = Context.getPointerType(ConvType); 6871 D.setInvalidType(); 6872 } 6873 6874 // Rebuild the function type "R" without any parameters (in case any 6875 // of the errors above fired) and with the conversion type as the 6876 // return type. 6877 if (D.isInvalidType()) 6878 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6879 6880 // C++0x explicit conversion operators. 6881 if (D.getDeclSpec().isExplicitSpecified()) 6882 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6883 getLangOpts().CPlusPlus11 ? 6884 diag::warn_cxx98_compat_explicit_conversion_functions : 6885 diag::ext_explicit_conversion_functions) 6886 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6887 } 6888 6889 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6890 /// the declaration of the given C++ conversion function. This routine 6891 /// is responsible for recording the conversion function in the C++ 6892 /// class, if possible. 6893 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6894 assert(Conversion && "Expected to receive a conversion function declaration"); 6895 6896 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6897 6898 // Make sure we aren't redeclaring the conversion function. 6899 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6900 6901 // C++ [class.conv.fct]p1: 6902 // [...] A conversion function is never used to convert a 6903 // (possibly cv-qualified) object to the (possibly cv-qualified) 6904 // same object type (or a reference to it), to a (possibly 6905 // cv-qualified) base class of that type (or a reference to it), 6906 // or to (possibly cv-qualified) void. 6907 // FIXME: Suppress this warning if the conversion function ends up being a 6908 // virtual function that overrides a virtual function in a base class. 6909 QualType ClassType 6910 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6911 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6912 ConvType = ConvTypeRef->getPointeeType(); 6913 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6914 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6915 /* Suppress diagnostics for instantiations. */; 6916 else if (ConvType->isRecordType()) { 6917 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6918 if (ConvType == ClassType) 6919 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6920 << ClassType; 6921 else if (IsDerivedFrom(ClassType, ConvType)) 6922 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6923 << ClassType << ConvType; 6924 } else if (ConvType->isVoidType()) { 6925 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6926 << ClassType << ConvType; 6927 } 6928 6929 if (FunctionTemplateDecl *ConversionTemplate 6930 = Conversion->getDescribedFunctionTemplate()) 6931 return ConversionTemplate; 6932 6933 return Conversion; 6934 } 6935 6936 //===----------------------------------------------------------------------===// 6937 // Namespace Handling 6938 //===----------------------------------------------------------------------===// 6939 6940 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6941 /// reopened. 6942 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6943 SourceLocation Loc, 6944 IdentifierInfo *II, bool *IsInline, 6945 NamespaceDecl *PrevNS) { 6946 assert(*IsInline != PrevNS->isInline()); 6947 6948 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6949 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6950 // inline namespaces, with the intention of bringing names into namespace std. 6951 // 6952 // We support this just well enough to get that case working; this is not 6953 // sufficient to support reopening namespaces as inline in general. 6954 if (*IsInline && II && II->getName().startswith("__atomic") && 6955 S.getSourceManager().isInSystemHeader(Loc)) { 6956 // Mark all prior declarations of the namespace as inline. 6957 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6958 NS = NS->getPreviousDecl()) 6959 NS->setInline(*IsInline); 6960 // Patch up the lookup table for the containing namespace. This isn't really 6961 // correct, but it's good enough for this particular case. 6962 for (auto *I : PrevNS->decls()) 6963 if (auto *ND = dyn_cast<NamedDecl>(I)) 6964 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6965 return; 6966 } 6967 6968 if (PrevNS->isInline()) 6969 // The user probably just forgot the 'inline', so suggest that it 6970 // be added back. 6971 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6972 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6973 else 6974 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6975 6976 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6977 *IsInline = PrevNS->isInline(); 6978 } 6979 6980 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6981 /// definition. 6982 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6983 SourceLocation InlineLoc, 6984 SourceLocation NamespaceLoc, 6985 SourceLocation IdentLoc, 6986 IdentifierInfo *II, 6987 SourceLocation LBrace, 6988 AttributeList *AttrList) { 6989 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6990 // For anonymous namespace, take the location of the left brace. 6991 SourceLocation Loc = II ? IdentLoc : LBrace; 6992 bool IsInline = InlineLoc.isValid(); 6993 bool IsInvalid = false; 6994 bool IsStd = false; 6995 bool AddToKnown = false; 6996 Scope *DeclRegionScope = NamespcScope->getParent(); 6997 6998 NamespaceDecl *PrevNS = nullptr; 6999 if (II) { 7000 // C++ [namespace.def]p2: 7001 // The identifier in an original-namespace-definition shall not 7002 // have been previously defined in the declarative region in 7003 // which the original-namespace-definition appears. The 7004 // identifier in an original-namespace-definition is the name of 7005 // the namespace. Subsequently in that declarative region, it is 7006 // treated as an original-namespace-name. 7007 // 7008 // Since namespace names are unique in their scope, and we don't 7009 // look through using directives, just look for any ordinary names. 7010 7011 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7012 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7013 Decl::IDNS_Namespace; 7014 NamedDecl *PrevDecl = nullptr; 7015 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7016 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7017 ++I) { 7018 if ((*I)->getIdentifierNamespace() & IDNS) { 7019 PrevDecl = *I; 7020 break; 7021 } 7022 } 7023 7024 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7025 7026 if (PrevNS) { 7027 // This is an extended namespace definition. 7028 if (IsInline != PrevNS->isInline()) 7029 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7030 &IsInline, PrevNS); 7031 } else if (PrevDecl) { 7032 // This is an invalid name redefinition. 7033 Diag(Loc, diag::err_redefinition_different_kind) 7034 << II; 7035 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7036 IsInvalid = true; 7037 // Continue on to push Namespc as current DeclContext and return it. 7038 } else if (II->isStr("std") && 7039 CurContext->getRedeclContext()->isTranslationUnit()) { 7040 // This is the first "real" definition of the namespace "std", so update 7041 // our cache of the "std" namespace to point at this definition. 7042 PrevNS = getStdNamespace(); 7043 IsStd = true; 7044 AddToKnown = !IsInline; 7045 } else { 7046 // We've seen this namespace for the first time. 7047 AddToKnown = !IsInline; 7048 } 7049 } else { 7050 // Anonymous namespaces. 7051 7052 // Determine whether the parent already has an anonymous namespace. 7053 DeclContext *Parent = CurContext->getRedeclContext(); 7054 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7055 PrevNS = TU->getAnonymousNamespace(); 7056 } else { 7057 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7058 PrevNS = ND->getAnonymousNamespace(); 7059 } 7060 7061 if (PrevNS && IsInline != PrevNS->isInline()) 7062 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7063 &IsInline, PrevNS); 7064 } 7065 7066 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7067 StartLoc, Loc, II, PrevNS); 7068 if (IsInvalid) 7069 Namespc->setInvalidDecl(); 7070 7071 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7072 7073 // FIXME: Should we be merging attributes? 7074 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7075 PushNamespaceVisibilityAttr(Attr, Loc); 7076 7077 if (IsStd) 7078 StdNamespace = Namespc; 7079 if (AddToKnown) 7080 KnownNamespaces[Namespc] = false; 7081 7082 if (II) { 7083 PushOnScopeChains(Namespc, DeclRegionScope); 7084 } else { 7085 // Link the anonymous namespace into its parent. 7086 DeclContext *Parent = CurContext->getRedeclContext(); 7087 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7088 TU->setAnonymousNamespace(Namespc); 7089 } else { 7090 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7091 } 7092 7093 CurContext->addDecl(Namespc); 7094 7095 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7096 // behaves as if it were replaced by 7097 // namespace unique { /* empty body */ } 7098 // using namespace unique; 7099 // namespace unique { namespace-body } 7100 // where all occurrences of 'unique' in a translation unit are 7101 // replaced by the same identifier and this identifier differs 7102 // from all other identifiers in the entire program. 7103 7104 // We just create the namespace with an empty name and then add an 7105 // implicit using declaration, just like the standard suggests. 7106 // 7107 // CodeGen enforces the "universally unique" aspect by giving all 7108 // declarations semantically contained within an anonymous 7109 // namespace internal linkage. 7110 7111 if (!PrevNS) { 7112 UsingDirectiveDecl* UD 7113 = UsingDirectiveDecl::Create(Context, Parent, 7114 /* 'using' */ LBrace, 7115 /* 'namespace' */ SourceLocation(), 7116 /* qualifier */ NestedNameSpecifierLoc(), 7117 /* identifier */ SourceLocation(), 7118 Namespc, 7119 /* Ancestor */ Parent); 7120 UD->setImplicit(); 7121 Parent->addDecl(UD); 7122 } 7123 } 7124 7125 ActOnDocumentableDecl(Namespc); 7126 7127 // Although we could have an invalid decl (i.e. the namespace name is a 7128 // redefinition), push it as current DeclContext and try to continue parsing. 7129 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7130 // for the namespace has the declarations that showed up in that particular 7131 // namespace definition. 7132 PushDeclContext(NamespcScope, Namespc); 7133 return Namespc; 7134 } 7135 7136 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7137 /// is a namespace alias, returns the namespace it points to. 7138 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7139 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7140 return AD->getNamespace(); 7141 return dyn_cast_or_null<NamespaceDecl>(D); 7142 } 7143 7144 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7145 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7146 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7147 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7148 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7149 Namespc->setRBraceLoc(RBrace); 7150 PopDeclContext(); 7151 if (Namespc->hasAttr<VisibilityAttr>()) 7152 PopPragmaVisibility(true, RBrace); 7153 } 7154 7155 CXXRecordDecl *Sema::getStdBadAlloc() const { 7156 return cast_or_null<CXXRecordDecl>( 7157 StdBadAlloc.get(Context.getExternalSource())); 7158 } 7159 7160 NamespaceDecl *Sema::getStdNamespace() const { 7161 return cast_or_null<NamespaceDecl>( 7162 StdNamespace.get(Context.getExternalSource())); 7163 } 7164 7165 /// \brief Retrieve the special "std" namespace, which may require us to 7166 /// implicitly define the namespace. 7167 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7168 if (!StdNamespace) { 7169 // The "std" namespace has not yet been defined, so build one implicitly. 7170 StdNamespace = NamespaceDecl::Create(Context, 7171 Context.getTranslationUnitDecl(), 7172 /*Inline=*/false, 7173 SourceLocation(), SourceLocation(), 7174 &PP.getIdentifierTable().get("std"), 7175 /*PrevDecl=*/nullptr); 7176 getStdNamespace()->setImplicit(true); 7177 } 7178 7179 return getStdNamespace(); 7180 } 7181 7182 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7183 assert(getLangOpts().CPlusPlus && 7184 "Looking for std::initializer_list outside of C++."); 7185 7186 // We're looking for implicit instantiations of 7187 // template <typename E> class std::initializer_list. 7188 7189 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7190 return false; 7191 7192 ClassTemplateDecl *Template = nullptr; 7193 const TemplateArgument *Arguments = nullptr; 7194 7195 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7196 7197 ClassTemplateSpecializationDecl *Specialization = 7198 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7199 if (!Specialization) 7200 return false; 7201 7202 Template = Specialization->getSpecializedTemplate(); 7203 Arguments = Specialization->getTemplateArgs().data(); 7204 } else if (const TemplateSpecializationType *TST = 7205 Ty->getAs<TemplateSpecializationType>()) { 7206 Template = dyn_cast_or_null<ClassTemplateDecl>( 7207 TST->getTemplateName().getAsTemplateDecl()); 7208 Arguments = TST->getArgs(); 7209 } 7210 if (!Template) 7211 return false; 7212 7213 if (!StdInitializerList) { 7214 // Haven't recognized std::initializer_list yet, maybe this is it. 7215 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7216 if (TemplateClass->getIdentifier() != 7217 &PP.getIdentifierTable().get("initializer_list") || 7218 !getStdNamespace()->InEnclosingNamespaceSetOf( 7219 TemplateClass->getDeclContext())) 7220 return false; 7221 // This is a template called std::initializer_list, but is it the right 7222 // template? 7223 TemplateParameterList *Params = Template->getTemplateParameters(); 7224 if (Params->getMinRequiredArguments() != 1) 7225 return false; 7226 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7227 return false; 7228 7229 // It's the right template. 7230 StdInitializerList = Template; 7231 } 7232 7233 if (Template != StdInitializerList) 7234 return false; 7235 7236 // This is an instance of std::initializer_list. Find the argument type. 7237 if (Element) 7238 *Element = Arguments[0].getAsType(); 7239 return true; 7240 } 7241 7242 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7243 NamespaceDecl *Std = S.getStdNamespace(); 7244 if (!Std) { 7245 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7246 return nullptr; 7247 } 7248 7249 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7250 Loc, Sema::LookupOrdinaryName); 7251 if (!S.LookupQualifiedName(Result, Std)) { 7252 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7253 return nullptr; 7254 } 7255 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7256 if (!Template) { 7257 Result.suppressDiagnostics(); 7258 // We found something weird. Complain about the first thing we found. 7259 NamedDecl *Found = *Result.begin(); 7260 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7261 return nullptr; 7262 } 7263 7264 // We found some template called std::initializer_list. Now verify that it's 7265 // correct. 7266 TemplateParameterList *Params = Template->getTemplateParameters(); 7267 if (Params->getMinRequiredArguments() != 1 || 7268 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7269 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7270 return nullptr; 7271 } 7272 7273 return Template; 7274 } 7275 7276 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7277 if (!StdInitializerList) { 7278 StdInitializerList = LookupStdInitializerList(*this, Loc); 7279 if (!StdInitializerList) 7280 return QualType(); 7281 } 7282 7283 TemplateArgumentListInfo Args(Loc, Loc); 7284 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7285 Context.getTrivialTypeSourceInfo(Element, 7286 Loc))); 7287 return Context.getCanonicalType( 7288 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7289 } 7290 7291 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7292 // C++ [dcl.init.list]p2: 7293 // A constructor is an initializer-list constructor if its first parameter 7294 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7295 // std::initializer_list<E> for some type E, and either there are no other 7296 // parameters or else all other parameters have default arguments. 7297 if (Ctor->getNumParams() < 1 || 7298 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7299 return false; 7300 7301 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7302 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7303 ArgType = RT->getPointeeType().getUnqualifiedType(); 7304 7305 return isStdInitializerList(ArgType, nullptr); 7306 } 7307 7308 /// \brief Determine whether a using statement is in a context where it will be 7309 /// apply in all contexts. 7310 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7311 switch (CurContext->getDeclKind()) { 7312 case Decl::TranslationUnit: 7313 return true; 7314 case Decl::LinkageSpec: 7315 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7316 default: 7317 return false; 7318 } 7319 } 7320 7321 namespace { 7322 7323 // Callback to only accept typo corrections that are namespaces. 7324 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7325 public: 7326 bool ValidateCandidate(const TypoCorrection &candidate) override { 7327 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7328 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7329 return false; 7330 } 7331 }; 7332 7333 } 7334 7335 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7336 CXXScopeSpec &SS, 7337 SourceLocation IdentLoc, 7338 IdentifierInfo *Ident) { 7339 R.clear(); 7340 if (TypoCorrection Corrected = 7341 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7342 llvm::make_unique<NamespaceValidatorCCC>(), 7343 Sema::CTK_ErrorRecovery)) { 7344 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7345 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7346 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7347 Ident->getName().equals(CorrectedStr); 7348 S.diagnoseTypo(Corrected, 7349 S.PDiag(diag::err_using_directive_member_suggest) 7350 << Ident << DC << DroppedSpecifier << SS.getRange(), 7351 S.PDiag(diag::note_namespace_defined_here)); 7352 } else { 7353 S.diagnoseTypo(Corrected, 7354 S.PDiag(diag::err_using_directive_suggest) << Ident, 7355 S.PDiag(diag::note_namespace_defined_here)); 7356 } 7357 R.addDecl(Corrected.getCorrectionDecl()); 7358 return true; 7359 } 7360 return false; 7361 } 7362 7363 Decl *Sema::ActOnUsingDirective(Scope *S, 7364 SourceLocation UsingLoc, 7365 SourceLocation NamespcLoc, 7366 CXXScopeSpec &SS, 7367 SourceLocation IdentLoc, 7368 IdentifierInfo *NamespcName, 7369 AttributeList *AttrList) { 7370 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7371 assert(NamespcName && "Invalid NamespcName."); 7372 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7373 7374 // This can only happen along a recovery path. 7375 while (S->getFlags() & Scope::TemplateParamScope) 7376 S = S->getParent(); 7377 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7378 7379 UsingDirectiveDecl *UDir = nullptr; 7380 NestedNameSpecifier *Qualifier = nullptr; 7381 if (SS.isSet()) 7382 Qualifier = SS.getScopeRep(); 7383 7384 // Lookup namespace name. 7385 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7386 LookupParsedName(R, S, &SS); 7387 if (R.isAmbiguous()) 7388 return nullptr; 7389 7390 if (R.empty()) { 7391 R.clear(); 7392 // Allow "using namespace std;" or "using namespace ::std;" even if 7393 // "std" hasn't been defined yet, for GCC compatibility. 7394 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7395 NamespcName->isStr("std")) { 7396 Diag(IdentLoc, diag::ext_using_undefined_std); 7397 R.addDecl(getOrCreateStdNamespace()); 7398 R.resolveKind(); 7399 } 7400 // Otherwise, attempt typo correction. 7401 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7402 } 7403 7404 if (!R.empty()) { 7405 NamedDecl *Named = R.getFoundDecl(); 7406 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7407 && "expected namespace decl"); 7408 7409 // The use of a nested name specifier may trigger deprecation warnings. 7410 DiagnoseUseOfDecl(Named, IdentLoc); 7411 7412 // C++ [namespace.udir]p1: 7413 // A using-directive specifies that the names in the nominated 7414 // namespace can be used in the scope in which the 7415 // using-directive appears after the using-directive. During 7416 // unqualified name lookup (3.4.1), the names appear as if they 7417 // were declared in the nearest enclosing namespace which 7418 // contains both the using-directive and the nominated 7419 // namespace. [Note: in this context, "contains" means "contains 7420 // directly or indirectly". ] 7421 7422 // Find enclosing context containing both using-directive and 7423 // nominated namespace. 7424 NamespaceDecl *NS = getNamespaceDecl(Named); 7425 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7426 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7427 CommonAncestor = CommonAncestor->getParent(); 7428 7429 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7430 SS.getWithLocInContext(Context), 7431 IdentLoc, Named, CommonAncestor); 7432 7433 if (IsUsingDirectiveInToplevelContext(CurContext) && 7434 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7435 Diag(IdentLoc, diag::warn_using_directive_in_header); 7436 } 7437 7438 PushUsingDirective(S, UDir); 7439 } else { 7440 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7441 } 7442 7443 if (UDir) 7444 ProcessDeclAttributeList(S, UDir, AttrList); 7445 7446 return UDir; 7447 } 7448 7449 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7450 // If the scope has an associated entity and the using directive is at 7451 // namespace or translation unit scope, add the UsingDirectiveDecl into 7452 // its lookup structure so qualified name lookup can find it. 7453 DeclContext *Ctx = S->getEntity(); 7454 if (Ctx && !Ctx->isFunctionOrMethod()) 7455 Ctx->addDecl(UDir); 7456 else 7457 // Otherwise, it is at block scope. The using-directives will affect lookup 7458 // only to the end of the scope. 7459 S->PushUsingDirective(UDir); 7460 } 7461 7462 7463 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7464 AccessSpecifier AS, 7465 bool HasUsingKeyword, 7466 SourceLocation UsingLoc, 7467 CXXScopeSpec &SS, 7468 UnqualifiedId &Name, 7469 AttributeList *AttrList, 7470 bool HasTypenameKeyword, 7471 SourceLocation TypenameLoc) { 7472 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7473 7474 switch (Name.getKind()) { 7475 case UnqualifiedId::IK_ImplicitSelfParam: 7476 case UnqualifiedId::IK_Identifier: 7477 case UnqualifiedId::IK_OperatorFunctionId: 7478 case UnqualifiedId::IK_LiteralOperatorId: 7479 case UnqualifiedId::IK_ConversionFunctionId: 7480 break; 7481 7482 case UnqualifiedId::IK_ConstructorName: 7483 case UnqualifiedId::IK_ConstructorTemplateId: 7484 // C++11 inheriting constructors. 7485 Diag(Name.getLocStart(), 7486 getLangOpts().CPlusPlus11 ? 7487 diag::warn_cxx98_compat_using_decl_constructor : 7488 diag::err_using_decl_constructor) 7489 << SS.getRange(); 7490 7491 if (getLangOpts().CPlusPlus11) break; 7492 7493 return nullptr; 7494 7495 case UnqualifiedId::IK_DestructorName: 7496 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7497 << SS.getRange(); 7498 return nullptr; 7499 7500 case UnqualifiedId::IK_TemplateId: 7501 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7502 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7503 return nullptr; 7504 } 7505 7506 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7507 DeclarationName TargetName = TargetNameInfo.getName(); 7508 if (!TargetName) 7509 return nullptr; 7510 7511 // Warn about access declarations. 7512 if (!HasUsingKeyword) { 7513 Diag(Name.getLocStart(), 7514 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7515 : diag::warn_access_decl_deprecated) 7516 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7517 } 7518 7519 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7520 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7521 return nullptr; 7522 7523 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7524 TargetNameInfo, AttrList, 7525 /* IsInstantiation */ false, 7526 HasTypenameKeyword, TypenameLoc); 7527 if (UD) 7528 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7529 7530 return UD; 7531 } 7532 7533 /// \brief Determine whether a using declaration considers the given 7534 /// declarations as "equivalent", e.g., if they are redeclarations of 7535 /// the same entity or are both typedefs of the same type. 7536 static bool 7537 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7538 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7539 return true; 7540 7541 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7542 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7543 return Context.hasSameType(TD1->getUnderlyingType(), 7544 TD2->getUnderlyingType()); 7545 7546 return false; 7547 } 7548 7549 7550 /// Determines whether to create a using shadow decl for a particular 7551 /// decl, given the set of decls existing prior to this using lookup. 7552 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7553 const LookupResult &Previous, 7554 UsingShadowDecl *&PrevShadow) { 7555 // Diagnose finding a decl which is not from a base class of the 7556 // current class. We do this now because there are cases where this 7557 // function will silently decide not to build a shadow decl, which 7558 // will pre-empt further diagnostics. 7559 // 7560 // We don't need to do this in C++0x because we do the check once on 7561 // the qualifier. 7562 // 7563 // FIXME: diagnose the following if we care enough: 7564 // struct A { int foo; }; 7565 // struct B : A { using A::foo; }; 7566 // template <class T> struct C : A {}; 7567 // template <class T> struct D : C<T> { using B::foo; } // <--- 7568 // This is invalid (during instantiation) in C++03 because B::foo 7569 // resolves to the using decl in B, which is not a base class of D<T>. 7570 // We can't diagnose it immediately because C<T> is an unknown 7571 // specialization. The UsingShadowDecl in D<T> then points directly 7572 // to A::foo, which will look well-formed when we instantiate. 7573 // The right solution is to not collapse the shadow-decl chain. 7574 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7575 DeclContext *OrigDC = Orig->getDeclContext(); 7576 7577 // Handle enums and anonymous structs. 7578 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7579 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7580 while (OrigRec->isAnonymousStructOrUnion()) 7581 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7582 7583 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7584 if (OrigDC == CurContext) { 7585 Diag(Using->getLocation(), 7586 diag::err_using_decl_nested_name_specifier_is_current_class) 7587 << Using->getQualifierLoc().getSourceRange(); 7588 Diag(Orig->getLocation(), diag::note_using_decl_target); 7589 return true; 7590 } 7591 7592 Diag(Using->getQualifierLoc().getBeginLoc(), 7593 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7594 << Using->getQualifier() 7595 << cast<CXXRecordDecl>(CurContext) 7596 << Using->getQualifierLoc().getSourceRange(); 7597 Diag(Orig->getLocation(), diag::note_using_decl_target); 7598 return true; 7599 } 7600 } 7601 7602 if (Previous.empty()) return false; 7603 7604 NamedDecl *Target = Orig; 7605 if (isa<UsingShadowDecl>(Target)) 7606 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7607 7608 // If the target happens to be one of the previous declarations, we 7609 // don't have a conflict. 7610 // 7611 // FIXME: but we might be increasing its access, in which case we 7612 // should redeclare it. 7613 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7614 bool FoundEquivalentDecl = false; 7615 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7616 I != E; ++I) { 7617 NamedDecl *D = (*I)->getUnderlyingDecl(); 7618 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7619 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7620 PrevShadow = Shadow; 7621 FoundEquivalentDecl = true; 7622 } 7623 7624 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7625 } 7626 7627 if (FoundEquivalentDecl) 7628 return false; 7629 7630 if (FunctionDecl *FD = Target->getAsFunction()) { 7631 NamedDecl *OldDecl = nullptr; 7632 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7633 /*IsForUsingDecl*/ true)) { 7634 case Ovl_Overload: 7635 return false; 7636 7637 case Ovl_NonFunction: 7638 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7639 break; 7640 7641 // We found a decl with the exact signature. 7642 case Ovl_Match: 7643 // If we're in a record, we want to hide the target, so we 7644 // return true (without a diagnostic) to tell the caller not to 7645 // build a shadow decl. 7646 if (CurContext->isRecord()) 7647 return true; 7648 7649 // If we're not in a record, this is an error. 7650 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7651 break; 7652 } 7653 7654 Diag(Target->getLocation(), diag::note_using_decl_target); 7655 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7656 return true; 7657 } 7658 7659 // Target is not a function. 7660 7661 if (isa<TagDecl>(Target)) { 7662 // No conflict between a tag and a non-tag. 7663 if (!Tag) return false; 7664 7665 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7666 Diag(Target->getLocation(), diag::note_using_decl_target); 7667 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7668 return true; 7669 } 7670 7671 // No conflict between a tag and a non-tag. 7672 if (!NonTag) return false; 7673 7674 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7675 Diag(Target->getLocation(), diag::note_using_decl_target); 7676 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7677 return true; 7678 } 7679 7680 /// Builds a shadow declaration corresponding to a 'using' declaration. 7681 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7682 UsingDecl *UD, 7683 NamedDecl *Orig, 7684 UsingShadowDecl *PrevDecl) { 7685 7686 // If we resolved to another shadow declaration, just coalesce them. 7687 NamedDecl *Target = Orig; 7688 if (isa<UsingShadowDecl>(Target)) { 7689 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7690 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7691 } 7692 7693 UsingShadowDecl *Shadow 7694 = UsingShadowDecl::Create(Context, CurContext, 7695 UD->getLocation(), UD, Target); 7696 UD->addShadowDecl(Shadow); 7697 7698 Shadow->setAccess(UD->getAccess()); 7699 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7700 Shadow->setInvalidDecl(); 7701 7702 Shadow->setPreviousDecl(PrevDecl); 7703 7704 if (S) 7705 PushOnScopeChains(Shadow, S); 7706 else 7707 CurContext->addDecl(Shadow); 7708 7709 7710 return Shadow; 7711 } 7712 7713 /// Hides a using shadow declaration. This is required by the current 7714 /// using-decl implementation when a resolvable using declaration in a 7715 /// class is followed by a declaration which would hide or override 7716 /// one or more of the using decl's targets; for example: 7717 /// 7718 /// struct Base { void foo(int); }; 7719 /// struct Derived : Base { 7720 /// using Base::foo; 7721 /// void foo(int); 7722 /// }; 7723 /// 7724 /// The governing language is C++03 [namespace.udecl]p12: 7725 /// 7726 /// When a using-declaration brings names from a base class into a 7727 /// derived class scope, member functions in the derived class 7728 /// override and/or hide member functions with the same name and 7729 /// parameter types in a base class (rather than conflicting). 7730 /// 7731 /// There are two ways to implement this: 7732 /// (1) optimistically create shadow decls when they're not hidden 7733 /// by existing declarations, or 7734 /// (2) don't create any shadow decls (or at least don't make them 7735 /// visible) until we've fully parsed/instantiated the class. 7736 /// The problem with (1) is that we might have to retroactively remove 7737 /// a shadow decl, which requires several O(n) operations because the 7738 /// decl structures are (very reasonably) not designed for removal. 7739 /// (2) avoids this but is very fiddly and phase-dependent. 7740 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7741 if (Shadow->getDeclName().getNameKind() == 7742 DeclarationName::CXXConversionFunctionName) 7743 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7744 7745 // Remove it from the DeclContext... 7746 Shadow->getDeclContext()->removeDecl(Shadow); 7747 7748 // ...and the scope, if applicable... 7749 if (S) { 7750 S->RemoveDecl(Shadow); 7751 IdResolver.RemoveDecl(Shadow); 7752 } 7753 7754 // ...and the using decl. 7755 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7756 7757 // TODO: complain somehow if Shadow was used. It shouldn't 7758 // be possible for this to happen, because...? 7759 } 7760 7761 /// Find the base specifier for a base class with the given type. 7762 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7763 QualType DesiredBase, 7764 bool &AnyDependentBases) { 7765 // Check whether the named type is a direct base class. 7766 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7767 for (auto &Base : Derived->bases()) { 7768 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7769 if (CanonicalDesiredBase == BaseType) 7770 return &Base; 7771 if (BaseType->isDependentType()) 7772 AnyDependentBases = true; 7773 } 7774 return nullptr; 7775 } 7776 7777 namespace { 7778 class UsingValidatorCCC : public CorrectionCandidateCallback { 7779 public: 7780 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7781 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7782 : HasTypenameKeyword(HasTypenameKeyword), 7783 IsInstantiation(IsInstantiation), OldNNS(NNS), 7784 RequireMemberOf(RequireMemberOf) {} 7785 7786 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7787 NamedDecl *ND = Candidate.getCorrectionDecl(); 7788 7789 // Keywords are not valid here. 7790 if (!ND || isa<NamespaceDecl>(ND)) 7791 return false; 7792 7793 // Completely unqualified names are invalid for a 'using' declaration. 7794 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7795 return false; 7796 7797 if (RequireMemberOf) { 7798 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7799 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7800 // No-one ever wants a using-declaration to name an injected-class-name 7801 // of a base class, unless they're declaring an inheriting constructor. 7802 ASTContext &Ctx = ND->getASTContext(); 7803 if (!Ctx.getLangOpts().CPlusPlus11) 7804 return false; 7805 QualType FoundType = Ctx.getRecordType(FoundRecord); 7806 7807 // Check that the injected-class-name is named as a member of its own 7808 // type; we don't want to suggest 'using Derived::Base;', since that 7809 // means something else. 7810 NestedNameSpecifier *Specifier = 7811 Candidate.WillReplaceSpecifier() 7812 ? Candidate.getCorrectionSpecifier() 7813 : OldNNS; 7814 if (!Specifier->getAsType() || 7815 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7816 return false; 7817 7818 // Check that this inheriting constructor declaration actually names a 7819 // direct base class of the current class. 7820 bool AnyDependentBases = false; 7821 if (!findDirectBaseWithType(RequireMemberOf, 7822 Ctx.getRecordType(FoundRecord), 7823 AnyDependentBases) && 7824 !AnyDependentBases) 7825 return false; 7826 } else { 7827 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7828 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7829 return false; 7830 7831 // FIXME: Check that the base class member is accessible? 7832 } 7833 } 7834 7835 if (isa<TypeDecl>(ND)) 7836 return HasTypenameKeyword || !IsInstantiation; 7837 7838 return !HasTypenameKeyword; 7839 } 7840 7841 private: 7842 bool HasTypenameKeyword; 7843 bool IsInstantiation; 7844 NestedNameSpecifier *OldNNS; 7845 CXXRecordDecl *RequireMemberOf; 7846 }; 7847 } // end anonymous namespace 7848 7849 /// Builds a using declaration. 7850 /// 7851 /// \param IsInstantiation - Whether this call arises from an 7852 /// instantiation of an unresolved using declaration. We treat 7853 /// the lookup differently for these declarations. 7854 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7855 SourceLocation UsingLoc, 7856 CXXScopeSpec &SS, 7857 DeclarationNameInfo NameInfo, 7858 AttributeList *AttrList, 7859 bool IsInstantiation, 7860 bool HasTypenameKeyword, 7861 SourceLocation TypenameLoc) { 7862 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7863 SourceLocation IdentLoc = NameInfo.getLoc(); 7864 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7865 7866 // FIXME: We ignore attributes for now. 7867 7868 if (SS.isEmpty()) { 7869 Diag(IdentLoc, diag::err_using_requires_qualname); 7870 return nullptr; 7871 } 7872 7873 // Do the redeclaration lookup in the current scope. 7874 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7875 ForRedeclaration); 7876 Previous.setHideTags(false); 7877 if (S) { 7878 LookupName(Previous, S); 7879 7880 // It is really dumb that we have to do this. 7881 LookupResult::Filter F = Previous.makeFilter(); 7882 while (F.hasNext()) { 7883 NamedDecl *D = F.next(); 7884 if (!isDeclInScope(D, CurContext, S)) 7885 F.erase(); 7886 // If we found a local extern declaration that's not ordinarily visible, 7887 // and this declaration is being added to a non-block scope, ignore it. 7888 // We're only checking for scope conflicts here, not also for violations 7889 // of the linkage rules. 7890 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7891 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7892 F.erase(); 7893 } 7894 F.done(); 7895 } else { 7896 assert(IsInstantiation && "no scope in non-instantiation"); 7897 assert(CurContext->isRecord() && "scope not record in instantiation"); 7898 LookupQualifiedName(Previous, CurContext); 7899 } 7900 7901 // Check for invalid redeclarations. 7902 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7903 SS, IdentLoc, Previous)) 7904 return nullptr; 7905 7906 // Check for bad qualifiers. 7907 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7908 return nullptr; 7909 7910 DeclContext *LookupContext = computeDeclContext(SS); 7911 NamedDecl *D; 7912 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7913 if (!LookupContext) { 7914 if (HasTypenameKeyword) { 7915 // FIXME: not all declaration name kinds are legal here 7916 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7917 UsingLoc, TypenameLoc, 7918 QualifierLoc, 7919 IdentLoc, NameInfo.getName()); 7920 } else { 7921 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7922 QualifierLoc, NameInfo); 7923 } 7924 D->setAccess(AS); 7925 CurContext->addDecl(D); 7926 return D; 7927 } 7928 7929 auto Build = [&](bool Invalid) { 7930 UsingDecl *UD = 7931 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 7932 HasTypenameKeyword); 7933 UD->setAccess(AS); 7934 CurContext->addDecl(UD); 7935 UD->setInvalidDecl(Invalid); 7936 return UD; 7937 }; 7938 auto BuildInvalid = [&]{ return Build(true); }; 7939 auto BuildValid = [&]{ return Build(false); }; 7940 7941 if (RequireCompleteDeclContext(SS, LookupContext)) 7942 return BuildInvalid(); 7943 7944 // The normal rules do not apply to inheriting constructor declarations. 7945 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7946 UsingDecl *UD = BuildValid(); 7947 CheckInheritingConstructorUsingDecl(UD); 7948 return UD; 7949 } 7950 7951 // Otherwise, look up the target name. 7952 7953 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7954 7955 // Unlike most lookups, we don't always want to hide tag 7956 // declarations: tag names are visible through the using declaration 7957 // even if hidden by ordinary names, *except* in a dependent context 7958 // where it's important for the sanity of two-phase lookup. 7959 if (!IsInstantiation) 7960 R.setHideTags(false); 7961 7962 // For the purposes of this lookup, we have a base object type 7963 // equal to that of the current context. 7964 if (CurContext->isRecord()) { 7965 R.setBaseObjectType( 7966 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7967 } 7968 7969 LookupQualifiedName(R, LookupContext); 7970 7971 // Try to correct typos if possible. 7972 if (R.empty()) { 7973 if (TypoCorrection Corrected = CorrectTypo( 7974 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 7975 llvm::make_unique<UsingValidatorCCC>( 7976 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 7977 dyn_cast<CXXRecordDecl>(CurContext)), 7978 CTK_ErrorRecovery)) { 7979 // We reject any correction for which ND would be NULL. 7980 NamedDecl *ND = Corrected.getCorrectionDecl(); 7981 7982 // We reject candidates where DroppedSpecifier == true, hence the 7983 // literal '0' below. 7984 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7985 << NameInfo.getName() << LookupContext << 0 7986 << SS.getRange()); 7987 7988 // If we corrected to an inheriting constructor, handle it as one. 7989 auto *RD = dyn_cast<CXXRecordDecl>(ND); 7990 if (RD && RD->isInjectedClassName()) { 7991 // Fix up the information we'll use to build the using declaration. 7992 if (Corrected.WillReplaceSpecifier()) { 7993 NestedNameSpecifierLocBuilder Builder; 7994 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 7995 QualifierLoc.getSourceRange()); 7996 QualifierLoc = Builder.getWithLocInContext(Context); 7997 } 7998 7999 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8000 Context.getCanonicalType(Context.getRecordType(RD)))); 8001 NameInfo.setNamedTypeInfo(nullptr); 8002 8003 // Build it and process it as an inheriting constructor. 8004 UsingDecl *UD = BuildValid(); 8005 CheckInheritingConstructorUsingDecl(UD); 8006 return UD; 8007 } 8008 8009 // FIXME: Pick up all the declarations if we found an overloaded function. 8010 R.setLookupName(Corrected.getCorrection()); 8011 R.addDecl(ND); 8012 } else { 8013 Diag(IdentLoc, diag::err_no_member) 8014 << NameInfo.getName() << LookupContext << SS.getRange(); 8015 return BuildInvalid(); 8016 } 8017 } 8018 8019 if (R.isAmbiguous()) 8020 return BuildInvalid(); 8021 8022 if (HasTypenameKeyword) { 8023 // If we asked for a typename and got a non-type decl, error out. 8024 if (!R.getAsSingle<TypeDecl>()) { 8025 Diag(IdentLoc, diag::err_using_typename_non_type); 8026 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8027 Diag((*I)->getUnderlyingDecl()->getLocation(), 8028 diag::note_using_decl_target); 8029 return BuildInvalid(); 8030 } 8031 } else { 8032 // If we asked for a non-typename and we got a type, error out, 8033 // but only if this is an instantiation of an unresolved using 8034 // decl. Otherwise just silently find the type name. 8035 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8036 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8037 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8038 return BuildInvalid(); 8039 } 8040 } 8041 8042 // C++0x N2914 [namespace.udecl]p6: 8043 // A using-declaration shall not name a namespace. 8044 if (R.getAsSingle<NamespaceDecl>()) { 8045 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8046 << SS.getRange(); 8047 return BuildInvalid(); 8048 } 8049 8050 UsingDecl *UD = BuildValid(); 8051 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8052 UsingShadowDecl *PrevDecl = nullptr; 8053 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8054 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8055 } 8056 8057 return UD; 8058 } 8059 8060 /// Additional checks for a using declaration referring to a constructor name. 8061 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8062 assert(!UD->hasTypename() && "expecting a constructor name"); 8063 8064 const Type *SourceType = UD->getQualifier()->getAsType(); 8065 assert(SourceType && 8066 "Using decl naming constructor doesn't have type in scope spec."); 8067 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8068 8069 // Check whether the named type is a direct base class. 8070 bool AnyDependentBases = false; 8071 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8072 AnyDependentBases); 8073 if (!Base && !AnyDependentBases) { 8074 Diag(UD->getUsingLoc(), 8075 diag::err_using_decl_constructor_not_in_direct_base) 8076 << UD->getNameInfo().getSourceRange() 8077 << QualType(SourceType, 0) << TargetClass; 8078 UD->setInvalidDecl(); 8079 return true; 8080 } 8081 8082 if (Base) 8083 Base->setInheritConstructors(); 8084 8085 return false; 8086 } 8087 8088 /// Checks that the given using declaration is not an invalid 8089 /// redeclaration. Note that this is checking only for the using decl 8090 /// itself, not for any ill-formedness among the UsingShadowDecls. 8091 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8092 bool HasTypenameKeyword, 8093 const CXXScopeSpec &SS, 8094 SourceLocation NameLoc, 8095 const LookupResult &Prev) { 8096 // C++03 [namespace.udecl]p8: 8097 // C++0x [namespace.udecl]p10: 8098 // A using-declaration is a declaration and can therefore be used 8099 // repeatedly where (and only where) multiple declarations are 8100 // allowed. 8101 // 8102 // That's in non-member contexts. 8103 if (!CurContext->getRedeclContext()->isRecord()) 8104 return false; 8105 8106 NestedNameSpecifier *Qual = SS.getScopeRep(); 8107 8108 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8109 NamedDecl *D = *I; 8110 8111 bool DTypename; 8112 NestedNameSpecifier *DQual; 8113 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8114 DTypename = UD->hasTypename(); 8115 DQual = UD->getQualifier(); 8116 } else if (UnresolvedUsingValueDecl *UD 8117 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8118 DTypename = false; 8119 DQual = UD->getQualifier(); 8120 } else if (UnresolvedUsingTypenameDecl *UD 8121 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8122 DTypename = true; 8123 DQual = UD->getQualifier(); 8124 } else continue; 8125 8126 // using decls differ if one says 'typename' and the other doesn't. 8127 // FIXME: non-dependent using decls? 8128 if (HasTypenameKeyword != DTypename) continue; 8129 8130 // using decls differ if they name different scopes (but note that 8131 // template instantiation can cause this check to trigger when it 8132 // didn't before instantiation). 8133 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8134 Context.getCanonicalNestedNameSpecifier(DQual)) 8135 continue; 8136 8137 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8138 Diag(D->getLocation(), diag::note_using_decl) << 1; 8139 return true; 8140 } 8141 8142 return false; 8143 } 8144 8145 8146 /// Checks that the given nested-name qualifier used in a using decl 8147 /// in the current context is appropriately related to the current 8148 /// scope. If an error is found, diagnoses it and returns true. 8149 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8150 const CXXScopeSpec &SS, 8151 const DeclarationNameInfo &NameInfo, 8152 SourceLocation NameLoc) { 8153 DeclContext *NamedContext = computeDeclContext(SS); 8154 8155 if (!CurContext->isRecord()) { 8156 // C++03 [namespace.udecl]p3: 8157 // C++0x [namespace.udecl]p8: 8158 // A using-declaration for a class member shall be a member-declaration. 8159 8160 // If we weren't able to compute a valid scope, it must be a 8161 // dependent class scope. 8162 if (!NamedContext || NamedContext->isRecord()) { 8163 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 8164 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8165 RD = nullptr; 8166 8167 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8168 << SS.getRange(); 8169 8170 // If we have a complete, non-dependent source type, try to suggest a 8171 // way to get the same effect. 8172 if (!RD) 8173 return true; 8174 8175 // Find what this using-declaration was referring to. 8176 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8177 R.setHideTags(false); 8178 R.suppressDiagnostics(); 8179 LookupQualifiedName(R, RD); 8180 8181 if (R.getAsSingle<TypeDecl>()) { 8182 if (getLangOpts().CPlusPlus11) { 8183 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8184 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8185 << 0 // alias declaration 8186 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8187 NameInfo.getName().getAsString() + 8188 " = "); 8189 } else { 8190 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8191 SourceLocation InsertLoc = 8192 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8193 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8194 << 1 // typedef declaration 8195 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8196 << FixItHint::CreateInsertion( 8197 InsertLoc, " " + NameInfo.getName().getAsString()); 8198 } 8199 } else if (R.getAsSingle<VarDecl>()) { 8200 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8201 // repeating the type of the static data member here. 8202 FixItHint FixIt; 8203 if (getLangOpts().CPlusPlus11) { 8204 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8205 FixIt = FixItHint::CreateReplacement( 8206 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8207 } 8208 8209 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8210 << 2 // reference declaration 8211 << FixIt; 8212 } 8213 return true; 8214 } 8215 8216 // Otherwise, everything is known to be fine. 8217 return false; 8218 } 8219 8220 // The current scope is a record. 8221 8222 // If the named context is dependent, we can't decide much. 8223 if (!NamedContext) { 8224 // FIXME: in C++0x, we can diagnose if we can prove that the 8225 // nested-name-specifier does not refer to a base class, which is 8226 // still possible in some cases. 8227 8228 // Otherwise we have to conservatively report that things might be 8229 // okay. 8230 return false; 8231 } 8232 8233 if (!NamedContext->isRecord()) { 8234 // Ideally this would point at the last name in the specifier, 8235 // but we don't have that level of source info. 8236 Diag(SS.getRange().getBegin(), 8237 diag::err_using_decl_nested_name_specifier_is_not_class) 8238 << SS.getScopeRep() << SS.getRange(); 8239 return true; 8240 } 8241 8242 if (!NamedContext->isDependentContext() && 8243 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8244 return true; 8245 8246 if (getLangOpts().CPlusPlus11) { 8247 // C++0x [namespace.udecl]p3: 8248 // In a using-declaration used as a member-declaration, the 8249 // nested-name-specifier shall name a base class of the class 8250 // being defined. 8251 8252 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8253 cast<CXXRecordDecl>(NamedContext))) { 8254 if (CurContext == NamedContext) { 8255 Diag(NameLoc, 8256 diag::err_using_decl_nested_name_specifier_is_current_class) 8257 << SS.getRange(); 8258 return true; 8259 } 8260 8261 Diag(SS.getRange().getBegin(), 8262 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8263 << SS.getScopeRep() 8264 << cast<CXXRecordDecl>(CurContext) 8265 << SS.getRange(); 8266 return true; 8267 } 8268 8269 return false; 8270 } 8271 8272 // C++03 [namespace.udecl]p4: 8273 // A using-declaration used as a member-declaration shall refer 8274 // to a member of a base class of the class being defined [etc.]. 8275 8276 // Salient point: SS doesn't have to name a base class as long as 8277 // lookup only finds members from base classes. Therefore we can 8278 // diagnose here only if we can prove that that can't happen, 8279 // i.e. if the class hierarchies provably don't intersect. 8280 8281 // TODO: it would be nice if "definitely valid" results were cached 8282 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8283 // need to be repeated. 8284 8285 struct UserData { 8286 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8287 8288 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8289 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8290 Data->Bases.insert(Base); 8291 return true; 8292 } 8293 8294 bool hasDependentBases(const CXXRecordDecl *Class) { 8295 return !Class->forallBases(collect, this); 8296 } 8297 8298 /// Returns true if the base is dependent or is one of the 8299 /// accumulated base classes. 8300 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8301 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8302 return !Data->Bases.count(Base); 8303 } 8304 8305 bool mightShareBases(const CXXRecordDecl *Class) { 8306 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8307 } 8308 }; 8309 8310 UserData Data; 8311 8312 // Returns false if we find a dependent base. 8313 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8314 return false; 8315 8316 // Returns false if the class has a dependent base or if it or one 8317 // of its bases is present in the base set of the current context. 8318 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8319 return false; 8320 8321 Diag(SS.getRange().getBegin(), 8322 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8323 << SS.getScopeRep() 8324 << cast<CXXRecordDecl>(CurContext) 8325 << SS.getRange(); 8326 8327 return true; 8328 } 8329 8330 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8331 AccessSpecifier AS, 8332 MultiTemplateParamsArg TemplateParamLists, 8333 SourceLocation UsingLoc, 8334 UnqualifiedId &Name, 8335 AttributeList *AttrList, 8336 TypeResult Type) { 8337 // Skip up to the relevant declaration scope. 8338 while (S->getFlags() & Scope::TemplateParamScope) 8339 S = S->getParent(); 8340 assert((S->getFlags() & Scope::DeclScope) && 8341 "got alias-declaration outside of declaration scope"); 8342 8343 if (Type.isInvalid()) 8344 return nullptr; 8345 8346 bool Invalid = false; 8347 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8348 TypeSourceInfo *TInfo = nullptr; 8349 GetTypeFromParser(Type.get(), &TInfo); 8350 8351 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8352 return nullptr; 8353 8354 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8355 UPPC_DeclarationType)) { 8356 Invalid = true; 8357 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8358 TInfo->getTypeLoc().getBeginLoc()); 8359 } 8360 8361 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8362 LookupName(Previous, S); 8363 8364 // Warn about shadowing the name of a template parameter. 8365 if (Previous.isSingleResult() && 8366 Previous.getFoundDecl()->isTemplateParameter()) { 8367 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8368 Previous.clear(); 8369 } 8370 8371 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8372 "name in alias declaration must be an identifier"); 8373 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8374 Name.StartLocation, 8375 Name.Identifier, TInfo); 8376 8377 NewTD->setAccess(AS); 8378 8379 if (Invalid) 8380 NewTD->setInvalidDecl(); 8381 8382 ProcessDeclAttributeList(S, NewTD, AttrList); 8383 8384 CheckTypedefForVariablyModifiedType(S, NewTD); 8385 Invalid |= NewTD->isInvalidDecl(); 8386 8387 bool Redeclaration = false; 8388 8389 NamedDecl *NewND; 8390 if (TemplateParamLists.size()) { 8391 TypeAliasTemplateDecl *OldDecl = nullptr; 8392 TemplateParameterList *OldTemplateParams = nullptr; 8393 8394 if (TemplateParamLists.size() != 1) { 8395 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8396 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8397 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8398 } 8399 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8400 8401 // Only consider previous declarations in the same scope. 8402 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8403 /*ExplicitInstantiationOrSpecialization*/false); 8404 if (!Previous.empty()) { 8405 Redeclaration = true; 8406 8407 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8408 if (!OldDecl && !Invalid) { 8409 Diag(UsingLoc, diag::err_redefinition_different_kind) 8410 << Name.Identifier; 8411 8412 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8413 if (OldD->getLocation().isValid()) 8414 Diag(OldD->getLocation(), diag::note_previous_definition); 8415 8416 Invalid = true; 8417 } 8418 8419 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8420 if (TemplateParameterListsAreEqual(TemplateParams, 8421 OldDecl->getTemplateParameters(), 8422 /*Complain=*/true, 8423 TPL_TemplateMatch)) 8424 OldTemplateParams = OldDecl->getTemplateParameters(); 8425 else 8426 Invalid = true; 8427 8428 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8429 if (!Invalid && 8430 !Context.hasSameType(OldTD->getUnderlyingType(), 8431 NewTD->getUnderlyingType())) { 8432 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8433 // but we can't reasonably accept it. 8434 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8435 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8436 if (OldTD->getLocation().isValid()) 8437 Diag(OldTD->getLocation(), diag::note_previous_definition); 8438 Invalid = true; 8439 } 8440 } 8441 } 8442 8443 // Merge any previous default template arguments into our parameters, 8444 // and check the parameter list. 8445 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8446 TPC_TypeAliasTemplate)) 8447 return nullptr; 8448 8449 TypeAliasTemplateDecl *NewDecl = 8450 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8451 Name.Identifier, TemplateParams, 8452 NewTD); 8453 NewTD->setDescribedAliasTemplate(NewDecl); 8454 8455 NewDecl->setAccess(AS); 8456 8457 if (Invalid) 8458 NewDecl->setInvalidDecl(); 8459 else if (OldDecl) 8460 NewDecl->setPreviousDecl(OldDecl); 8461 8462 NewND = NewDecl; 8463 } else { 8464 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8465 NewND = NewTD; 8466 } 8467 8468 if (!Redeclaration) 8469 PushOnScopeChains(NewND, S); 8470 8471 ActOnDocumentableDecl(NewND); 8472 return NewND; 8473 } 8474 8475 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8476 SourceLocation AliasLoc, 8477 IdentifierInfo *Alias, CXXScopeSpec &SS, 8478 SourceLocation IdentLoc, 8479 IdentifierInfo *Ident) { 8480 8481 // Lookup the namespace name. 8482 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8483 LookupParsedName(R, S, &SS); 8484 8485 if (R.isAmbiguous()) 8486 return nullptr; 8487 8488 if (R.empty()) { 8489 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8490 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8491 return nullptr; 8492 } 8493 } 8494 assert(!R.isAmbiguous() && !R.empty()); 8495 8496 // Check if we have a previous declaration with the same name. 8497 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8498 ForRedeclaration); 8499 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8500 PrevDecl = nullptr; 8501 8502 NamedDecl *ND = R.getFoundDecl(); 8503 8504 if (PrevDecl) { 8505 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8506 // We already have an alias with the same name that points to the same 8507 // namespace; check that it matches. 8508 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8509 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8510 << Alias; 8511 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8512 << AD->getNamespace(); 8513 return nullptr; 8514 } 8515 } else { 8516 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8517 ? diag::err_redefinition 8518 : diag::err_redefinition_different_kind; 8519 Diag(AliasLoc, DiagID) << Alias; 8520 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8521 return nullptr; 8522 } 8523 } 8524 8525 // The use of a nested name specifier may trigger deprecation warnings. 8526 DiagnoseUseOfDecl(ND, IdentLoc); 8527 8528 NamespaceAliasDecl *AliasDecl = 8529 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8530 Alias, SS.getWithLocInContext(Context), 8531 IdentLoc, ND); 8532 if (PrevDecl) 8533 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8534 8535 PushOnScopeChains(AliasDecl, S); 8536 return AliasDecl; 8537 } 8538 8539 Sema::ImplicitExceptionSpecification 8540 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8541 CXXMethodDecl *MD) { 8542 CXXRecordDecl *ClassDecl = MD->getParent(); 8543 8544 // C++ [except.spec]p14: 8545 // An implicitly declared special member function (Clause 12) shall have an 8546 // exception-specification. [...] 8547 ImplicitExceptionSpecification ExceptSpec(*this); 8548 if (ClassDecl->isInvalidDecl()) 8549 return ExceptSpec; 8550 8551 // Direct base-class constructors. 8552 for (const auto &B : ClassDecl->bases()) { 8553 if (B.isVirtual()) // Handled below. 8554 continue; 8555 8556 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8557 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8558 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8559 // If this is a deleted function, add it anyway. This might be conformant 8560 // with the standard. This might not. I'm not sure. It might not matter. 8561 if (Constructor) 8562 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8563 } 8564 } 8565 8566 // Virtual base-class constructors. 8567 for (const auto &B : ClassDecl->vbases()) { 8568 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8569 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8570 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8571 // If this is a deleted function, add it anyway. This might be conformant 8572 // with the standard. This might not. I'm not sure. It might not matter. 8573 if (Constructor) 8574 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8575 } 8576 } 8577 8578 // Field constructors. 8579 for (const auto *F : ClassDecl->fields()) { 8580 if (F->hasInClassInitializer()) { 8581 if (Expr *E = F->getInClassInitializer()) 8582 ExceptSpec.CalledExpr(E); 8583 } else if (const RecordType *RecordTy 8584 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8585 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8586 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8587 // If this is a deleted function, add it anyway. This might be conformant 8588 // with the standard. This might not. I'm not sure. It might not matter. 8589 // In particular, the problem is that this function never gets called. It 8590 // might just be ill-formed because this function attempts to refer to 8591 // a deleted function here. 8592 if (Constructor) 8593 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8594 } 8595 } 8596 8597 return ExceptSpec; 8598 } 8599 8600 Sema::ImplicitExceptionSpecification 8601 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8602 CXXRecordDecl *ClassDecl = CD->getParent(); 8603 8604 // C++ [except.spec]p14: 8605 // An inheriting constructor [...] shall have an exception-specification. [...] 8606 ImplicitExceptionSpecification ExceptSpec(*this); 8607 if (ClassDecl->isInvalidDecl()) 8608 return ExceptSpec; 8609 8610 // Inherited constructor. 8611 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8612 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8613 // FIXME: Copying or moving the parameters could add extra exceptions to the 8614 // set, as could the default arguments for the inherited constructor. This 8615 // will be addressed when we implement the resolution of core issue 1351. 8616 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8617 8618 // Direct base-class constructors. 8619 for (const auto &B : ClassDecl->bases()) { 8620 if (B.isVirtual()) // Handled below. 8621 continue; 8622 8623 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8624 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8625 if (BaseClassDecl == InheritedDecl) 8626 continue; 8627 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8628 if (Constructor) 8629 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8630 } 8631 } 8632 8633 // Virtual base-class constructors. 8634 for (const auto &B : ClassDecl->vbases()) { 8635 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8636 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8637 if (BaseClassDecl == InheritedDecl) 8638 continue; 8639 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8640 if (Constructor) 8641 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8642 } 8643 } 8644 8645 // Field constructors. 8646 for (const auto *F : ClassDecl->fields()) { 8647 if (F->hasInClassInitializer()) { 8648 if (Expr *E = F->getInClassInitializer()) 8649 ExceptSpec.CalledExpr(E); 8650 } else if (const RecordType *RecordTy 8651 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8652 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8653 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8654 if (Constructor) 8655 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8656 } 8657 } 8658 8659 return ExceptSpec; 8660 } 8661 8662 namespace { 8663 /// RAII object to register a special member as being currently declared. 8664 struct DeclaringSpecialMember { 8665 Sema &S; 8666 Sema::SpecialMemberDecl D; 8667 bool WasAlreadyBeingDeclared; 8668 8669 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8670 : S(S), D(RD, CSM) { 8671 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8672 if (WasAlreadyBeingDeclared) 8673 // This almost never happens, but if it does, ensure that our cache 8674 // doesn't contain a stale result. 8675 S.SpecialMemberCache.clear(); 8676 8677 // FIXME: Register a note to be produced if we encounter an error while 8678 // declaring the special member. 8679 } 8680 ~DeclaringSpecialMember() { 8681 if (!WasAlreadyBeingDeclared) 8682 S.SpecialMembersBeingDeclared.erase(D); 8683 } 8684 8685 /// \brief Are we already trying to declare this special member? 8686 bool isAlreadyBeingDeclared() const { 8687 return WasAlreadyBeingDeclared; 8688 } 8689 }; 8690 } 8691 8692 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8693 CXXRecordDecl *ClassDecl) { 8694 // C++ [class.ctor]p5: 8695 // A default constructor for a class X is a constructor of class X 8696 // that can be called without an argument. If there is no 8697 // user-declared constructor for class X, a default constructor is 8698 // implicitly declared. An implicitly-declared default constructor 8699 // is an inline public member of its class. 8700 assert(ClassDecl->needsImplicitDefaultConstructor() && 8701 "Should not build implicit default constructor!"); 8702 8703 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8704 if (DSM.isAlreadyBeingDeclared()) 8705 return nullptr; 8706 8707 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8708 CXXDefaultConstructor, 8709 false); 8710 8711 // Create the actual constructor declaration. 8712 CanQualType ClassType 8713 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8714 SourceLocation ClassLoc = ClassDecl->getLocation(); 8715 DeclarationName Name 8716 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8717 DeclarationNameInfo NameInfo(Name, ClassLoc); 8718 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8719 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8720 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8721 /*isImplicitlyDeclared=*/true, Constexpr); 8722 DefaultCon->setAccess(AS_public); 8723 DefaultCon->setDefaulted(); 8724 8725 if (getLangOpts().CUDA) { 8726 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8727 DefaultCon, 8728 /* ConstRHS */ false, 8729 /* Diagnose */ false); 8730 } 8731 8732 // Build an exception specification pointing back at this constructor. 8733 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8734 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8735 8736 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8737 // constructors is easy to compute. 8738 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8739 8740 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8741 SetDeclDeleted(DefaultCon, ClassLoc); 8742 8743 // Note that we have declared this constructor. 8744 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8745 8746 if (Scope *S = getScopeForContext(ClassDecl)) 8747 PushOnScopeChains(DefaultCon, S, false); 8748 ClassDecl->addDecl(DefaultCon); 8749 8750 return DefaultCon; 8751 } 8752 8753 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8754 CXXConstructorDecl *Constructor) { 8755 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8756 !Constructor->doesThisDeclarationHaveABody() && 8757 !Constructor->isDeleted()) && 8758 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8759 8760 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8761 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8762 8763 SynthesizedFunctionScope Scope(*this, Constructor); 8764 DiagnosticErrorTrap Trap(Diags); 8765 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8766 Trap.hasErrorOccurred()) { 8767 Diag(CurrentLocation, diag::note_member_synthesized_at) 8768 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8769 Constructor->setInvalidDecl(); 8770 return; 8771 } 8772 8773 // The exception specification is needed because we are defining the 8774 // function. 8775 ResolveExceptionSpec(CurrentLocation, 8776 Constructor->getType()->castAs<FunctionProtoType>()); 8777 8778 SourceLocation Loc = Constructor->getLocEnd().isValid() 8779 ? Constructor->getLocEnd() 8780 : Constructor->getLocation(); 8781 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8782 8783 Constructor->markUsed(Context); 8784 MarkVTableUsed(CurrentLocation, ClassDecl); 8785 8786 if (ASTMutationListener *L = getASTMutationListener()) { 8787 L->CompletedImplicitDefinition(Constructor); 8788 } 8789 8790 DiagnoseUninitializedFields(*this, Constructor); 8791 } 8792 8793 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8794 // Perform any delayed checks on exception specifications. 8795 CheckDelayedMemberExceptionSpecs(); 8796 } 8797 8798 namespace { 8799 /// Information on inheriting constructors to declare. 8800 class InheritingConstructorInfo { 8801 public: 8802 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8803 : SemaRef(SemaRef), Derived(Derived) { 8804 // Mark the constructors that we already have in the derived class. 8805 // 8806 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8807 // unless there is a user-declared constructor with the same signature in 8808 // the class where the using-declaration appears. 8809 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8810 } 8811 8812 void inheritAll(CXXRecordDecl *RD) { 8813 visitAll(RD, &InheritingConstructorInfo::inherit); 8814 } 8815 8816 private: 8817 /// Information about an inheriting constructor. 8818 struct InheritingConstructor { 8819 InheritingConstructor() 8820 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8821 8822 /// If \c true, a constructor with this signature is already declared 8823 /// in the derived class. 8824 bool DeclaredInDerived; 8825 8826 /// The constructor which is inherited. 8827 const CXXConstructorDecl *BaseCtor; 8828 8829 /// The derived constructor we declared. 8830 CXXConstructorDecl *DerivedCtor; 8831 }; 8832 8833 /// Inheriting constructors with a given canonical type. There can be at 8834 /// most one such non-template constructor, and any number of templated 8835 /// constructors. 8836 struct InheritingConstructorsForType { 8837 InheritingConstructor NonTemplate; 8838 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8839 Templates; 8840 8841 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8842 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8843 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8844 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8845 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8846 false, S.TPL_TemplateMatch)) 8847 return Templates[I].second; 8848 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8849 return Templates.back().second; 8850 } 8851 8852 return NonTemplate; 8853 } 8854 }; 8855 8856 /// Get or create the inheriting constructor record for a constructor. 8857 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8858 QualType CtorType) { 8859 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8860 .getEntry(SemaRef, Ctor); 8861 } 8862 8863 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8864 8865 /// Process all constructors for a class. 8866 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8867 for (const auto *Ctor : RD->ctors()) 8868 (this->*Callback)(Ctor); 8869 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8870 I(RD->decls_begin()), E(RD->decls_end()); 8871 I != E; ++I) { 8872 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8873 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8874 (this->*Callback)(CD); 8875 } 8876 } 8877 8878 /// Note that a constructor (or constructor template) was declared in Derived. 8879 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8880 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8881 } 8882 8883 /// Inherit a single constructor. 8884 void inherit(const CXXConstructorDecl *Ctor) { 8885 const FunctionProtoType *CtorType = 8886 Ctor->getType()->castAs<FunctionProtoType>(); 8887 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 8888 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8889 8890 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8891 8892 // Core issue (no number yet): the ellipsis is always discarded. 8893 if (EPI.Variadic) { 8894 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8895 SemaRef.Diag(Ctor->getLocation(), 8896 diag::note_using_decl_constructor_ellipsis); 8897 EPI.Variadic = false; 8898 } 8899 8900 // Declare a constructor for each number of parameters. 8901 // 8902 // C++11 [class.inhctor]p1: 8903 // The candidate set of inherited constructors from the class X named in 8904 // the using-declaration consists of [... modulo defects ...] for each 8905 // constructor or constructor template of X, the set of constructors or 8906 // constructor templates that results from omitting any ellipsis parameter 8907 // specification and successively omitting parameters with a default 8908 // argument from the end of the parameter-type-list 8909 unsigned MinParams = minParamsToInherit(Ctor); 8910 unsigned Params = Ctor->getNumParams(); 8911 if (Params >= MinParams) { 8912 do 8913 declareCtor(UsingLoc, Ctor, 8914 SemaRef.Context.getFunctionType( 8915 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8916 while (Params > MinParams && 8917 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8918 } 8919 } 8920 8921 /// Find the using-declaration which specified that we should inherit the 8922 /// constructors of \p Base. 8923 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8924 // No fancy lookup required; just look for the base constructor name 8925 // directly within the derived class. 8926 ASTContext &Context = SemaRef.Context; 8927 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8928 Context.getCanonicalType(Context.getRecordType(Base))); 8929 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8930 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8931 } 8932 8933 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8934 // C++11 [class.inhctor]p3: 8935 // [F]or each constructor template in the candidate set of inherited 8936 // constructors, a constructor template is implicitly declared 8937 if (Ctor->getDescribedFunctionTemplate()) 8938 return 0; 8939 8940 // For each non-template constructor in the candidate set of inherited 8941 // constructors other than a constructor having no parameters or a 8942 // copy/move constructor having a single parameter, a constructor is 8943 // implicitly declared [...] 8944 if (Ctor->getNumParams() == 0) 8945 return 1; 8946 if (Ctor->isCopyOrMoveConstructor()) 8947 return 2; 8948 8949 // Per discussion on core reflector, never inherit a constructor which 8950 // would become a default, copy, or move constructor of Derived either. 8951 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8952 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8953 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8954 } 8955 8956 /// Declare a single inheriting constructor, inheriting the specified 8957 /// constructor, with the given type. 8958 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8959 QualType DerivedType) { 8960 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8961 8962 // C++11 [class.inhctor]p3: 8963 // ... a constructor is implicitly declared with the same constructor 8964 // characteristics unless there is a user-declared constructor with 8965 // the same signature in the class where the using-declaration appears 8966 if (Entry.DeclaredInDerived) 8967 return; 8968 8969 // C++11 [class.inhctor]p7: 8970 // If two using-declarations declare inheriting constructors with the 8971 // same signature, the program is ill-formed 8972 if (Entry.DerivedCtor) { 8973 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8974 // Only diagnose this once per constructor. 8975 if (Entry.DerivedCtor->isInvalidDecl()) 8976 return; 8977 Entry.DerivedCtor->setInvalidDecl(); 8978 8979 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8980 SemaRef.Diag(BaseCtor->getLocation(), 8981 diag::note_using_decl_constructor_conflict_current_ctor); 8982 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8983 diag::note_using_decl_constructor_conflict_previous_ctor); 8984 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8985 diag::note_using_decl_constructor_conflict_previous_using); 8986 } else { 8987 // Core issue (no number): if the same inheriting constructor is 8988 // produced by multiple base class constructors from the same base 8989 // class, the inheriting constructor is defined as deleted. 8990 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8991 } 8992 8993 return; 8994 } 8995 8996 ASTContext &Context = SemaRef.Context; 8997 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8998 Context.getCanonicalType(Context.getRecordType(Derived))); 8999 DeclarationNameInfo NameInfo(Name, UsingLoc); 9000 9001 TemplateParameterList *TemplateParams = nullptr; 9002 if (const FunctionTemplateDecl *FTD = 9003 BaseCtor->getDescribedFunctionTemplate()) { 9004 TemplateParams = FTD->getTemplateParameters(); 9005 // We're reusing template parameters from a different DeclContext. This 9006 // is questionable at best, but works out because the template depth in 9007 // both places is guaranteed to be 0. 9008 // FIXME: Rebuild the template parameters in the new context, and 9009 // transform the function type to refer to them. 9010 } 9011 9012 // Build type source info pointing at the using-declaration. This is 9013 // required by template instantiation. 9014 TypeSourceInfo *TInfo = 9015 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9016 FunctionProtoTypeLoc ProtoLoc = 9017 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9018 9019 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9020 Context, Derived, UsingLoc, NameInfo, DerivedType, 9021 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9022 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9023 9024 // Build an unevaluated exception specification for this constructor. 9025 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9026 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9027 EPI.ExceptionSpec.Type = EST_Unevaluated; 9028 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9029 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9030 FPT->getParamTypes(), EPI)); 9031 9032 // Build the parameter declarations. 9033 SmallVector<ParmVarDecl *, 16> ParamDecls; 9034 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9035 TypeSourceInfo *TInfo = 9036 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9037 ParmVarDecl *PD = ParmVarDecl::Create( 9038 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9039 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9040 PD->setScopeInfo(0, I); 9041 PD->setImplicit(); 9042 ParamDecls.push_back(PD); 9043 ProtoLoc.setParam(I, PD); 9044 } 9045 9046 // Set up the new constructor. 9047 DerivedCtor->setAccess(BaseCtor->getAccess()); 9048 DerivedCtor->setParams(ParamDecls); 9049 DerivedCtor->setInheritedConstructor(BaseCtor); 9050 if (BaseCtor->isDeleted()) 9051 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9052 9053 // If this is a constructor template, build the template declaration. 9054 if (TemplateParams) { 9055 FunctionTemplateDecl *DerivedTemplate = 9056 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9057 TemplateParams, DerivedCtor); 9058 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9059 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9060 Derived->addDecl(DerivedTemplate); 9061 } else { 9062 Derived->addDecl(DerivedCtor); 9063 } 9064 9065 Entry.BaseCtor = BaseCtor; 9066 Entry.DerivedCtor = DerivedCtor; 9067 } 9068 9069 Sema &SemaRef; 9070 CXXRecordDecl *Derived; 9071 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9072 MapType Map; 9073 }; 9074 } 9075 9076 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9077 // Defer declaring the inheriting constructors until the class is 9078 // instantiated. 9079 if (ClassDecl->isDependentContext()) 9080 return; 9081 9082 // Find base classes from which we might inherit constructors. 9083 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9084 for (const auto &BaseIt : ClassDecl->bases()) 9085 if (BaseIt.getInheritConstructors()) 9086 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9087 9088 // Go no further if we're not inheriting any constructors. 9089 if (InheritedBases.empty()) 9090 return; 9091 9092 // Declare the inherited constructors. 9093 InheritingConstructorInfo ICI(*this, ClassDecl); 9094 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9095 ICI.inheritAll(InheritedBases[I]); 9096 } 9097 9098 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9099 CXXConstructorDecl *Constructor) { 9100 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9101 assert(Constructor->getInheritedConstructor() && 9102 !Constructor->doesThisDeclarationHaveABody() && 9103 !Constructor->isDeleted()); 9104 9105 SynthesizedFunctionScope Scope(*this, Constructor); 9106 DiagnosticErrorTrap Trap(Diags); 9107 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9108 Trap.hasErrorOccurred()) { 9109 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9110 << Context.getTagDeclType(ClassDecl); 9111 Constructor->setInvalidDecl(); 9112 return; 9113 } 9114 9115 SourceLocation Loc = Constructor->getLocation(); 9116 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9117 9118 Constructor->markUsed(Context); 9119 MarkVTableUsed(CurrentLocation, ClassDecl); 9120 9121 if (ASTMutationListener *L = getASTMutationListener()) { 9122 L->CompletedImplicitDefinition(Constructor); 9123 } 9124 } 9125 9126 9127 Sema::ImplicitExceptionSpecification 9128 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9129 CXXRecordDecl *ClassDecl = MD->getParent(); 9130 9131 // C++ [except.spec]p14: 9132 // An implicitly declared special member function (Clause 12) shall have 9133 // an exception-specification. 9134 ImplicitExceptionSpecification ExceptSpec(*this); 9135 if (ClassDecl->isInvalidDecl()) 9136 return ExceptSpec; 9137 9138 // Direct base-class destructors. 9139 for (const auto &B : ClassDecl->bases()) { 9140 if (B.isVirtual()) // Handled below. 9141 continue; 9142 9143 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9144 ExceptSpec.CalledDecl(B.getLocStart(), 9145 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9146 } 9147 9148 // Virtual base-class destructors. 9149 for (const auto &B : ClassDecl->vbases()) { 9150 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9151 ExceptSpec.CalledDecl(B.getLocStart(), 9152 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9153 } 9154 9155 // Field destructors. 9156 for (const auto *F : ClassDecl->fields()) { 9157 if (const RecordType *RecordTy 9158 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9159 ExceptSpec.CalledDecl(F->getLocation(), 9160 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9161 } 9162 9163 return ExceptSpec; 9164 } 9165 9166 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9167 // C++ [class.dtor]p2: 9168 // If a class has no user-declared destructor, a destructor is 9169 // declared implicitly. An implicitly-declared destructor is an 9170 // inline public member of its class. 9171 assert(ClassDecl->needsImplicitDestructor()); 9172 9173 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9174 if (DSM.isAlreadyBeingDeclared()) 9175 return nullptr; 9176 9177 // Create the actual destructor declaration. 9178 CanQualType ClassType 9179 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9180 SourceLocation ClassLoc = ClassDecl->getLocation(); 9181 DeclarationName Name 9182 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9183 DeclarationNameInfo NameInfo(Name, ClassLoc); 9184 CXXDestructorDecl *Destructor 9185 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9186 QualType(), nullptr, /*isInline=*/true, 9187 /*isImplicitlyDeclared=*/true); 9188 Destructor->setAccess(AS_public); 9189 Destructor->setDefaulted(); 9190 9191 if (getLangOpts().CUDA) { 9192 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9193 Destructor, 9194 /* ConstRHS */ false, 9195 /* Diagnose */ false); 9196 } 9197 9198 // Build an exception specification pointing back at this destructor. 9199 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9200 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9201 9202 AddOverriddenMethods(ClassDecl, Destructor); 9203 9204 // We don't need to use SpecialMemberIsTrivial here; triviality for 9205 // destructors is easy to compute. 9206 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9207 9208 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9209 SetDeclDeleted(Destructor, ClassLoc); 9210 9211 // Note that we have declared this destructor. 9212 ++ASTContext::NumImplicitDestructorsDeclared; 9213 9214 // Introduce this destructor into its scope. 9215 if (Scope *S = getScopeForContext(ClassDecl)) 9216 PushOnScopeChains(Destructor, S, false); 9217 ClassDecl->addDecl(Destructor); 9218 9219 return Destructor; 9220 } 9221 9222 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9223 CXXDestructorDecl *Destructor) { 9224 assert((Destructor->isDefaulted() && 9225 !Destructor->doesThisDeclarationHaveABody() && 9226 !Destructor->isDeleted()) && 9227 "DefineImplicitDestructor - call it for implicit default dtor"); 9228 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9229 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9230 9231 if (Destructor->isInvalidDecl()) 9232 return; 9233 9234 SynthesizedFunctionScope Scope(*this, Destructor); 9235 9236 DiagnosticErrorTrap Trap(Diags); 9237 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9238 Destructor->getParent()); 9239 9240 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9241 Diag(CurrentLocation, diag::note_member_synthesized_at) 9242 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9243 9244 Destructor->setInvalidDecl(); 9245 return; 9246 } 9247 9248 // The exception specification is needed because we are defining the 9249 // function. 9250 ResolveExceptionSpec(CurrentLocation, 9251 Destructor->getType()->castAs<FunctionProtoType>()); 9252 9253 SourceLocation Loc = Destructor->getLocEnd().isValid() 9254 ? Destructor->getLocEnd() 9255 : Destructor->getLocation(); 9256 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9257 Destructor->markUsed(Context); 9258 MarkVTableUsed(CurrentLocation, ClassDecl); 9259 9260 if (ASTMutationListener *L = getASTMutationListener()) { 9261 L->CompletedImplicitDefinition(Destructor); 9262 } 9263 } 9264 9265 /// \brief Perform any semantic analysis which needs to be delayed until all 9266 /// pending class member declarations have been parsed. 9267 void Sema::ActOnFinishCXXMemberDecls() { 9268 // If the context is an invalid C++ class, just suppress these checks. 9269 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9270 if (Record->isInvalidDecl()) { 9271 DelayedDefaultedMemberExceptionSpecs.clear(); 9272 DelayedDestructorExceptionSpecChecks.clear(); 9273 return; 9274 } 9275 } 9276 } 9277 9278 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9279 CXXDestructorDecl *Destructor) { 9280 assert(getLangOpts().CPlusPlus11 && 9281 "adjusting dtor exception specs was introduced in c++11"); 9282 9283 // C++11 [class.dtor]p3: 9284 // A declaration of a destructor that does not have an exception- 9285 // specification is implicitly considered to have the same exception- 9286 // specification as an implicit declaration. 9287 const FunctionProtoType *DtorType = Destructor->getType()-> 9288 getAs<FunctionProtoType>(); 9289 if (DtorType->hasExceptionSpec()) 9290 return; 9291 9292 // Replace the destructor's type, building off the existing one. Fortunately, 9293 // the only thing of interest in the destructor type is its extended info. 9294 // The return and arguments are fixed. 9295 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9296 EPI.ExceptionSpec.Type = EST_Unevaluated; 9297 EPI.ExceptionSpec.SourceDecl = Destructor; 9298 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9299 9300 // FIXME: If the destructor has a body that could throw, and the newly created 9301 // spec doesn't allow exceptions, we should emit a warning, because this 9302 // change in behavior can break conforming C++03 programs at runtime. 9303 // However, we don't have a body or an exception specification yet, so it 9304 // needs to be done somewhere else. 9305 } 9306 9307 namespace { 9308 /// \brief An abstract base class for all helper classes used in building the 9309 // copy/move operators. These classes serve as factory functions and help us 9310 // avoid using the same Expr* in the AST twice. 9311 class ExprBuilder { 9312 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9313 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9314 9315 protected: 9316 static Expr *assertNotNull(Expr *E) { 9317 assert(E && "Expression construction must not fail."); 9318 return E; 9319 } 9320 9321 public: 9322 ExprBuilder() {} 9323 virtual ~ExprBuilder() {} 9324 9325 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9326 }; 9327 9328 class RefBuilder: public ExprBuilder { 9329 VarDecl *Var; 9330 QualType VarType; 9331 9332 public: 9333 Expr *build(Sema &S, SourceLocation Loc) const override { 9334 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9335 } 9336 9337 RefBuilder(VarDecl *Var, QualType VarType) 9338 : Var(Var), VarType(VarType) {} 9339 }; 9340 9341 class ThisBuilder: public ExprBuilder { 9342 public: 9343 Expr *build(Sema &S, SourceLocation Loc) const override { 9344 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9345 } 9346 }; 9347 9348 class CastBuilder: public ExprBuilder { 9349 const ExprBuilder &Builder; 9350 QualType Type; 9351 ExprValueKind Kind; 9352 const CXXCastPath &Path; 9353 9354 public: 9355 Expr *build(Sema &S, SourceLocation Loc) const override { 9356 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9357 CK_UncheckedDerivedToBase, Kind, 9358 &Path).get()); 9359 } 9360 9361 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9362 const CXXCastPath &Path) 9363 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9364 }; 9365 9366 class DerefBuilder: public ExprBuilder { 9367 const ExprBuilder &Builder; 9368 9369 public: 9370 Expr *build(Sema &S, SourceLocation Loc) const override { 9371 return assertNotNull( 9372 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9373 } 9374 9375 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9376 }; 9377 9378 class MemberBuilder: public ExprBuilder { 9379 const ExprBuilder &Builder; 9380 QualType Type; 9381 CXXScopeSpec SS; 9382 bool IsArrow; 9383 LookupResult &MemberLookup; 9384 9385 public: 9386 Expr *build(Sema &S, SourceLocation Loc) const override { 9387 return assertNotNull(S.BuildMemberReferenceExpr( 9388 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9389 nullptr, MemberLookup, nullptr).get()); 9390 } 9391 9392 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9393 LookupResult &MemberLookup) 9394 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9395 MemberLookup(MemberLookup) {} 9396 }; 9397 9398 class MoveCastBuilder: public ExprBuilder { 9399 const ExprBuilder &Builder; 9400 9401 public: 9402 Expr *build(Sema &S, SourceLocation Loc) const override { 9403 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9404 } 9405 9406 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9407 }; 9408 9409 class LvalueConvBuilder: public ExprBuilder { 9410 const ExprBuilder &Builder; 9411 9412 public: 9413 Expr *build(Sema &S, SourceLocation Loc) const override { 9414 return assertNotNull( 9415 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9416 } 9417 9418 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9419 }; 9420 9421 class SubscriptBuilder: public ExprBuilder { 9422 const ExprBuilder &Base; 9423 const ExprBuilder &Index; 9424 9425 public: 9426 Expr *build(Sema &S, SourceLocation Loc) const override { 9427 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9428 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9429 } 9430 9431 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9432 : Base(Base), Index(Index) {} 9433 }; 9434 9435 } // end anonymous namespace 9436 9437 /// When generating a defaulted copy or move assignment operator, if a field 9438 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9439 /// do so. This optimization only applies for arrays of scalars, and for arrays 9440 /// of class type where the selected copy/move-assignment operator is trivial. 9441 static StmtResult 9442 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9443 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9444 // Compute the size of the memory buffer to be copied. 9445 QualType SizeType = S.Context.getSizeType(); 9446 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9447 S.Context.getTypeSizeInChars(T).getQuantity()); 9448 9449 // Take the address of the field references for "from" and "to". We 9450 // directly construct UnaryOperators here because semantic analysis 9451 // does not permit us to take the address of an xvalue. 9452 Expr *From = FromB.build(S, Loc); 9453 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9454 S.Context.getPointerType(From->getType()), 9455 VK_RValue, OK_Ordinary, Loc); 9456 Expr *To = ToB.build(S, Loc); 9457 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9458 S.Context.getPointerType(To->getType()), 9459 VK_RValue, OK_Ordinary, Loc); 9460 9461 const Type *E = T->getBaseElementTypeUnsafe(); 9462 bool NeedsCollectableMemCpy = 9463 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9464 9465 // Create a reference to the __builtin_objc_memmove_collectable function 9466 StringRef MemCpyName = NeedsCollectableMemCpy ? 9467 "__builtin_objc_memmove_collectable" : 9468 "__builtin_memcpy"; 9469 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9470 Sema::LookupOrdinaryName); 9471 S.LookupName(R, S.TUScope, true); 9472 9473 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9474 if (!MemCpy) 9475 // Something went horribly wrong earlier, and we will have complained 9476 // about it. 9477 return StmtError(); 9478 9479 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9480 VK_RValue, Loc, nullptr); 9481 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9482 9483 Expr *CallArgs[] = { 9484 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9485 }; 9486 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9487 Loc, CallArgs, Loc); 9488 9489 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9490 return Call.getAs<Stmt>(); 9491 } 9492 9493 /// \brief Builds a statement that copies/moves the given entity from \p From to 9494 /// \c To. 9495 /// 9496 /// This routine is used to copy/move the members of a class with an 9497 /// implicitly-declared copy/move assignment operator. When the entities being 9498 /// copied are arrays, this routine builds for loops to copy them. 9499 /// 9500 /// \param S The Sema object used for type-checking. 9501 /// 9502 /// \param Loc The location where the implicit copy/move is being generated. 9503 /// 9504 /// \param T The type of the expressions being copied/moved. Both expressions 9505 /// must have this type. 9506 /// 9507 /// \param To The expression we are copying/moving to. 9508 /// 9509 /// \param From The expression we are copying/moving from. 9510 /// 9511 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9512 /// Otherwise, it's a non-static member subobject. 9513 /// 9514 /// \param Copying Whether we're copying or moving. 9515 /// 9516 /// \param Depth Internal parameter recording the depth of the recursion. 9517 /// 9518 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9519 /// if a memcpy should be used instead. 9520 static StmtResult 9521 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9522 const ExprBuilder &To, const ExprBuilder &From, 9523 bool CopyingBaseSubobject, bool Copying, 9524 unsigned Depth = 0) { 9525 // C++11 [class.copy]p28: 9526 // Each subobject is assigned in the manner appropriate to its type: 9527 // 9528 // - if the subobject is of class type, as if by a call to operator= with 9529 // the subobject as the object expression and the corresponding 9530 // subobject of x as a single function argument (as if by explicit 9531 // qualification; that is, ignoring any possible virtual overriding 9532 // functions in more derived classes); 9533 // 9534 // C++03 [class.copy]p13: 9535 // - if the subobject is of class type, the copy assignment operator for 9536 // the class is used (as if by explicit qualification; that is, 9537 // ignoring any possible virtual overriding functions in more derived 9538 // classes); 9539 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9540 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9541 9542 // Look for operator=. 9543 DeclarationName Name 9544 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9545 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9546 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9547 9548 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9549 // operator. 9550 if (!S.getLangOpts().CPlusPlus11) { 9551 LookupResult::Filter F = OpLookup.makeFilter(); 9552 while (F.hasNext()) { 9553 NamedDecl *D = F.next(); 9554 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9555 if (Method->isCopyAssignmentOperator() || 9556 (!Copying && Method->isMoveAssignmentOperator())) 9557 continue; 9558 9559 F.erase(); 9560 } 9561 F.done(); 9562 } 9563 9564 // Suppress the protected check (C++ [class.protected]) for each of the 9565 // assignment operators we found. This strange dance is required when 9566 // we're assigning via a base classes's copy-assignment operator. To 9567 // ensure that we're getting the right base class subobject (without 9568 // ambiguities), we need to cast "this" to that subobject type; to 9569 // ensure that we don't go through the virtual call mechanism, we need 9570 // to qualify the operator= name with the base class (see below). However, 9571 // this means that if the base class has a protected copy assignment 9572 // operator, the protected member access check will fail. So, we 9573 // rewrite "protected" access to "public" access in this case, since we 9574 // know by construction that we're calling from a derived class. 9575 if (CopyingBaseSubobject) { 9576 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9577 L != LEnd; ++L) { 9578 if (L.getAccess() == AS_protected) 9579 L.setAccess(AS_public); 9580 } 9581 } 9582 9583 // Create the nested-name-specifier that will be used to qualify the 9584 // reference to operator=; this is required to suppress the virtual 9585 // call mechanism. 9586 CXXScopeSpec SS; 9587 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9588 SS.MakeTrivial(S.Context, 9589 NestedNameSpecifier::Create(S.Context, nullptr, false, 9590 CanonicalT), 9591 Loc); 9592 9593 // Create the reference to operator=. 9594 ExprResult OpEqualRef 9595 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9596 SS, /*TemplateKWLoc=*/SourceLocation(), 9597 /*FirstQualifierInScope=*/nullptr, 9598 OpLookup, 9599 /*TemplateArgs=*/nullptr, 9600 /*SuppressQualifierCheck=*/true); 9601 if (OpEqualRef.isInvalid()) 9602 return StmtError(); 9603 9604 // Build the call to the assignment operator. 9605 9606 Expr *FromInst = From.build(S, Loc); 9607 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9608 OpEqualRef.getAs<Expr>(), 9609 Loc, FromInst, Loc); 9610 if (Call.isInvalid()) 9611 return StmtError(); 9612 9613 // If we built a call to a trivial 'operator=' while copying an array, 9614 // bail out. We'll replace the whole shebang with a memcpy. 9615 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9616 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9617 return StmtResult((Stmt*)nullptr); 9618 9619 // Convert to an expression-statement, and clean up any produced 9620 // temporaries. 9621 return S.ActOnExprStmt(Call); 9622 } 9623 9624 // - if the subobject is of scalar type, the built-in assignment 9625 // operator is used. 9626 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9627 if (!ArrayTy) { 9628 ExprResult Assignment = S.CreateBuiltinBinOp( 9629 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9630 if (Assignment.isInvalid()) 9631 return StmtError(); 9632 return S.ActOnExprStmt(Assignment); 9633 } 9634 9635 // - if the subobject is an array, each element is assigned, in the 9636 // manner appropriate to the element type; 9637 9638 // Construct a loop over the array bounds, e.g., 9639 // 9640 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9641 // 9642 // that will copy each of the array elements. 9643 QualType SizeType = S.Context.getSizeType(); 9644 9645 // Create the iteration variable. 9646 IdentifierInfo *IterationVarName = nullptr; 9647 { 9648 SmallString<8> Str; 9649 llvm::raw_svector_ostream OS(Str); 9650 OS << "__i" << Depth; 9651 IterationVarName = &S.Context.Idents.get(OS.str()); 9652 } 9653 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9654 IterationVarName, SizeType, 9655 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9656 SC_None); 9657 9658 // Initialize the iteration variable to zero. 9659 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9660 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9661 9662 // Creates a reference to the iteration variable. 9663 RefBuilder IterationVarRef(IterationVar, SizeType); 9664 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9665 9666 // Create the DeclStmt that holds the iteration variable. 9667 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9668 9669 // Subscript the "from" and "to" expressions with the iteration variable. 9670 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9671 MoveCastBuilder FromIndexMove(FromIndexCopy); 9672 const ExprBuilder *FromIndex; 9673 if (Copying) 9674 FromIndex = &FromIndexCopy; 9675 else 9676 FromIndex = &FromIndexMove; 9677 9678 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9679 9680 // Build the copy/move for an individual element of the array. 9681 StmtResult Copy = 9682 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9683 ToIndex, *FromIndex, CopyingBaseSubobject, 9684 Copying, Depth + 1); 9685 // Bail out if copying fails or if we determined that we should use memcpy. 9686 if (Copy.isInvalid() || !Copy.get()) 9687 return Copy; 9688 9689 // Create the comparison against the array bound. 9690 llvm::APInt Upper 9691 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9692 Expr *Comparison 9693 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9694 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9695 BO_NE, S.Context.BoolTy, 9696 VK_RValue, OK_Ordinary, Loc, false); 9697 9698 // Create the pre-increment of the iteration variable. 9699 Expr *Increment 9700 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9701 SizeType, VK_LValue, OK_Ordinary, Loc); 9702 9703 // Construct the loop that copies all elements of this array. 9704 return S.ActOnForStmt(Loc, Loc, InitStmt, 9705 S.MakeFullExpr(Comparison), 9706 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9707 Loc, Copy.get()); 9708 } 9709 9710 static StmtResult 9711 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9712 const ExprBuilder &To, const ExprBuilder &From, 9713 bool CopyingBaseSubobject, bool Copying) { 9714 // Maybe we should use a memcpy? 9715 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9716 T.isTriviallyCopyableType(S.Context)) 9717 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9718 9719 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9720 CopyingBaseSubobject, 9721 Copying, 0)); 9722 9723 // If we ended up picking a trivial assignment operator for an array of a 9724 // non-trivially-copyable class type, just emit a memcpy. 9725 if (!Result.isInvalid() && !Result.get()) 9726 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9727 9728 return Result; 9729 } 9730 9731 Sema::ImplicitExceptionSpecification 9732 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9733 CXXRecordDecl *ClassDecl = MD->getParent(); 9734 9735 ImplicitExceptionSpecification ExceptSpec(*this); 9736 if (ClassDecl->isInvalidDecl()) 9737 return ExceptSpec; 9738 9739 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9740 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9741 unsigned ArgQuals = 9742 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9743 9744 // C++ [except.spec]p14: 9745 // An implicitly declared special member function (Clause 12) shall have an 9746 // exception-specification. [...] 9747 9748 // It is unspecified whether or not an implicit copy assignment operator 9749 // attempts to deduplicate calls to assignment operators of virtual bases are 9750 // made. As such, this exception specification is effectively unspecified. 9751 // Based on a similar decision made for constness in C++0x, we're erring on 9752 // the side of assuming such calls to be made regardless of whether they 9753 // actually happen. 9754 for (const auto &Base : ClassDecl->bases()) { 9755 if (Base.isVirtual()) 9756 continue; 9757 9758 CXXRecordDecl *BaseClassDecl 9759 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9760 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9761 ArgQuals, false, 0)) 9762 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9763 } 9764 9765 for (const auto &Base : ClassDecl->vbases()) { 9766 CXXRecordDecl *BaseClassDecl 9767 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9768 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9769 ArgQuals, false, 0)) 9770 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9771 } 9772 9773 for (const auto *Field : ClassDecl->fields()) { 9774 QualType FieldType = Context.getBaseElementType(Field->getType()); 9775 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9776 if (CXXMethodDecl *CopyAssign = 9777 LookupCopyingAssignment(FieldClassDecl, 9778 ArgQuals | FieldType.getCVRQualifiers(), 9779 false, 0)) 9780 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9781 } 9782 } 9783 9784 return ExceptSpec; 9785 } 9786 9787 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9788 // Note: The following rules are largely analoguous to the copy 9789 // constructor rules. Note that virtual bases are not taken into account 9790 // for determining the argument type of the operator. Note also that 9791 // operators taking an object instead of a reference are allowed. 9792 assert(ClassDecl->needsImplicitCopyAssignment()); 9793 9794 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9795 if (DSM.isAlreadyBeingDeclared()) 9796 return nullptr; 9797 9798 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9799 QualType RetType = Context.getLValueReferenceType(ArgType); 9800 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9801 if (Const) 9802 ArgType = ArgType.withConst(); 9803 ArgType = Context.getLValueReferenceType(ArgType); 9804 9805 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9806 CXXCopyAssignment, 9807 Const); 9808 9809 // An implicitly-declared copy assignment operator is an inline public 9810 // member of its class. 9811 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9812 SourceLocation ClassLoc = ClassDecl->getLocation(); 9813 DeclarationNameInfo NameInfo(Name, ClassLoc); 9814 CXXMethodDecl *CopyAssignment = 9815 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9816 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9817 /*isInline=*/true, Constexpr, SourceLocation()); 9818 CopyAssignment->setAccess(AS_public); 9819 CopyAssignment->setDefaulted(); 9820 CopyAssignment->setImplicit(); 9821 9822 if (getLangOpts().CUDA) { 9823 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 9824 CopyAssignment, 9825 /* ConstRHS */ Const, 9826 /* Diagnose */ false); 9827 } 9828 9829 // Build an exception specification pointing back at this member. 9830 FunctionProtoType::ExtProtoInfo EPI = 9831 getImplicitMethodEPI(*this, CopyAssignment); 9832 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9833 9834 // Add the parameter to the operator. 9835 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9836 ClassLoc, ClassLoc, 9837 /*Id=*/nullptr, ArgType, 9838 /*TInfo=*/nullptr, SC_None, 9839 nullptr); 9840 CopyAssignment->setParams(FromParam); 9841 9842 AddOverriddenMethods(ClassDecl, CopyAssignment); 9843 9844 CopyAssignment->setTrivial( 9845 ClassDecl->needsOverloadResolutionForCopyAssignment() 9846 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9847 : ClassDecl->hasTrivialCopyAssignment()); 9848 9849 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9850 SetDeclDeleted(CopyAssignment, ClassLoc); 9851 9852 // Note that we have added this copy-assignment operator. 9853 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9854 9855 if (Scope *S = getScopeForContext(ClassDecl)) 9856 PushOnScopeChains(CopyAssignment, S, false); 9857 ClassDecl->addDecl(CopyAssignment); 9858 9859 return CopyAssignment; 9860 } 9861 9862 /// Diagnose an implicit copy operation for a class which is odr-used, but 9863 /// which is deprecated because the class has a user-declared copy constructor, 9864 /// copy assignment operator, or destructor. 9865 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9866 SourceLocation UseLoc) { 9867 assert(CopyOp->isImplicit()); 9868 9869 CXXRecordDecl *RD = CopyOp->getParent(); 9870 CXXMethodDecl *UserDeclaredOperation = nullptr; 9871 9872 // In Microsoft mode, assignment operations don't affect constructors and 9873 // vice versa. 9874 if (RD->hasUserDeclaredDestructor()) { 9875 UserDeclaredOperation = RD->getDestructor(); 9876 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9877 RD->hasUserDeclaredCopyConstructor() && 9878 !S.getLangOpts().MSVCCompat) { 9879 // Find any user-declared copy constructor. 9880 for (auto *I : RD->ctors()) { 9881 if (I->isCopyConstructor()) { 9882 UserDeclaredOperation = I; 9883 break; 9884 } 9885 } 9886 assert(UserDeclaredOperation); 9887 } else if (isa<CXXConstructorDecl>(CopyOp) && 9888 RD->hasUserDeclaredCopyAssignment() && 9889 !S.getLangOpts().MSVCCompat) { 9890 // Find any user-declared move assignment operator. 9891 for (auto *I : RD->methods()) { 9892 if (I->isCopyAssignmentOperator()) { 9893 UserDeclaredOperation = I; 9894 break; 9895 } 9896 } 9897 assert(UserDeclaredOperation); 9898 } 9899 9900 if (UserDeclaredOperation) { 9901 S.Diag(UserDeclaredOperation->getLocation(), 9902 diag::warn_deprecated_copy_operation) 9903 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9904 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9905 S.Diag(UseLoc, diag::note_member_synthesized_at) 9906 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9907 : Sema::CXXCopyAssignment) 9908 << RD; 9909 } 9910 } 9911 9912 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9913 CXXMethodDecl *CopyAssignOperator) { 9914 assert((CopyAssignOperator->isDefaulted() && 9915 CopyAssignOperator->isOverloadedOperator() && 9916 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9917 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9918 !CopyAssignOperator->isDeleted()) && 9919 "DefineImplicitCopyAssignment called for wrong function"); 9920 9921 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9922 9923 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9924 CopyAssignOperator->setInvalidDecl(); 9925 return; 9926 } 9927 9928 // C++11 [class.copy]p18: 9929 // The [definition of an implicitly declared copy assignment operator] is 9930 // deprecated if the class has a user-declared copy constructor or a 9931 // user-declared destructor. 9932 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9933 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9934 9935 CopyAssignOperator->markUsed(Context); 9936 9937 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9938 DiagnosticErrorTrap Trap(Diags); 9939 9940 // C++0x [class.copy]p30: 9941 // The implicitly-defined or explicitly-defaulted copy assignment operator 9942 // for a non-union class X performs memberwise copy assignment of its 9943 // subobjects. The direct base classes of X are assigned first, in the 9944 // order of their declaration in the base-specifier-list, and then the 9945 // immediate non-static data members of X are assigned, in the order in 9946 // which they were declared in the class definition. 9947 9948 // The statements that form the synthesized function body. 9949 SmallVector<Stmt*, 8> Statements; 9950 9951 // The parameter for the "other" object, which we are copying from. 9952 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9953 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9954 QualType OtherRefType = Other->getType(); 9955 if (const LValueReferenceType *OtherRef 9956 = OtherRefType->getAs<LValueReferenceType>()) { 9957 OtherRefType = OtherRef->getPointeeType(); 9958 OtherQuals = OtherRefType.getQualifiers(); 9959 } 9960 9961 // Our location for everything implicitly-generated. 9962 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 9963 ? CopyAssignOperator->getLocEnd() 9964 : CopyAssignOperator->getLocation(); 9965 9966 // Builds a DeclRefExpr for the "other" object. 9967 RefBuilder OtherRef(Other, OtherRefType); 9968 9969 // Builds the "this" pointer. 9970 ThisBuilder This; 9971 9972 // Assign base classes. 9973 bool Invalid = false; 9974 for (auto &Base : ClassDecl->bases()) { 9975 // Form the assignment: 9976 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9977 QualType BaseType = Base.getType().getUnqualifiedType(); 9978 if (!BaseType->isRecordType()) { 9979 Invalid = true; 9980 continue; 9981 } 9982 9983 CXXCastPath BasePath; 9984 BasePath.push_back(&Base); 9985 9986 // Construct the "from" expression, which is an implicit cast to the 9987 // appropriately-qualified base type. 9988 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9989 VK_LValue, BasePath); 9990 9991 // Dereference "this". 9992 DerefBuilder DerefThis(This); 9993 CastBuilder To(DerefThis, 9994 Context.getCVRQualifiedType( 9995 BaseType, CopyAssignOperator->getTypeQualifiers()), 9996 VK_LValue, BasePath); 9997 9998 // Build the copy. 9999 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10000 To, From, 10001 /*CopyingBaseSubobject=*/true, 10002 /*Copying=*/true); 10003 if (Copy.isInvalid()) { 10004 Diag(CurrentLocation, diag::note_member_synthesized_at) 10005 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10006 CopyAssignOperator->setInvalidDecl(); 10007 return; 10008 } 10009 10010 // Success! Record the copy. 10011 Statements.push_back(Copy.getAs<Expr>()); 10012 } 10013 10014 // Assign non-static members. 10015 for (auto *Field : ClassDecl->fields()) { 10016 if (Field->isUnnamedBitfield()) 10017 continue; 10018 10019 if (Field->isInvalidDecl()) { 10020 Invalid = true; 10021 continue; 10022 } 10023 10024 // Check for members of reference type; we can't copy those. 10025 if (Field->getType()->isReferenceType()) { 10026 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10027 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10028 Diag(Field->getLocation(), diag::note_declared_at); 10029 Diag(CurrentLocation, diag::note_member_synthesized_at) 10030 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10031 Invalid = true; 10032 continue; 10033 } 10034 10035 // Check for members of const-qualified, non-class type. 10036 QualType BaseType = Context.getBaseElementType(Field->getType()); 10037 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10038 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10039 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10040 Diag(Field->getLocation(), diag::note_declared_at); 10041 Diag(CurrentLocation, diag::note_member_synthesized_at) 10042 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10043 Invalid = true; 10044 continue; 10045 } 10046 10047 // Suppress assigning zero-width bitfields. 10048 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10049 continue; 10050 10051 QualType FieldType = Field->getType().getNonReferenceType(); 10052 if (FieldType->isIncompleteArrayType()) { 10053 assert(ClassDecl->hasFlexibleArrayMember() && 10054 "Incomplete array type is not valid"); 10055 continue; 10056 } 10057 10058 // Build references to the field in the object we're copying from and to. 10059 CXXScopeSpec SS; // Intentionally empty 10060 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10061 LookupMemberName); 10062 MemberLookup.addDecl(Field); 10063 MemberLookup.resolveKind(); 10064 10065 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10066 10067 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10068 10069 // Build the copy of this field. 10070 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10071 To, From, 10072 /*CopyingBaseSubobject=*/false, 10073 /*Copying=*/true); 10074 if (Copy.isInvalid()) { 10075 Diag(CurrentLocation, diag::note_member_synthesized_at) 10076 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10077 CopyAssignOperator->setInvalidDecl(); 10078 return; 10079 } 10080 10081 // Success! Record the copy. 10082 Statements.push_back(Copy.getAs<Stmt>()); 10083 } 10084 10085 if (!Invalid) { 10086 // Add a "return *this;" 10087 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10088 10089 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10090 if (Return.isInvalid()) 10091 Invalid = true; 10092 else { 10093 Statements.push_back(Return.getAs<Stmt>()); 10094 10095 if (Trap.hasErrorOccurred()) { 10096 Diag(CurrentLocation, diag::note_member_synthesized_at) 10097 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10098 Invalid = true; 10099 } 10100 } 10101 } 10102 10103 // The exception specification is needed because we are defining the 10104 // function. 10105 ResolveExceptionSpec(CurrentLocation, 10106 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10107 10108 if (Invalid) { 10109 CopyAssignOperator->setInvalidDecl(); 10110 return; 10111 } 10112 10113 StmtResult Body; 10114 { 10115 CompoundScopeRAII CompoundScope(*this); 10116 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10117 /*isStmtExpr=*/false); 10118 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10119 } 10120 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10121 10122 if (ASTMutationListener *L = getASTMutationListener()) { 10123 L->CompletedImplicitDefinition(CopyAssignOperator); 10124 } 10125 } 10126 10127 Sema::ImplicitExceptionSpecification 10128 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10129 CXXRecordDecl *ClassDecl = MD->getParent(); 10130 10131 ImplicitExceptionSpecification ExceptSpec(*this); 10132 if (ClassDecl->isInvalidDecl()) 10133 return ExceptSpec; 10134 10135 // C++0x [except.spec]p14: 10136 // An implicitly declared special member function (Clause 12) shall have an 10137 // exception-specification. [...] 10138 10139 // It is unspecified whether or not an implicit move assignment operator 10140 // attempts to deduplicate calls to assignment operators of virtual bases are 10141 // made. As such, this exception specification is effectively unspecified. 10142 // Based on a similar decision made for constness in C++0x, we're erring on 10143 // the side of assuming such calls to be made regardless of whether they 10144 // actually happen. 10145 // Note that a move constructor is not implicitly declared when there are 10146 // virtual bases, but it can still be user-declared and explicitly defaulted. 10147 for (const auto &Base : ClassDecl->bases()) { 10148 if (Base.isVirtual()) 10149 continue; 10150 10151 CXXRecordDecl *BaseClassDecl 10152 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10153 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10154 0, false, 0)) 10155 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10156 } 10157 10158 for (const auto &Base : ClassDecl->vbases()) { 10159 CXXRecordDecl *BaseClassDecl 10160 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10161 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10162 0, false, 0)) 10163 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10164 } 10165 10166 for (const auto *Field : ClassDecl->fields()) { 10167 QualType FieldType = Context.getBaseElementType(Field->getType()); 10168 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10169 if (CXXMethodDecl *MoveAssign = 10170 LookupMovingAssignment(FieldClassDecl, 10171 FieldType.getCVRQualifiers(), 10172 false, 0)) 10173 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10174 } 10175 } 10176 10177 return ExceptSpec; 10178 } 10179 10180 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10181 assert(ClassDecl->needsImplicitMoveAssignment()); 10182 10183 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10184 if (DSM.isAlreadyBeingDeclared()) 10185 return nullptr; 10186 10187 // Note: The following rules are largely analoguous to the move 10188 // constructor rules. 10189 10190 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10191 QualType RetType = Context.getLValueReferenceType(ArgType); 10192 ArgType = Context.getRValueReferenceType(ArgType); 10193 10194 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10195 CXXMoveAssignment, 10196 false); 10197 10198 // An implicitly-declared move assignment operator is an inline public 10199 // member of its class. 10200 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10201 SourceLocation ClassLoc = ClassDecl->getLocation(); 10202 DeclarationNameInfo NameInfo(Name, ClassLoc); 10203 CXXMethodDecl *MoveAssignment = 10204 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10205 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10206 /*isInline=*/true, Constexpr, SourceLocation()); 10207 MoveAssignment->setAccess(AS_public); 10208 MoveAssignment->setDefaulted(); 10209 MoveAssignment->setImplicit(); 10210 10211 if (getLangOpts().CUDA) { 10212 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10213 MoveAssignment, 10214 /* ConstRHS */ false, 10215 /* Diagnose */ false); 10216 } 10217 10218 // Build an exception specification pointing back at this member. 10219 FunctionProtoType::ExtProtoInfo EPI = 10220 getImplicitMethodEPI(*this, MoveAssignment); 10221 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10222 10223 // Add the parameter to the operator. 10224 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10225 ClassLoc, ClassLoc, 10226 /*Id=*/nullptr, ArgType, 10227 /*TInfo=*/nullptr, SC_None, 10228 nullptr); 10229 MoveAssignment->setParams(FromParam); 10230 10231 AddOverriddenMethods(ClassDecl, MoveAssignment); 10232 10233 MoveAssignment->setTrivial( 10234 ClassDecl->needsOverloadResolutionForMoveAssignment() 10235 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10236 : ClassDecl->hasTrivialMoveAssignment()); 10237 10238 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10239 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10240 SetDeclDeleted(MoveAssignment, ClassLoc); 10241 } 10242 10243 // Note that we have added this copy-assignment operator. 10244 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10245 10246 if (Scope *S = getScopeForContext(ClassDecl)) 10247 PushOnScopeChains(MoveAssignment, S, false); 10248 ClassDecl->addDecl(MoveAssignment); 10249 10250 return MoveAssignment; 10251 } 10252 10253 /// Check if we're implicitly defining a move assignment operator for a class 10254 /// with virtual bases. Such a move assignment might move-assign the virtual 10255 /// base multiple times. 10256 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10257 SourceLocation CurrentLocation) { 10258 assert(!Class->isDependentContext() && "should not define dependent move"); 10259 10260 // Only a virtual base could get implicitly move-assigned multiple times. 10261 // Only a non-trivial move assignment can observe this. We only want to 10262 // diagnose if we implicitly define an assignment operator that assigns 10263 // two base classes, both of which move-assign the same virtual base. 10264 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10265 Class->getNumBases() < 2) 10266 return; 10267 10268 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10269 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10270 VBaseMap VBases; 10271 10272 for (auto &BI : Class->bases()) { 10273 Worklist.push_back(&BI); 10274 while (!Worklist.empty()) { 10275 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10276 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10277 10278 // If the base has no non-trivial move assignment operators, 10279 // we don't care about moves from it. 10280 if (!Base->hasNonTrivialMoveAssignment()) 10281 continue; 10282 10283 // If there's nothing virtual here, skip it. 10284 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10285 continue; 10286 10287 // If we're not actually going to call a move assignment for this base, 10288 // or the selected move assignment is trivial, skip it. 10289 Sema::SpecialMemberOverloadResult *SMOR = 10290 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10291 /*ConstArg*/false, /*VolatileArg*/false, 10292 /*RValueThis*/true, /*ConstThis*/false, 10293 /*VolatileThis*/false); 10294 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10295 !SMOR->getMethod()->isMoveAssignmentOperator()) 10296 continue; 10297 10298 if (BaseSpec->isVirtual()) { 10299 // We're going to move-assign this virtual base, and its move 10300 // assignment operator is not trivial. If this can happen for 10301 // multiple distinct direct bases of Class, diagnose it. (If it 10302 // only happens in one base, we'll diagnose it when synthesizing 10303 // that base class's move assignment operator.) 10304 CXXBaseSpecifier *&Existing = 10305 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10306 .first->second; 10307 if (Existing && Existing != &BI) { 10308 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10309 << Class << Base; 10310 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10311 << (Base->getCanonicalDecl() == 10312 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10313 << Base << Existing->getType() << Existing->getSourceRange(); 10314 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10315 << (Base->getCanonicalDecl() == 10316 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10317 << Base << BI.getType() << BaseSpec->getSourceRange(); 10318 10319 // Only diagnose each vbase once. 10320 Existing = nullptr; 10321 } 10322 } else { 10323 // Only walk over bases that have defaulted move assignment operators. 10324 // We assume that any user-provided move assignment operator handles 10325 // the multiple-moves-of-vbase case itself somehow. 10326 if (!SMOR->getMethod()->isDefaulted()) 10327 continue; 10328 10329 // We're going to move the base classes of Base. Add them to the list. 10330 for (auto &BI : Base->bases()) 10331 Worklist.push_back(&BI); 10332 } 10333 } 10334 } 10335 } 10336 10337 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10338 CXXMethodDecl *MoveAssignOperator) { 10339 assert((MoveAssignOperator->isDefaulted() && 10340 MoveAssignOperator->isOverloadedOperator() && 10341 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10342 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10343 !MoveAssignOperator->isDeleted()) && 10344 "DefineImplicitMoveAssignment called for wrong function"); 10345 10346 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10347 10348 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10349 MoveAssignOperator->setInvalidDecl(); 10350 return; 10351 } 10352 10353 MoveAssignOperator->markUsed(Context); 10354 10355 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10356 DiagnosticErrorTrap Trap(Diags); 10357 10358 // C++0x [class.copy]p28: 10359 // The implicitly-defined or move assignment operator for a non-union class 10360 // X performs memberwise move assignment of its subobjects. The direct base 10361 // classes of X are assigned first, in the order of their declaration in the 10362 // base-specifier-list, and then the immediate non-static data members of X 10363 // are assigned, in the order in which they were declared in the class 10364 // definition. 10365 10366 // Issue a warning if our implicit move assignment operator will move 10367 // from a virtual base more than once. 10368 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10369 10370 // The statements that form the synthesized function body. 10371 SmallVector<Stmt*, 8> Statements; 10372 10373 // The parameter for the "other" object, which we are move from. 10374 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10375 QualType OtherRefType = Other->getType()-> 10376 getAs<RValueReferenceType>()->getPointeeType(); 10377 assert(!OtherRefType.getQualifiers() && 10378 "Bad argument type of defaulted move assignment"); 10379 10380 // Our location for everything implicitly-generated. 10381 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10382 ? MoveAssignOperator->getLocEnd() 10383 : MoveAssignOperator->getLocation(); 10384 10385 // Builds a reference to the "other" object. 10386 RefBuilder OtherRef(Other, OtherRefType); 10387 // Cast to rvalue. 10388 MoveCastBuilder MoveOther(OtherRef); 10389 10390 // Builds the "this" pointer. 10391 ThisBuilder This; 10392 10393 // Assign base classes. 10394 bool Invalid = false; 10395 for (auto &Base : ClassDecl->bases()) { 10396 // C++11 [class.copy]p28: 10397 // It is unspecified whether subobjects representing virtual base classes 10398 // are assigned more than once by the implicitly-defined copy assignment 10399 // operator. 10400 // FIXME: Do not assign to a vbase that will be assigned by some other base 10401 // class. For a move-assignment, this can result in the vbase being moved 10402 // multiple times. 10403 10404 // Form the assignment: 10405 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10406 QualType BaseType = Base.getType().getUnqualifiedType(); 10407 if (!BaseType->isRecordType()) { 10408 Invalid = true; 10409 continue; 10410 } 10411 10412 CXXCastPath BasePath; 10413 BasePath.push_back(&Base); 10414 10415 // Construct the "from" expression, which is an implicit cast to the 10416 // appropriately-qualified base type. 10417 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10418 10419 // Dereference "this". 10420 DerefBuilder DerefThis(This); 10421 10422 // Implicitly cast "this" to the appropriately-qualified base type. 10423 CastBuilder To(DerefThis, 10424 Context.getCVRQualifiedType( 10425 BaseType, MoveAssignOperator->getTypeQualifiers()), 10426 VK_LValue, BasePath); 10427 10428 // Build the move. 10429 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10430 To, From, 10431 /*CopyingBaseSubobject=*/true, 10432 /*Copying=*/false); 10433 if (Move.isInvalid()) { 10434 Diag(CurrentLocation, diag::note_member_synthesized_at) 10435 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10436 MoveAssignOperator->setInvalidDecl(); 10437 return; 10438 } 10439 10440 // Success! Record the move. 10441 Statements.push_back(Move.getAs<Expr>()); 10442 } 10443 10444 // Assign non-static members. 10445 for (auto *Field : ClassDecl->fields()) { 10446 if (Field->isUnnamedBitfield()) 10447 continue; 10448 10449 if (Field->isInvalidDecl()) { 10450 Invalid = true; 10451 continue; 10452 } 10453 10454 // Check for members of reference type; we can't move those. 10455 if (Field->getType()->isReferenceType()) { 10456 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10457 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10458 Diag(Field->getLocation(), diag::note_declared_at); 10459 Diag(CurrentLocation, diag::note_member_synthesized_at) 10460 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10461 Invalid = true; 10462 continue; 10463 } 10464 10465 // Check for members of const-qualified, non-class type. 10466 QualType BaseType = Context.getBaseElementType(Field->getType()); 10467 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10468 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10469 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10470 Diag(Field->getLocation(), diag::note_declared_at); 10471 Diag(CurrentLocation, diag::note_member_synthesized_at) 10472 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10473 Invalid = true; 10474 continue; 10475 } 10476 10477 // Suppress assigning zero-width bitfields. 10478 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10479 continue; 10480 10481 QualType FieldType = Field->getType().getNonReferenceType(); 10482 if (FieldType->isIncompleteArrayType()) { 10483 assert(ClassDecl->hasFlexibleArrayMember() && 10484 "Incomplete array type is not valid"); 10485 continue; 10486 } 10487 10488 // Build references to the field in the object we're copying from and to. 10489 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10490 LookupMemberName); 10491 MemberLookup.addDecl(Field); 10492 MemberLookup.resolveKind(); 10493 MemberBuilder From(MoveOther, OtherRefType, 10494 /*IsArrow=*/false, MemberLookup); 10495 MemberBuilder To(This, getCurrentThisType(), 10496 /*IsArrow=*/true, MemberLookup); 10497 10498 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10499 "Member reference with rvalue base must be rvalue except for reference " 10500 "members, which aren't allowed for move assignment."); 10501 10502 // Build the move of this field. 10503 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10504 To, From, 10505 /*CopyingBaseSubobject=*/false, 10506 /*Copying=*/false); 10507 if (Move.isInvalid()) { 10508 Diag(CurrentLocation, diag::note_member_synthesized_at) 10509 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10510 MoveAssignOperator->setInvalidDecl(); 10511 return; 10512 } 10513 10514 // Success! Record the copy. 10515 Statements.push_back(Move.getAs<Stmt>()); 10516 } 10517 10518 if (!Invalid) { 10519 // Add a "return *this;" 10520 ExprResult ThisObj = 10521 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10522 10523 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10524 if (Return.isInvalid()) 10525 Invalid = true; 10526 else { 10527 Statements.push_back(Return.getAs<Stmt>()); 10528 10529 if (Trap.hasErrorOccurred()) { 10530 Diag(CurrentLocation, diag::note_member_synthesized_at) 10531 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10532 Invalid = true; 10533 } 10534 } 10535 } 10536 10537 // The exception specification is needed because we are defining the 10538 // function. 10539 ResolveExceptionSpec(CurrentLocation, 10540 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10541 10542 if (Invalid) { 10543 MoveAssignOperator->setInvalidDecl(); 10544 return; 10545 } 10546 10547 StmtResult Body; 10548 { 10549 CompoundScopeRAII CompoundScope(*this); 10550 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10551 /*isStmtExpr=*/false); 10552 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10553 } 10554 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10555 10556 if (ASTMutationListener *L = getASTMutationListener()) { 10557 L->CompletedImplicitDefinition(MoveAssignOperator); 10558 } 10559 } 10560 10561 Sema::ImplicitExceptionSpecification 10562 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10563 CXXRecordDecl *ClassDecl = MD->getParent(); 10564 10565 ImplicitExceptionSpecification ExceptSpec(*this); 10566 if (ClassDecl->isInvalidDecl()) 10567 return ExceptSpec; 10568 10569 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10570 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10571 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10572 10573 // C++ [except.spec]p14: 10574 // An implicitly declared special member function (Clause 12) shall have an 10575 // exception-specification. [...] 10576 for (const auto &Base : ClassDecl->bases()) { 10577 // Virtual bases are handled below. 10578 if (Base.isVirtual()) 10579 continue; 10580 10581 CXXRecordDecl *BaseClassDecl 10582 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10583 if (CXXConstructorDecl *CopyConstructor = 10584 LookupCopyingConstructor(BaseClassDecl, Quals)) 10585 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10586 } 10587 for (const auto &Base : ClassDecl->vbases()) { 10588 CXXRecordDecl *BaseClassDecl 10589 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10590 if (CXXConstructorDecl *CopyConstructor = 10591 LookupCopyingConstructor(BaseClassDecl, Quals)) 10592 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10593 } 10594 for (const auto *Field : ClassDecl->fields()) { 10595 QualType FieldType = Context.getBaseElementType(Field->getType()); 10596 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10597 if (CXXConstructorDecl *CopyConstructor = 10598 LookupCopyingConstructor(FieldClassDecl, 10599 Quals | FieldType.getCVRQualifiers())) 10600 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10601 } 10602 } 10603 10604 return ExceptSpec; 10605 } 10606 10607 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10608 CXXRecordDecl *ClassDecl) { 10609 // C++ [class.copy]p4: 10610 // If the class definition does not explicitly declare a copy 10611 // constructor, one is declared implicitly. 10612 assert(ClassDecl->needsImplicitCopyConstructor()); 10613 10614 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10615 if (DSM.isAlreadyBeingDeclared()) 10616 return nullptr; 10617 10618 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10619 QualType ArgType = ClassType; 10620 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10621 if (Const) 10622 ArgType = ArgType.withConst(); 10623 ArgType = Context.getLValueReferenceType(ArgType); 10624 10625 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10626 CXXCopyConstructor, 10627 Const); 10628 10629 DeclarationName Name 10630 = Context.DeclarationNames.getCXXConstructorName( 10631 Context.getCanonicalType(ClassType)); 10632 SourceLocation ClassLoc = ClassDecl->getLocation(); 10633 DeclarationNameInfo NameInfo(Name, ClassLoc); 10634 10635 // An implicitly-declared copy constructor is an inline public 10636 // member of its class. 10637 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10638 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10639 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10640 Constexpr); 10641 CopyConstructor->setAccess(AS_public); 10642 CopyConstructor->setDefaulted(); 10643 10644 if (getLangOpts().CUDA) { 10645 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10646 CopyConstructor, 10647 /* ConstRHS */ Const, 10648 /* Diagnose */ false); 10649 } 10650 10651 // Build an exception specification pointing back at this member. 10652 FunctionProtoType::ExtProtoInfo EPI = 10653 getImplicitMethodEPI(*this, CopyConstructor); 10654 CopyConstructor->setType( 10655 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10656 10657 // Add the parameter to the constructor. 10658 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10659 ClassLoc, ClassLoc, 10660 /*IdentifierInfo=*/nullptr, 10661 ArgType, /*TInfo=*/nullptr, 10662 SC_None, nullptr); 10663 CopyConstructor->setParams(FromParam); 10664 10665 CopyConstructor->setTrivial( 10666 ClassDecl->needsOverloadResolutionForCopyConstructor() 10667 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10668 : ClassDecl->hasTrivialCopyConstructor()); 10669 10670 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10671 SetDeclDeleted(CopyConstructor, ClassLoc); 10672 10673 // Note that we have declared this constructor. 10674 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10675 10676 if (Scope *S = getScopeForContext(ClassDecl)) 10677 PushOnScopeChains(CopyConstructor, S, false); 10678 ClassDecl->addDecl(CopyConstructor); 10679 10680 return CopyConstructor; 10681 } 10682 10683 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10684 CXXConstructorDecl *CopyConstructor) { 10685 assert((CopyConstructor->isDefaulted() && 10686 CopyConstructor->isCopyConstructor() && 10687 !CopyConstructor->doesThisDeclarationHaveABody() && 10688 !CopyConstructor->isDeleted()) && 10689 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10690 10691 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10692 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10693 10694 // C++11 [class.copy]p7: 10695 // The [definition of an implicitly declared copy constructor] is 10696 // deprecated if the class has a user-declared copy assignment operator 10697 // or a user-declared destructor. 10698 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10699 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10700 10701 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10702 DiagnosticErrorTrap Trap(Diags); 10703 10704 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10705 Trap.hasErrorOccurred()) { 10706 Diag(CurrentLocation, diag::note_member_synthesized_at) 10707 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10708 CopyConstructor->setInvalidDecl(); 10709 } else { 10710 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10711 ? CopyConstructor->getLocEnd() 10712 : CopyConstructor->getLocation(); 10713 Sema::CompoundScopeRAII CompoundScope(*this); 10714 CopyConstructor->setBody( 10715 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10716 } 10717 10718 // The exception specification is needed because we are defining the 10719 // function. 10720 ResolveExceptionSpec(CurrentLocation, 10721 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10722 10723 CopyConstructor->markUsed(Context); 10724 MarkVTableUsed(CurrentLocation, ClassDecl); 10725 10726 if (ASTMutationListener *L = getASTMutationListener()) { 10727 L->CompletedImplicitDefinition(CopyConstructor); 10728 } 10729 } 10730 10731 Sema::ImplicitExceptionSpecification 10732 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10733 CXXRecordDecl *ClassDecl = MD->getParent(); 10734 10735 // C++ [except.spec]p14: 10736 // An implicitly declared special member function (Clause 12) shall have an 10737 // exception-specification. [...] 10738 ImplicitExceptionSpecification ExceptSpec(*this); 10739 if (ClassDecl->isInvalidDecl()) 10740 return ExceptSpec; 10741 10742 // Direct base-class constructors. 10743 for (const auto &B : ClassDecl->bases()) { 10744 if (B.isVirtual()) // Handled below. 10745 continue; 10746 10747 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10748 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10749 CXXConstructorDecl *Constructor = 10750 LookupMovingConstructor(BaseClassDecl, 0); 10751 // If this is a deleted function, add it anyway. This might be conformant 10752 // with the standard. This might not. I'm not sure. It might not matter. 10753 if (Constructor) 10754 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10755 } 10756 } 10757 10758 // Virtual base-class constructors. 10759 for (const auto &B : ClassDecl->vbases()) { 10760 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10761 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10762 CXXConstructorDecl *Constructor = 10763 LookupMovingConstructor(BaseClassDecl, 0); 10764 // If this is a deleted function, add it anyway. This might be conformant 10765 // with the standard. This might not. I'm not sure. It might not matter. 10766 if (Constructor) 10767 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10768 } 10769 } 10770 10771 // Field constructors. 10772 for (const auto *F : ClassDecl->fields()) { 10773 QualType FieldType = Context.getBaseElementType(F->getType()); 10774 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10775 CXXConstructorDecl *Constructor = 10776 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10777 // If this is a deleted function, add it anyway. This might be conformant 10778 // with the standard. This might not. I'm not sure. It might not matter. 10779 // In particular, the problem is that this function never gets called. It 10780 // might just be ill-formed because this function attempts to refer to 10781 // a deleted function here. 10782 if (Constructor) 10783 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10784 } 10785 } 10786 10787 return ExceptSpec; 10788 } 10789 10790 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10791 CXXRecordDecl *ClassDecl) { 10792 assert(ClassDecl->needsImplicitMoveConstructor()); 10793 10794 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10795 if (DSM.isAlreadyBeingDeclared()) 10796 return nullptr; 10797 10798 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10799 QualType ArgType = Context.getRValueReferenceType(ClassType); 10800 10801 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10802 CXXMoveConstructor, 10803 false); 10804 10805 DeclarationName Name 10806 = Context.DeclarationNames.getCXXConstructorName( 10807 Context.getCanonicalType(ClassType)); 10808 SourceLocation ClassLoc = ClassDecl->getLocation(); 10809 DeclarationNameInfo NameInfo(Name, ClassLoc); 10810 10811 // C++11 [class.copy]p11: 10812 // An implicitly-declared copy/move constructor is an inline public 10813 // member of its class. 10814 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10815 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10816 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10817 Constexpr); 10818 MoveConstructor->setAccess(AS_public); 10819 MoveConstructor->setDefaulted(); 10820 10821 if (getLangOpts().CUDA) { 10822 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 10823 MoveConstructor, 10824 /* ConstRHS */ false, 10825 /* Diagnose */ false); 10826 } 10827 10828 // Build an exception specification pointing back at this member. 10829 FunctionProtoType::ExtProtoInfo EPI = 10830 getImplicitMethodEPI(*this, MoveConstructor); 10831 MoveConstructor->setType( 10832 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10833 10834 // Add the parameter to the constructor. 10835 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10836 ClassLoc, ClassLoc, 10837 /*IdentifierInfo=*/nullptr, 10838 ArgType, /*TInfo=*/nullptr, 10839 SC_None, nullptr); 10840 MoveConstructor->setParams(FromParam); 10841 10842 MoveConstructor->setTrivial( 10843 ClassDecl->needsOverloadResolutionForMoveConstructor() 10844 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10845 : ClassDecl->hasTrivialMoveConstructor()); 10846 10847 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10848 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10849 SetDeclDeleted(MoveConstructor, ClassLoc); 10850 } 10851 10852 // Note that we have declared this constructor. 10853 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10854 10855 if (Scope *S = getScopeForContext(ClassDecl)) 10856 PushOnScopeChains(MoveConstructor, S, false); 10857 ClassDecl->addDecl(MoveConstructor); 10858 10859 return MoveConstructor; 10860 } 10861 10862 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10863 CXXConstructorDecl *MoveConstructor) { 10864 assert((MoveConstructor->isDefaulted() && 10865 MoveConstructor->isMoveConstructor() && 10866 !MoveConstructor->doesThisDeclarationHaveABody() && 10867 !MoveConstructor->isDeleted()) && 10868 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10869 10870 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10871 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10872 10873 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10874 DiagnosticErrorTrap Trap(Diags); 10875 10876 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10877 Trap.hasErrorOccurred()) { 10878 Diag(CurrentLocation, diag::note_member_synthesized_at) 10879 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10880 MoveConstructor->setInvalidDecl(); 10881 } else { 10882 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 10883 ? MoveConstructor->getLocEnd() 10884 : MoveConstructor->getLocation(); 10885 Sema::CompoundScopeRAII CompoundScope(*this); 10886 MoveConstructor->setBody(ActOnCompoundStmt( 10887 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 10888 } 10889 10890 // The exception specification is needed because we are defining the 10891 // function. 10892 ResolveExceptionSpec(CurrentLocation, 10893 MoveConstructor->getType()->castAs<FunctionProtoType>()); 10894 10895 MoveConstructor->markUsed(Context); 10896 MarkVTableUsed(CurrentLocation, ClassDecl); 10897 10898 if (ASTMutationListener *L = getASTMutationListener()) { 10899 L->CompletedImplicitDefinition(MoveConstructor); 10900 } 10901 } 10902 10903 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10904 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10905 } 10906 10907 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10908 SourceLocation CurrentLocation, 10909 CXXConversionDecl *Conv) { 10910 CXXRecordDecl *Lambda = Conv->getParent(); 10911 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10912 // If we are defining a specialization of a conversion to function-ptr 10913 // cache the deduced template arguments for this specialization 10914 // so that we can use them to retrieve the corresponding call-operator 10915 // and static-invoker. 10916 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 10917 10918 // Retrieve the corresponding call-operator specialization. 10919 if (Lambda->isGenericLambda()) { 10920 assert(Conv->isFunctionTemplateSpecialization()); 10921 FunctionTemplateDecl *CallOpTemplate = 10922 CallOp->getDescribedFunctionTemplate(); 10923 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10924 void *InsertPos = nullptr; 10925 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10926 DeducedTemplateArgs->asArray(), 10927 InsertPos); 10928 assert(CallOpSpec && 10929 "Conversion operator must have a corresponding call operator"); 10930 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10931 } 10932 // Mark the call operator referenced (and add to pending instantiations 10933 // if necessary). 10934 // For both the conversion and static-invoker template specializations 10935 // we construct their body's in this function, so no need to add them 10936 // to the PendingInstantiations. 10937 MarkFunctionReferenced(CurrentLocation, CallOp); 10938 10939 SynthesizedFunctionScope Scope(*this, Conv); 10940 DiagnosticErrorTrap Trap(Diags); 10941 10942 // Retrieve the static invoker... 10943 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10944 // ... and get the corresponding specialization for a generic lambda. 10945 if (Lambda->isGenericLambda()) { 10946 assert(DeducedTemplateArgs && 10947 "Must have deduced template arguments from Conversion Operator"); 10948 FunctionTemplateDecl *InvokeTemplate = 10949 Invoker->getDescribedFunctionTemplate(); 10950 void *InsertPos = nullptr; 10951 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10952 DeducedTemplateArgs->asArray(), 10953 InsertPos); 10954 assert(InvokeSpec && 10955 "Must have a corresponding static invoker specialization"); 10956 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10957 } 10958 // Construct the body of the conversion function { return __invoke; }. 10959 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10960 VK_LValue, Conv->getLocation()).get(); 10961 assert(FunctionRef && "Can't refer to __invoke function?"); 10962 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 10963 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10964 Conv->getLocation(), 10965 Conv->getLocation())); 10966 10967 Conv->markUsed(Context); 10968 Conv->setReferenced(); 10969 10970 // Fill in the __invoke function with a dummy implementation. IR generation 10971 // will fill in the actual details. 10972 Invoker->markUsed(Context); 10973 Invoker->setReferenced(); 10974 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10975 10976 if (ASTMutationListener *L = getASTMutationListener()) { 10977 L->CompletedImplicitDefinition(Conv); 10978 L->CompletedImplicitDefinition(Invoker); 10979 } 10980 } 10981 10982 10983 10984 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10985 SourceLocation CurrentLocation, 10986 CXXConversionDecl *Conv) 10987 { 10988 assert(!Conv->getParent()->isGenericLambda()); 10989 10990 Conv->markUsed(Context); 10991 10992 SynthesizedFunctionScope Scope(*this, Conv); 10993 DiagnosticErrorTrap Trap(Diags); 10994 10995 // Copy-initialize the lambda object as needed to capture it. 10996 Expr *This = ActOnCXXThis(CurrentLocation).get(); 10997 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 10998 10999 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11000 Conv->getLocation(), 11001 Conv, DerefThis); 11002 11003 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11004 // behavior. Note that only the general conversion function does this 11005 // (since it's unusable otherwise); in the case where we inline the 11006 // block literal, it has block literal lifetime semantics. 11007 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11008 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11009 CK_CopyAndAutoreleaseBlockObject, 11010 BuildBlock.get(), nullptr, VK_RValue); 11011 11012 if (BuildBlock.isInvalid()) { 11013 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11014 Conv->setInvalidDecl(); 11015 return; 11016 } 11017 11018 // Create the return statement that returns the block from the conversion 11019 // function. 11020 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11021 if (Return.isInvalid()) { 11022 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11023 Conv->setInvalidDecl(); 11024 return; 11025 } 11026 11027 // Set the body of the conversion function. 11028 Stmt *ReturnS = Return.get(); 11029 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11030 Conv->getLocation(), 11031 Conv->getLocation())); 11032 11033 // We're done; notify the mutation listener, if any. 11034 if (ASTMutationListener *L = getASTMutationListener()) { 11035 L->CompletedImplicitDefinition(Conv); 11036 } 11037 } 11038 11039 /// \brief Determine whether the given list arguments contains exactly one 11040 /// "real" (non-default) argument. 11041 static bool hasOneRealArgument(MultiExprArg Args) { 11042 switch (Args.size()) { 11043 case 0: 11044 return false; 11045 11046 default: 11047 if (!Args[1]->isDefaultArgument()) 11048 return false; 11049 11050 // fall through 11051 case 1: 11052 return !Args[0]->isDefaultArgument(); 11053 } 11054 11055 return false; 11056 } 11057 11058 ExprResult 11059 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11060 CXXConstructorDecl *Constructor, 11061 MultiExprArg ExprArgs, 11062 bool HadMultipleCandidates, 11063 bool IsListInitialization, 11064 bool IsStdInitListInitialization, 11065 bool RequiresZeroInit, 11066 unsigned ConstructKind, 11067 SourceRange ParenRange) { 11068 bool Elidable = false; 11069 11070 // C++0x [class.copy]p34: 11071 // When certain criteria are met, an implementation is allowed to 11072 // omit the copy/move construction of a class object, even if the 11073 // copy/move constructor and/or destructor for the object have 11074 // side effects. [...] 11075 // - when a temporary class object that has not been bound to a 11076 // reference (12.2) would be copied/moved to a class object 11077 // with the same cv-unqualified type, the copy/move operation 11078 // can be omitted by constructing the temporary object 11079 // directly into the target of the omitted copy/move 11080 if (ConstructKind == CXXConstructExpr::CK_Complete && 11081 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11082 Expr *SubExpr = ExprArgs[0]; 11083 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11084 } 11085 11086 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11087 Elidable, ExprArgs, HadMultipleCandidates, 11088 IsListInitialization, 11089 IsStdInitListInitialization, RequiresZeroInit, 11090 ConstructKind, ParenRange); 11091 } 11092 11093 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11094 /// including handling of its default argument expressions. 11095 ExprResult 11096 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11097 CXXConstructorDecl *Constructor, bool Elidable, 11098 MultiExprArg ExprArgs, 11099 bool HadMultipleCandidates, 11100 bool IsListInitialization, 11101 bool IsStdInitListInitialization, 11102 bool RequiresZeroInit, 11103 unsigned ConstructKind, 11104 SourceRange ParenRange) { 11105 MarkFunctionReferenced(ConstructLoc, Constructor); 11106 return CXXConstructExpr::Create( 11107 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11108 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11109 RequiresZeroInit, 11110 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11111 ParenRange); 11112 } 11113 11114 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11115 assert(Field->hasInClassInitializer()); 11116 11117 // If we already have the in-class initializer nothing needs to be done. 11118 if (Field->getInClassInitializer()) 11119 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11120 11121 // Maybe we haven't instantiated the in-class initializer. Go check the 11122 // pattern FieldDecl to see if it has one. 11123 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11124 11125 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11126 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11127 DeclContext::lookup_result Lookup = 11128 ClassPattern->lookup(Field->getDeclName()); 11129 assert(Lookup.size() == 1); 11130 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11131 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11132 getTemplateInstantiationArgs(Field))) 11133 return ExprError(); 11134 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11135 } 11136 11137 // DR1351: 11138 // If the brace-or-equal-initializer of a non-static data member 11139 // invokes a defaulted default constructor of its class or of an 11140 // enclosing class in a potentially evaluated subexpression, the 11141 // program is ill-formed. 11142 // 11143 // This resolution is unworkable: the exception specification of the 11144 // default constructor can be needed in an unevaluated context, in 11145 // particular, in the operand of a noexcept-expression, and we can be 11146 // unable to compute an exception specification for an enclosed class. 11147 // 11148 // Any attempt to resolve the exception specification of a defaulted default 11149 // constructor before the initializer is lexically complete will ultimately 11150 // come here at which point we can diagnose it. 11151 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11152 if (OutermostClass == ParentRD) { 11153 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11154 << ParentRD << Field; 11155 } else { 11156 Diag(Field->getLocEnd(), 11157 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11158 << ParentRD << OutermostClass << Field; 11159 } 11160 11161 return ExprError(); 11162 } 11163 11164 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11165 if (VD->isInvalidDecl()) return; 11166 11167 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11168 if (ClassDecl->isInvalidDecl()) return; 11169 if (ClassDecl->hasIrrelevantDestructor()) return; 11170 if (ClassDecl->isDependentContext()) return; 11171 11172 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11173 MarkFunctionReferenced(VD->getLocation(), Destructor); 11174 CheckDestructorAccess(VD->getLocation(), Destructor, 11175 PDiag(diag::err_access_dtor_var) 11176 << VD->getDeclName() 11177 << VD->getType()); 11178 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11179 11180 if (Destructor->isTrivial()) return; 11181 if (!VD->hasGlobalStorage()) return; 11182 11183 // Emit warning for non-trivial dtor in global scope (a real global, 11184 // class-static, function-static). 11185 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11186 11187 // TODO: this should be re-enabled for static locals by !CXAAtExit 11188 if (!VD->isStaticLocal()) 11189 Diag(VD->getLocation(), diag::warn_global_destructor); 11190 } 11191 11192 /// \brief Given a constructor and the set of arguments provided for the 11193 /// constructor, convert the arguments and add any required default arguments 11194 /// to form a proper call to this constructor. 11195 /// 11196 /// \returns true if an error occurred, false otherwise. 11197 bool 11198 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11199 MultiExprArg ArgsPtr, 11200 SourceLocation Loc, 11201 SmallVectorImpl<Expr*> &ConvertedArgs, 11202 bool AllowExplicit, 11203 bool IsListInitialization) { 11204 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11205 unsigned NumArgs = ArgsPtr.size(); 11206 Expr **Args = ArgsPtr.data(); 11207 11208 const FunctionProtoType *Proto 11209 = Constructor->getType()->getAs<FunctionProtoType>(); 11210 assert(Proto && "Constructor without a prototype?"); 11211 unsigned NumParams = Proto->getNumParams(); 11212 11213 // If too few arguments are available, we'll fill in the rest with defaults. 11214 if (NumArgs < NumParams) 11215 ConvertedArgs.reserve(NumParams); 11216 else 11217 ConvertedArgs.reserve(NumArgs); 11218 11219 VariadicCallType CallType = 11220 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11221 SmallVector<Expr *, 8> AllArgs; 11222 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11223 Proto, 0, 11224 llvm::makeArrayRef(Args, NumArgs), 11225 AllArgs, 11226 CallType, AllowExplicit, 11227 IsListInitialization); 11228 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11229 11230 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11231 11232 CheckConstructorCall(Constructor, 11233 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11234 Proto, Loc); 11235 11236 return Invalid; 11237 } 11238 11239 static inline bool 11240 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11241 const FunctionDecl *FnDecl) { 11242 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11243 if (isa<NamespaceDecl>(DC)) { 11244 return SemaRef.Diag(FnDecl->getLocation(), 11245 diag::err_operator_new_delete_declared_in_namespace) 11246 << FnDecl->getDeclName(); 11247 } 11248 11249 if (isa<TranslationUnitDecl>(DC) && 11250 FnDecl->getStorageClass() == SC_Static) { 11251 return SemaRef.Diag(FnDecl->getLocation(), 11252 diag::err_operator_new_delete_declared_static) 11253 << FnDecl->getDeclName(); 11254 } 11255 11256 return false; 11257 } 11258 11259 static inline bool 11260 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11261 CanQualType ExpectedResultType, 11262 CanQualType ExpectedFirstParamType, 11263 unsigned DependentParamTypeDiag, 11264 unsigned InvalidParamTypeDiag) { 11265 QualType ResultType = 11266 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11267 11268 // Check that the result type is not dependent. 11269 if (ResultType->isDependentType()) 11270 return SemaRef.Diag(FnDecl->getLocation(), 11271 diag::err_operator_new_delete_dependent_result_type) 11272 << FnDecl->getDeclName() << ExpectedResultType; 11273 11274 // Check that the result type is what we expect. 11275 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11276 return SemaRef.Diag(FnDecl->getLocation(), 11277 diag::err_operator_new_delete_invalid_result_type) 11278 << FnDecl->getDeclName() << ExpectedResultType; 11279 11280 // A function template must have at least 2 parameters. 11281 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11282 return SemaRef.Diag(FnDecl->getLocation(), 11283 diag::err_operator_new_delete_template_too_few_parameters) 11284 << FnDecl->getDeclName(); 11285 11286 // The function decl must have at least 1 parameter. 11287 if (FnDecl->getNumParams() == 0) 11288 return SemaRef.Diag(FnDecl->getLocation(), 11289 diag::err_operator_new_delete_too_few_parameters) 11290 << FnDecl->getDeclName(); 11291 11292 // Check the first parameter type is not dependent. 11293 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11294 if (FirstParamType->isDependentType()) 11295 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11296 << FnDecl->getDeclName() << ExpectedFirstParamType; 11297 11298 // Check that the first parameter type is what we expect. 11299 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11300 ExpectedFirstParamType) 11301 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11302 << FnDecl->getDeclName() << ExpectedFirstParamType; 11303 11304 return false; 11305 } 11306 11307 static bool 11308 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11309 // C++ [basic.stc.dynamic.allocation]p1: 11310 // A program is ill-formed if an allocation function is declared in a 11311 // namespace scope other than global scope or declared static in global 11312 // scope. 11313 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11314 return true; 11315 11316 CanQualType SizeTy = 11317 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11318 11319 // C++ [basic.stc.dynamic.allocation]p1: 11320 // The return type shall be void*. The first parameter shall have type 11321 // std::size_t. 11322 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11323 SizeTy, 11324 diag::err_operator_new_dependent_param_type, 11325 diag::err_operator_new_param_type)) 11326 return true; 11327 11328 // C++ [basic.stc.dynamic.allocation]p1: 11329 // The first parameter shall not have an associated default argument. 11330 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11331 return SemaRef.Diag(FnDecl->getLocation(), 11332 diag::err_operator_new_default_arg) 11333 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11334 11335 return false; 11336 } 11337 11338 static bool 11339 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11340 // C++ [basic.stc.dynamic.deallocation]p1: 11341 // A program is ill-formed if deallocation functions are declared in a 11342 // namespace scope other than global scope or declared static in global 11343 // scope. 11344 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11345 return true; 11346 11347 // C++ [basic.stc.dynamic.deallocation]p2: 11348 // Each deallocation function shall return void and its first parameter 11349 // shall be void*. 11350 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11351 SemaRef.Context.VoidPtrTy, 11352 diag::err_operator_delete_dependent_param_type, 11353 diag::err_operator_delete_param_type)) 11354 return true; 11355 11356 return false; 11357 } 11358 11359 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11360 /// of this overloaded operator is well-formed. If so, returns false; 11361 /// otherwise, emits appropriate diagnostics and returns true. 11362 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11363 assert(FnDecl && FnDecl->isOverloadedOperator() && 11364 "Expected an overloaded operator declaration"); 11365 11366 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11367 11368 // C++ [over.oper]p5: 11369 // The allocation and deallocation functions, operator new, 11370 // operator new[], operator delete and operator delete[], are 11371 // described completely in 3.7.3. The attributes and restrictions 11372 // found in the rest of this subclause do not apply to them unless 11373 // explicitly stated in 3.7.3. 11374 if (Op == OO_Delete || Op == OO_Array_Delete) 11375 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11376 11377 if (Op == OO_New || Op == OO_Array_New) 11378 return CheckOperatorNewDeclaration(*this, FnDecl); 11379 11380 // C++ [over.oper]p6: 11381 // An operator function shall either be a non-static member 11382 // function or be a non-member function and have at least one 11383 // parameter whose type is a class, a reference to a class, an 11384 // enumeration, or a reference to an enumeration. 11385 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11386 if (MethodDecl->isStatic()) 11387 return Diag(FnDecl->getLocation(), 11388 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11389 } else { 11390 bool ClassOrEnumParam = false; 11391 for (auto Param : FnDecl->params()) { 11392 QualType ParamType = Param->getType().getNonReferenceType(); 11393 if (ParamType->isDependentType() || ParamType->isRecordType() || 11394 ParamType->isEnumeralType()) { 11395 ClassOrEnumParam = true; 11396 break; 11397 } 11398 } 11399 11400 if (!ClassOrEnumParam) 11401 return Diag(FnDecl->getLocation(), 11402 diag::err_operator_overload_needs_class_or_enum) 11403 << FnDecl->getDeclName(); 11404 } 11405 11406 // C++ [over.oper]p8: 11407 // An operator function cannot have default arguments (8.3.6), 11408 // except where explicitly stated below. 11409 // 11410 // Only the function-call operator allows default arguments 11411 // (C++ [over.call]p1). 11412 if (Op != OO_Call) { 11413 for (auto Param : FnDecl->params()) { 11414 if (Param->hasDefaultArg()) 11415 return Diag(Param->getLocation(), 11416 diag::err_operator_overload_default_arg) 11417 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11418 } 11419 } 11420 11421 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11422 { false, false, false } 11423 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11424 , { Unary, Binary, MemberOnly } 11425 #include "clang/Basic/OperatorKinds.def" 11426 }; 11427 11428 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11429 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11430 bool MustBeMemberOperator = OperatorUses[Op][2]; 11431 11432 // C++ [over.oper]p8: 11433 // [...] Operator functions cannot have more or fewer parameters 11434 // than the number required for the corresponding operator, as 11435 // described in the rest of this subclause. 11436 unsigned NumParams = FnDecl->getNumParams() 11437 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11438 if (Op != OO_Call && 11439 ((NumParams == 1 && !CanBeUnaryOperator) || 11440 (NumParams == 2 && !CanBeBinaryOperator) || 11441 (NumParams < 1) || (NumParams > 2))) { 11442 // We have the wrong number of parameters. 11443 unsigned ErrorKind; 11444 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11445 ErrorKind = 2; // 2 -> unary or binary. 11446 } else if (CanBeUnaryOperator) { 11447 ErrorKind = 0; // 0 -> unary 11448 } else { 11449 assert(CanBeBinaryOperator && 11450 "All non-call overloaded operators are unary or binary!"); 11451 ErrorKind = 1; // 1 -> binary 11452 } 11453 11454 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11455 << FnDecl->getDeclName() << NumParams << ErrorKind; 11456 } 11457 11458 // Overloaded operators other than operator() cannot be variadic. 11459 if (Op != OO_Call && 11460 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11461 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11462 << FnDecl->getDeclName(); 11463 } 11464 11465 // Some operators must be non-static member functions. 11466 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11467 return Diag(FnDecl->getLocation(), 11468 diag::err_operator_overload_must_be_member) 11469 << FnDecl->getDeclName(); 11470 } 11471 11472 // C++ [over.inc]p1: 11473 // The user-defined function called operator++ implements the 11474 // prefix and postfix ++ operator. If this function is a member 11475 // function with no parameters, or a non-member function with one 11476 // parameter of class or enumeration type, it defines the prefix 11477 // increment operator ++ for objects of that type. If the function 11478 // is a member function with one parameter (which shall be of type 11479 // int) or a non-member function with two parameters (the second 11480 // of which shall be of type int), it defines the postfix 11481 // increment operator ++ for objects of that type. 11482 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11483 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11484 QualType ParamType = LastParam->getType(); 11485 11486 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11487 !ParamType->isDependentType()) 11488 return Diag(LastParam->getLocation(), 11489 diag::err_operator_overload_post_incdec_must_be_int) 11490 << LastParam->getType() << (Op == OO_MinusMinus); 11491 } 11492 11493 return false; 11494 } 11495 11496 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11497 /// of this literal operator function is well-formed. If so, returns 11498 /// false; otherwise, emits appropriate diagnostics and returns true. 11499 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11500 if (isa<CXXMethodDecl>(FnDecl)) { 11501 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11502 << FnDecl->getDeclName(); 11503 return true; 11504 } 11505 11506 if (FnDecl->isExternC()) { 11507 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11508 return true; 11509 } 11510 11511 bool Valid = false; 11512 11513 // This might be the definition of a literal operator template. 11514 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11515 // This might be a specialization of a literal operator template. 11516 if (!TpDecl) 11517 TpDecl = FnDecl->getPrimaryTemplate(); 11518 11519 // template <char...> type operator "" name() and 11520 // template <class T, T...> type operator "" name() are the only valid 11521 // template signatures, and the only valid signatures with no parameters. 11522 if (TpDecl) { 11523 if (FnDecl->param_size() == 0) { 11524 // Must have one or two template parameters 11525 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11526 if (Params->size() == 1) { 11527 NonTypeTemplateParmDecl *PmDecl = 11528 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11529 11530 // The template parameter must be a char parameter pack. 11531 if (PmDecl && PmDecl->isTemplateParameterPack() && 11532 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11533 Valid = true; 11534 } else if (Params->size() == 2) { 11535 TemplateTypeParmDecl *PmType = 11536 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11537 NonTypeTemplateParmDecl *PmArgs = 11538 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11539 11540 // The second template parameter must be a parameter pack with the 11541 // first template parameter as its type. 11542 if (PmType && PmArgs && 11543 !PmType->isTemplateParameterPack() && 11544 PmArgs->isTemplateParameterPack()) { 11545 const TemplateTypeParmType *TArgs = 11546 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11547 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11548 TArgs->getIndex() == PmType->getIndex()) { 11549 Valid = true; 11550 if (ActiveTemplateInstantiations.empty()) 11551 Diag(FnDecl->getLocation(), 11552 diag::ext_string_literal_operator_template); 11553 } 11554 } 11555 } 11556 } 11557 } else if (FnDecl->param_size()) { 11558 // Check the first parameter 11559 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11560 11561 QualType T = (*Param)->getType().getUnqualifiedType(); 11562 11563 // unsigned long long int, long double, and any character type are allowed 11564 // as the only parameters. 11565 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11566 Context.hasSameType(T, Context.LongDoubleTy) || 11567 Context.hasSameType(T, Context.CharTy) || 11568 Context.hasSameType(T, Context.WideCharTy) || 11569 Context.hasSameType(T, Context.Char16Ty) || 11570 Context.hasSameType(T, Context.Char32Ty)) { 11571 if (++Param == FnDecl->param_end()) 11572 Valid = true; 11573 goto FinishedParams; 11574 } 11575 11576 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11577 const PointerType *PT = T->getAs<PointerType>(); 11578 if (!PT) 11579 goto FinishedParams; 11580 T = PT->getPointeeType(); 11581 if (!T.isConstQualified() || T.isVolatileQualified()) 11582 goto FinishedParams; 11583 T = T.getUnqualifiedType(); 11584 11585 // Move on to the second parameter; 11586 ++Param; 11587 11588 // If there is no second parameter, the first must be a const char * 11589 if (Param == FnDecl->param_end()) { 11590 if (Context.hasSameType(T, Context.CharTy)) 11591 Valid = true; 11592 goto FinishedParams; 11593 } 11594 11595 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11596 // are allowed as the first parameter to a two-parameter function 11597 if (!(Context.hasSameType(T, Context.CharTy) || 11598 Context.hasSameType(T, Context.WideCharTy) || 11599 Context.hasSameType(T, Context.Char16Ty) || 11600 Context.hasSameType(T, Context.Char32Ty))) 11601 goto FinishedParams; 11602 11603 // The second and final parameter must be an std::size_t 11604 T = (*Param)->getType().getUnqualifiedType(); 11605 if (Context.hasSameType(T, Context.getSizeType()) && 11606 ++Param == FnDecl->param_end()) 11607 Valid = true; 11608 } 11609 11610 // FIXME: This diagnostic is absolutely terrible. 11611 FinishedParams: 11612 if (!Valid) { 11613 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11614 << FnDecl->getDeclName(); 11615 return true; 11616 } 11617 11618 // A parameter-declaration-clause containing a default argument is not 11619 // equivalent to any of the permitted forms. 11620 for (auto Param : FnDecl->params()) { 11621 if (Param->hasDefaultArg()) { 11622 Diag(Param->getDefaultArgRange().getBegin(), 11623 diag::err_literal_operator_default_argument) 11624 << Param->getDefaultArgRange(); 11625 break; 11626 } 11627 } 11628 11629 StringRef LiteralName 11630 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11631 if (LiteralName[0] != '_') { 11632 // C++11 [usrlit.suffix]p1: 11633 // Literal suffix identifiers that do not start with an underscore 11634 // are reserved for future standardization. 11635 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11636 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11637 } 11638 11639 return false; 11640 } 11641 11642 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11643 /// linkage specification, including the language and (if present) 11644 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11645 /// language string literal. LBraceLoc, if valid, provides the location of 11646 /// the '{' brace. Otherwise, this linkage specification does not 11647 /// have any braces. 11648 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11649 Expr *LangStr, 11650 SourceLocation LBraceLoc) { 11651 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11652 if (!Lit->isAscii()) { 11653 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11654 << LangStr->getSourceRange(); 11655 return nullptr; 11656 } 11657 11658 StringRef Lang = Lit->getString(); 11659 LinkageSpecDecl::LanguageIDs Language; 11660 if (Lang == "C") 11661 Language = LinkageSpecDecl::lang_c; 11662 else if (Lang == "C++") 11663 Language = LinkageSpecDecl::lang_cxx; 11664 else { 11665 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11666 << LangStr->getSourceRange(); 11667 return nullptr; 11668 } 11669 11670 // FIXME: Add all the various semantics of linkage specifications 11671 11672 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11673 LangStr->getExprLoc(), Language, 11674 LBraceLoc.isValid()); 11675 CurContext->addDecl(D); 11676 PushDeclContext(S, D); 11677 return D; 11678 } 11679 11680 /// ActOnFinishLinkageSpecification - Complete the definition of 11681 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11682 /// valid, it's the position of the closing '}' brace in a linkage 11683 /// specification that uses braces. 11684 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11685 Decl *LinkageSpec, 11686 SourceLocation RBraceLoc) { 11687 if (RBraceLoc.isValid()) { 11688 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11689 LSDecl->setRBraceLoc(RBraceLoc); 11690 } 11691 PopDeclContext(); 11692 return LinkageSpec; 11693 } 11694 11695 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11696 AttributeList *AttrList, 11697 SourceLocation SemiLoc) { 11698 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11699 // Attribute declarations appertain to empty declaration so we handle 11700 // them here. 11701 if (AttrList) 11702 ProcessDeclAttributeList(S, ED, AttrList); 11703 11704 CurContext->addDecl(ED); 11705 return ED; 11706 } 11707 11708 /// \brief Perform semantic analysis for the variable declaration that 11709 /// occurs within a C++ catch clause, returning the newly-created 11710 /// variable. 11711 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11712 TypeSourceInfo *TInfo, 11713 SourceLocation StartLoc, 11714 SourceLocation Loc, 11715 IdentifierInfo *Name) { 11716 bool Invalid = false; 11717 QualType ExDeclType = TInfo->getType(); 11718 11719 // Arrays and functions decay. 11720 if (ExDeclType->isArrayType()) 11721 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11722 else if (ExDeclType->isFunctionType()) 11723 ExDeclType = Context.getPointerType(ExDeclType); 11724 11725 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11726 // The exception-declaration shall not denote a pointer or reference to an 11727 // incomplete type, other than [cv] void*. 11728 // N2844 forbids rvalue references. 11729 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11730 Diag(Loc, diag::err_catch_rvalue_ref); 11731 Invalid = true; 11732 } 11733 11734 QualType BaseType = ExDeclType; 11735 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11736 unsigned DK = diag::err_catch_incomplete; 11737 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11738 BaseType = Ptr->getPointeeType(); 11739 Mode = 1; 11740 DK = diag::err_catch_incomplete_ptr; 11741 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11742 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11743 BaseType = Ref->getPointeeType(); 11744 Mode = 2; 11745 DK = diag::err_catch_incomplete_ref; 11746 } 11747 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11748 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11749 Invalid = true; 11750 11751 if (!Invalid && !ExDeclType->isDependentType() && 11752 RequireNonAbstractType(Loc, ExDeclType, 11753 diag::err_abstract_type_in_decl, 11754 AbstractVariableType)) 11755 Invalid = true; 11756 11757 // Only the non-fragile NeXT runtime currently supports C++ catches 11758 // of ObjC types, and no runtime supports catching ObjC types by value. 11759 if (!Invalid && getLangOpts().ObjC1) { 11760 QualType T = ExDeclType; 11761 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11762 T = RT->getPointeeType(); 11763 11764 if (T->isObjCObjectType()) { 11765 Diag(Loc, diag::err_objc_object_catch); 11766 Invalid = true; 11767 } else if (T->isObjCObjectPointerType()) { 11768 // FIXME: should this be a test for macosx-fragile specifically? 11769 if (getLangOpts().ObjCRuntime.isFragile()) 11770 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11771 } 11772 } 11773 11774 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11775 ExDeclType, TInfo, SC_None); 11776 ExDecl->setExceptionVariable(true); 11777 11778 // In ARC, infer 'retaining' for variables of retainable type. 11779 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11780 Invalid = true; 11781 11782 if (!Invalid && !ExDeclType->isDependentType()) { 11783 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11784 // Insulate this from anything else we might currently be parsing. 11785 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11786 11787 // C++ [except.handle]p16: 11788 // The object declared in an exception-declaration or, if the 11789 // exception-declaration does not specify a name, a temporary (12.2) is 11790 // copy-initialized (8.5) from the exception object. [...] 11791 // The object is destroyed when the handler exits, after the destruction 11792 // of any automatic objects initialized within the handler. 11793 // 11794 // We just pretend to initialize the object with itself, then make sure 11795 // it can be destroyed later. 11796 QualType initType = ExDeclType; 11797 11798 InitializedEntity entity = 11799 InitializedEntity::InitializeVariable(ExDecl); 11800 InitializationKind initKind = 11801 InitializationKind::CreateCopy(Loc, SourceLocation()); 11802 11803 Expr *opaqueValue = 11804 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11805 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11806 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11807 if (result.isInvalid()) 11808 Invalid = true; 11809 else { 11810 // If the constructor used was non-trivial, set this as the 11811 // "initializer". 11812 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11813 if (!construct->getConstructor()->isTrivial()) { 11814 Expr *init = MaybeCreateExprWithCleanups(construct); 11815 ExDecl->setInit(init); 11816 } 11817 11818 // And make sure it's destructable. 11819 FinalizeVarWithDestructor(ExDecl, recordType); 11820 } 11821 } 11822 } 11823 11824 if (Invalid) 11825 ExDecl->setInvalidDecl(); 11826 11827 return ExDecl; 11828 } 11829 11830 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11831 /// handler. 11832 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11833 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11834 bool Invalid = D.isInvalidType(); 11835 11836 // Check for unexpanded parameter packs. 11837 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11838 UPPC_ExceptionType)) { 11839 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11840 D.getIdentifierLoc()); 11841 Invalid = true; 11842 } 11843 11844 IdentifierInfo *II = D.getIdentifier(); 11845 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11846 LookupOrdinaryName, 11847 ForRedeclaration)) { 11848 // The scope should be freshly made just for us. There is just no way 11849 // it contains any previous declaration, except for function parameters in 11850 // a function-try-block's catch statement. 11851 assert(!S->isDeclScope(PrevDecl)); 11852 if (isDeclInScope(PrevDecl, CurContext, S)) { 11853 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11854 << D.getIdentifier(); 11855 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11856 Invalid = true; 11857 } else if (PrevDecl->isTemplateParameter()) 11858 // Maybe we will complain about the shadowed template parameter. 11859 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11860 } 11861 11862 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11863 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11864 << D.getCXXScopeSpec().getRange(); 11865 Invalid = true; 11866 } 11867 11868 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11869 D.getLocStart(), 11870 D.getIdentifierLoc(), 11871 D.getIdentifier()); 11872 if (Invalid) 11873 ExDecl->setInvalidDecl(); 11874 11875 // Add the exception declaration into this scope. 11876 if (II) 11877 PushOnScopeChains(ExDecl, S); 11878 else 11879 CurContext->addDecl(ExDecl); 11880 11881 ProcessDeclAttributes(S, ExDecl, D); 11882 return ExDecl; 11883 } 11884 11885 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11886 Expr *AssertExpr, 11887 Expr *AssertMessageExpr, 11888 SourceLocation RParenLoc) { 11889 StringLiteral *AssertMessage = 11890 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 11891 11892 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11893 return nullptr; 11894 11895 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11896 AssertMessage, RParenLoc, false); 11897 } 11898 11899 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11900 Expr *AssertExpr, 11901 StringLiteral *AssertMessage, 11902 SourceLocation RParenLoc, 11903 bool Failed) { 11904 assert(AssertExpr != nullptr && "Expected non-null condition"); 11905 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11906 !Failed) { 11907 // In a static_assert-declaration, the constant-expression shall be a 11908 // constant expression that can be contextually converted to bool. 11909 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11910 if (Converted.isInvalid()) 11911 Failed = true; 11912 11913 llvm::APSInt Cond; 11914 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11915 diag::err_static_assert_expression_is_not_constant, 11916 /*AllowFold=*/false).isInvalid()) 11917 Failed = true; 11918 11919 if (!Failed && !Cond) { 11920 SmallString<256> MsgBuffer; 11921 llvm::raw_svector_ostream Msg(MsgBuffer); 11922 if (AssertMessage) 11923 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 11924 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11925 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 11926 Failed = true; 11927 } 11928 } 11929 11930 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11931 AssertExpr, AssertMessage, RParenLoc, 11932 Failed); 11933 11934 CurContext->addDecl(Decl); 11935 return Decl; 11936 } 11937 11938 /// \brief Perform semantic analysis of the given friend type declaration. 11939 /// 11940 /// \returns A friend declaration that. 11941 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11942 SourceLocation FriendLoc, 11943 TypeSourceInfo *TSInfo) { 11944 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11945 11946 QualType T = TSInfo->getType(); 11947 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11948 11949 // C++03 [class.friend]p2: 11950 // An elaborated-type-specifier shall be used in a friend declaration 11951 // for a class.* 11952 // 11953 // * The class-key of the elaborated-type-specifier is required. 11954 if (!ActiveTemplateInstantiations.empty()) { 11955 // Do not complain about the form of friend template types during 11956 // template instantiation; we will already have complained when the 11957 // template was declared. 11958 } else { 11959 if (!T->isElaboratedTypeSpecifier()) { 11960 // If we evaluated the type to a record type, suggest putting 11961 // a tag in front. 11962 if (const RecordType *RT = T->getAs<RecordType>()) { 11963 RecordDecl *RD = RT->getDecl(); 11964 11965 SmallString<16> InsertionText(" "); 11966 InsertionText += RD->getKindName(); 11967 11968 Diag(TypeRange.getBegin(), 11969 getLangOpts().CPlusPlus11 ? 11970 diag::warn_cxx98_compat_unelaborated_friend_type : 11971 diag::ext_unelaborated_friend_type) 11972 << (unsigned) RD->getTagKind() 11973 << T 11974 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11975 InsertionText); 11976 } else { 11977 Diag(FriendLoc, 11978 getLangOpts().CPlusPlus11 ? 11979 diag::warn_cxx98_compat_nonclass_type_friend : 11980 diag::ext_nonclass_type_friend) 11981 << T 11982 << TypeRange; 11983 } 11984 } else if (T->getAs<EnumType>()) { 11985 Diag(FriendLoc, 11986 getLangOpts().CPlusPlus11 ? 11987 diag::warn_cxx98_compat_enum_friend : 11988 diag::ext_enum_friend) 11989 << T 11990 << TypeRange; 11991 } 11992 11993 // C++11 [class.friend]p3: 11994 // A friend declaration that does not declare a function shall have one 11995 // of the following forms: 11996 // friend elaborated-type-specifier ; 11997 // friend simple-type-specifier ; 11998 // friend typename-specifier ; 11999 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12000 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12001 } 12002 12003 // If the type specifier in a friend declaration designates a (possibly 12004 // cv-qualified) class type, that class is declared as a friend; otherwise, 12005 // the friend declaration is ignored. 12006 return FriendDecl::Create(Context, CurContext, 12007 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12008 FriendLoc); 12009 } 12010 12011 /// Handle a friend tag declaration where the scope specifier was 12012 /// templated. 12013 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12014 unsigned TagSpec, SourceLocation TagLoc, 12015 CXXScopeSpec &SS, 12016 IdentifierInfo *Name, 12017 SourceLocation NameLoc, 12018 AttributeList *Attr, 12019 MultiTemplateParamsArg TempParamLists) { 12020 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12021 12022 bool isExplicitSpecialization = false; 12023 bool Invalid = false; 12024 12025 if (TemplateParameterList *TemplateParams = 12026 MatchTemplateParametersToScopeSpecifier( 12027 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12028 isExplicitSpecialization, Invalid)) { 12029 if (TemplateParams->size() > 0) { 12030 // This is a declaration of a class template. 12031 if (Invalid) 12032 return nullptr; 12033 12034 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12035 NameLoc, Attr, TemplateParams, AS_public, 12036 /*ModulePrivateLoc=*/SourceLocation(), 12037 FriendLoc, TempParamLists.size() - 1, 12038 TempParamLists.data()).get(); 12039 } else { 12040 // The "template<>" header is extraneous. 12041 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12042 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12043 isExplicitSpecialization = true; 12044 } 12045 } 12046 12047 if (Invalid) return nullptr; 12048 12049 bool isAllExplicitSpecializations = true; 12050 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12051 if (TempParamLists[I]->size()) { 12052 isAllExplicitSpecializations = false; 12053 break; 12054 } 12055 } 12056 12057 // FIXME: don't ignore attributes. 12058 12059 // If it's explicit specializations all the way down, just forget 12060 // about the template header and build an appropriate non-templated 12061 // friend. TODO: for source fidelity, remember the headers. 12062 if (isAllExplicitSpecializations) { 12063 if (SS.isEmpty()) { 12064 bool Owned = false; 12065 bool IsDependent = false; 12066 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12067 Attr, AS_public, 12068 /*ModulePrivateLoc=*/SourceLocation(), 12069 MultiTemplateParamsArg(), Owned, IsDependent, 12070 /*ScopedEnumKWLoc=*/SourceLocation(), 12071 /*ScopedEnumUsesClassTag=*/false, 12072 /*UnderlyingType=*/TypeResult(), 12073 /*IsTypeSpecifier=*/false); 12074 } 12075 12076 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12077 ElaboratedTypeKeyword Keyword 12078 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12079 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12080 *Name, NameLoc); 12081 if (T.isNull()) 12082 return nullptr; 12083 12084 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12085 if (isa<DependentNameType>(T)) { 12086 DependentNameTypeLoc TL = 12087 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12088 TL.setElaboratedKeywordLoc(TagLoc); 12089 TL.setQualifierLoc(QualifierLoc); 12090 TL.setNameLoc(NameLoc); 12091 } else { 12092 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12093 TL.setElaboratedKeywordLoc(TagLoc); 12094 TL.setQualifierLoc(QualifierLoc); 12095 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12096 } 12097 12098 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12099 TSI, FriendLoc, TempParamLists); 12100 Friend->setAccess(AS_public); 12101 CurContext->addDecl(Friend); 12102 return Friend; 12103 } 12104 12105 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12106 12107 12108 12109 // Handle the case of a templated-scope friend class. e.g. 12110 // template <class T> class A<T>::B; 12111 // FIXME: we don't support these right now. 12112 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12113 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12114 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12115 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12116 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12117 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12118 TL.setElaboratedKeywordLoc(TagLoc); 12119 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12120 TL.setNameLoc(NameLoc); 12121 12122 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12123 TSI, FriendLoc, TempParamLists); 12124 Friend->setAccess(AS_public); 12125 Friend->setUnsupportedFriend(true); 12126 CurContext->addDecl(Friend); 12127 return Friend; 12128 } 12129 12130 12131 /// Handle a friend type declaration. This works in tandem with 12132 /// ActOnTag. 12133 /// 12134 /// Notes on friend class templates: 12135 /// 12136 /// We generally treat friend class declarations as if they were 12137 /// declaring a class. So, for example, the elaborated type specifier 12138 /// in a friend declaration is required to obey the restrictions of a 12139 /// class-head (i.e. no typedefs in the scope chain), template 12140 /// parameters are required to match up with simple template-ids, &c. 12141 /// However, unlike when declaring a template specialization, it's 12142 /// okay to refer to a template specialization without an empty 12143 /// template parameter declaration, e.g. 12144 /// friend class A<T>::B<unsigned>; 12145 /// We permit this as a special case; if there are any template 12146 /// parameters present at all, require proper matching, i.e. 12147 /// template <> template \<class T> friend class A<int>::B; 12148 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12149 MultiTemplateParamsArg TempParams) { 12150 SourceLocation Loc = DS.getLocStart(); 12151 12152 assert(DS.isFriendSpecified()); 12153 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12154 12155 // Try to convert the decl specifier to a type. This works for 12156 // friend templates because ActOnTag never produces a ClassTemplateDecl 12157 // for a TUK_Friend. 12158 Declarator TheDeclarator(DS, Declarator::MemberContext); 12159 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12160 QualType T = TSI->getType(); 12161 if (TheDeclarator.isInvalidType()) 12162 return nullptr; 12163 12164 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12165 return nullptr; 12166 12167 // This is definitely an error in C++98. It's probably meant to 12168 // be forbidden in C++0x, too, but the specification is just 12169 // poorly written. 12170 // 12171 // The problem is with declarations like the following: 12172 // template <T> friend A<T>::foo; 12173 // where deciding whether a class C is a friend or not now hinges 12174 // on whether there exists an instantiation of A that causes 12175 // 'foo' to equal C. There are restrictions on class-heads 12176 // (which we declare (by fiat) elaborated friend declarations to 12177 // be) that makes this tractable. 12178 // 12179 // FIXME: handle "template <> friend class A<T>;", which 12180 // is possibly well-formed? Who even knows? 12181 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12182 Diag(Loc, diag::err_tagless_friend_type_template) 12183 << DS.getSourceRange(); 12184 return nullptr; 12185 } 12186 12187 // C++98 [class.friend]p1: A friend of a class is a function 12188 // or class that is not a member of the class . . . 12189 // This is fixed in DR77, which just barely didn't make the C++03 12190 // deadline. It's also a very silly restriction that seriously 12191 // affects inner classes and which nobody else seems to implement; 12192 // thus we never diagnose it, not even in -pedantic. 12193 // 12194 // But note that we could warn about it: it's always useless to 12195 // friend one of your own members (it's not, however, worthless to 12196 // friend a member of an arbitrary specialization of your template). 12197 12198 Decl *D; 12199 if (unsigned NumTempParamLists = TempParams.size()) 12200 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12201 NumTempParamLists, 12202 TempParams.data(), 12203 TSI, 12204 DS.getFriendSpecLoc()); 12205 else 12206 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12207 12208 if (!D) 12209 return nullptr; 12210 12211 D->setAccess(AS_public); 12212 CurContext->addDecl(D); 12213 12214 return D; 12215 } 12216 12217 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12218 MultiTemplateParamsArg TemplateParams) { 12219 const DeclSpec &DS = D.getDeclSpec(); 12220 12221 assert(DS.isFriendSpecified()); 12222 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12223 12224 SourceLocation Loc = D.getIdentifierLoc(); 12225 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12226 12227 // C++ [class.friend]p1 12228 // A friend of a class is a function or class.... 12229 // Note that this sees through typedefs, which is intended. 12230 // It *doesn't* see through dependent types, which is correct 12231 // according to [temp.arg.type]p3: 12232 // If a declaration acquires a function type through a 12233 // type dependent on a template-parameter and this causes 12234 // a declaration that does not use the syntactic form of a 12235 // function declarator to have a function type, the program 12236 // is ill-formed. 12237 if (!TInfo->getType()->isFunctionType()) { 12238 Diag(Loc, diag::err_unexpected_friend); 12239 12240 // It might be worthwhile to try to recover by creating an 12241 // appropriate declaration. 12242 return nullptr; 12243 } 12244 12245 // C++ [namespace.memdef]p3 12246 // - If a friend declaration in a non-local class first declares a 12247 // class or function, the friend class or function is a member 12248 // of the innermost enclosing namespace. 12249 // - The name of the friend is not found by simple name lookup 12250 // until a matching declaration is provided in that namespace 12251 // scope (either before or after the class declaration granting 12252 // friendship). 12253 // - If a friend function is called, its name may be found by the 12254 // name lookup that considers functions from namespaces and 12255 // classes associated with the types of the function arguments. 12256 // - When looking for a prior declaration of a class or a function 12257 // declared as a friend, scopes outside the innermost enclosing 12258 // namespace scope are not considered. 12259 12260 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12261 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12262 DeclarationName Name = NameInfo.getName(); 12263 assert(Name); 12264 12265 // Check for unexpanded parameter packs. 12266 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12267 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12268 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12269 return nullptr; 12270 12271 // The context we found the declaration in, or in which we should 12272 // create the declaration. 12273 DeclContext *DC; 12274 Scope *DCScope = S; 12275 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12276 ForRedeclaration); 12277 12278 // There are five cases here. 12279 // - There's no scope specifier and we're in a local class. Only look 12280 // for functions declared in the immediately-enclosing block scope. 12281 // We recover from invalid scope qualifiers as if they just weren't there. 12282 FunctionDecl *FunctionContainingLocalClass = nullptr; 12283 if ((SS.isInvalid() || !SS.isSet()) && 12284 (FunctionContainingLocalClass = 12285 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12286 // C++11 [class.friend]p11: 12287 // If a friend declaration appears in a local class and the name 12288 // specified is an unqualified name, a prior declaration is 12289 // looked up without considering scopes that are outside the 12290 // innermost enclosing non-class scope. For a friend function 12291 // declaration, if there is no prior declaration, the program is 12292 // ill-formed. 12293 12294 // Find the innermost enclosing non-class scope. This is the block 12295 // scope containing the local class definition (or for a nested class, 12296 // the outer local class). 12297 DCScope = S->getFnParent(); 12298 12299 // Look up the function name in the scope. 12300 Previous.clear(LookupLocalFriendName); 12301 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12302 12303 if (!Previous.empty()) { 12304 // All possible previous declarations must have the same context: 12305 // either they were declared at block scope or they are members of 12306 // one of the enclosing local classes. 12307 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12308 } else { 12309 // This is ill-formed, but provide the context that we would have 12310 // declared the function in, if we were permitted to, for error recovery. 12311 DC = FunctionContainingLocalClass; 12312 } 12313 adjustContextForLocalExternDecl(DC); 12314 12315 // C++ [class.friend]p6: 12316 // A function can be defined in a friend declaration of a class if and 12317 // only if the class is a non-local class (9.8), the function name is 12318 // unqualified, and the function has namespace scope. 12319 if (D.isFunctionDefinition()) { 12320 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12321 } 12322 12323 // - There's no scope specifier, in which case we just go to the 12324 // appropriate scope and look for a function or function template 12325 // there as appropriate. 12326 } else if (SS.isInvalid() || !SS.isSet()) { 12327 // C++11 [namespace.memdef]p3: 12328 // If the name in a friend declaration is neither qualified nor 12329 // a template-id and the declaration is a function or an 12330 // elaborated-type-specifier, the lookup to determine whether 12331 // the entity has been previously declared shall not consider 12332 // any scopes outside the innermost enclosing namespace. 12333 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12334 12335 // Find the appropriate context according to the above. 12336 DC = CurContext; 12337 12338 // Skip class contexts. If someone can cite chapter and verse 12339 // for this behavior, that would be nice --- it's what GCC and 12340 // EDG do, and it seems like a reasonable intent, but the spec 12341 // really only says that checks for unqualified existing 12342 // declarations should stop at the nearest enclosing namespace, 12343 // not that they should only consider the nearest enclosing 12344 // namespace. 12345 while (DC->isRecord()) 12346 DC = DC->getParent(); 12347 12348 DeclContext *LookupDC = DC; 12349 while (LookupDC->isTransparentContext()) 12350 LookupDC = LookupDC->getParent(); 12351 12352 while (true) { 12353 LookupQualifiedName(Previous, LookupDC); 12354 12355 if (!Previous.empty()) { 12356 DC = LookupDC; 12357 break; 12358 } 12359 12360 if (isTemplateId) { 12361 if (isa<TranslationUnitDecl>(LookupDC)) break; 12362 } else { 12363 if (LookupDC->isFileContext()) break; 12364 } 12365 LookupDC = LookupDC->getParent(); 12366 } 12367 12368 DCScope = getScopeForDeclContext(S, DC); 12369 12370 // - There's a non-dependent scope specifier, in which case we 12371 // compute it and do a previous lookup there for a function 12372 // or function template. 12373 } else if (!SS.getScopeRep()->isDependent()) { 12374 DC = computeDeclContext(SS); 12375 if (!DC) return nullptr; 12376 12377 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12378 12379 LookupQualifiedName(Previous, DC); 12380 12381 // Ignore things found implicitly in the wrong scope. 12382 // TODO: better diagnostics for this case. Suggesting the right 12383 // qualified scope would be nice... 12384 LookupResult::Filter F = Previous.makeFilter(); 12385 while (F.hasNext()) { 12386 NamedDecl *D = F.next(); 12387 if (!DC->InEnclosingNamespaceSetOf( 12388 D->getDeclContext()->getRedeclContext())) 12389 F.erase(); 12390 } 12391 F.done(); 12392 12393 if (Previous.empty()) { 12394 D.setInvalidType(); 12395 Diag(Loc, diag::err_qualified_friend_not_found) 12396 << Name << TInfo->getType(); 12397 return nullptr; 12398 } 12399 12400 // C++ [class.friend]p1: A friend of a class is a function or 12401 // class that is not a member of the class . . . 12402 if (DC->Equals(CurContext)) 12403 Diag(DS.getFriendSpecLoc(), 12404 getLangOpts().CPlusPlus11 ? 12405 diag::warn_cxx98_compat_friend_is_member : 12406 diag::err_friend_is_member); 12407 12408 if (D.isFunctionDefinition()) { 12409 // C++ [class.friend]p6: 12410 // A function can be defined in a friend declaration of a class if and 12411 // only if the class is a non-local class (9.8), the function name is 12412 // unqualified, and the function has namespace scope. 12413 SemaDiagnosticBuilder DB 12414 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12415 12416 DB << SS.getScopeRep(); 12417 if (DC->isFileContext()) 12418 DB << FixItHint::CreateRemoval(SS.getRange()); 12419 SS.clear(); 12420 } 12421 12422 // - There's a scope specifier that does not match any template 12423 // parameter lists, in which case we use some arbitrary context, 12424 // create a method or method template, and wait for instantiation. 12425 // - There's a scope specifier that does match some template 12426 // parameter lists, which we don't handle right now. 12427 } else { 12428 if (D.isFunctionDefinition()) { 12429 // C++ [class.friend]p6: 12430 // A function can be defined in a friend declaration of a class if and 12431 // only if the class is a non-local class (9.8), the function name is 12432 // unqualified, and the function has namespace scope. 12433 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12434 << SS.getScopeRep(); 12435 } 12436 12437 DC = CurContext; 12438 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12439 } 12440 12441 if (!DC->isRecord()) { 12442 // This implies that it has to be an operator or function. 12443 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12444 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12445 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12446 Diag(Loc, diag::err_introducing_special_friend) << 12447 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12448 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12449 return nullptr; 12450 } 12451 } 12452 12453 // FIXME: This is an egregious hack to cope with cases where the scope stack 12454 // does not contain the declaration context, i.e., in an out-of-line 12455 // definition of a class. 12456 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12457 if (!DCScope) { 12458 FakeDCScope.setEntity(DC); 12459 DCScope = &FakeDCScope; 12460 } 12461 12462 bool AddToScope = true; 12463 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12464 TemplateParams, AddToScope); 12465 if (!ND) return nullptr; 12466 12467 assert(ND->getLexicalDeclContext() == CurContext); 12468 12469 // If we performed typo correction, we might have added a scope specifier 12470 // and changed the decl context. 12471 DC = ND->getDeclContext(); 12472 12473 // Add the function declaration to the appropriate lookup tables, 12474 // adjusting the redeclarations list as necessary. We don't 12475 // want to do this yet if the friending class is dependent. 12476 // 12477 // Also update the scope-based lookup if the target context's 12478 // lookup context is in lexical scope. 12479 if (!CurContext->isDependentContext()) { 12480 DC = DC->getRedeclContext(); 12481 DC->makeDeclVisibleInContext(ND); 12482 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12483 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12484 } 12485 12486 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12487 D.getIdentifierLoc(), ND, 12488 DS.getFriendSpecLoc()); 12489 FrD->setAccess(AS_public); 12490 CurContext->addDecl(FrD); 12491 12492 if (ND->isInvalidDecl()) { 12493 FrD->setInvalidDecl(); 12494 } else { 12495 if (DC->isRecord()) CheckFriendAccess(ND); 12496 12497 FunctionDecl *FD; 12498 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12499 FD = FTD->getTemplatedDecl(); 12500 else 12501 FD = cast<FunctionDecl>(ND); 12502 12503 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12504 // default argument expression, that declaration shall be a definition 12505 // and shall be the only declaration of the function or function 12506 // template in the translation unit. 12507 if (functionDeclHasDefaultArgument(FD)) { 12508 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12509 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12510 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12511 } else if (!D.isFunctionDefinition()) 12512 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12513 } 12514 12515 // Mark templated-scope function declarations as unsupported. 12516 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12517 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12518 << SS.getScopeRep() << SS.getRange() 12519 << cast<CXXRecordDecl>(CurContext); 12520 FrD->setUnsupportedFriend(true); 12521 } 12522 } 12523 12524 return ND; 12525 } 12526 12527 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12528 AdjustDeclIfTemplate(Dcl); 12529 12530 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12531 if (!Fn) { 12532 Diag(DelLoc, diag::err_deleted_non_function); 12533 return; 12534 } 12535 12536 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12537 // Don't consider the implicit declaration we generate for explicit 12538 // specializations. FIXME: Do not generate these implicit declarations. 12539 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12540 Prev->getPreviousDecl()) && 12541 !Prev->isDefined()) { 12542 Diag(DelLoc, diag::err_deleted_decl_not_first); 12543 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12544 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12545 : diag::note_previous_declaration); 12546 } 12547 // If the declaration wasn't the first, we delete the function anyway for 12548 // recovery. 12549 Fn = Fn->getCanonicalDecl(); 12550 } 12551 12552 // dllimport/dllexport cannot be deleted. 12553 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12554 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12555 Fn->setInvalidDecl(); 12556 } 12557 12558 if (Fn->isDeleted()) 12559 return; 12560 12561 // See if we're deleting a function which is already known to override a 12562 // non-deleted virtual function. 12563 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12564 bool IssuedDiagnostic = false; 12565 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12566 E = MD->end_overridden_methods(); 12567 I != E; ++I) { 12568 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12569 if (!IssuedDiagnostic) { 12570 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12571 IssuedDiagnostic = true; 12572 } 12573 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12574 } 12575 } 12576 } 12577 12578 // C++11 [basic.start.main]p3: 12579 // A program that defines main as deleted [...] is ill-formed. 12580 if (Fn->isMain()) 12581 Diag(DelLoc, diag::err_deleted_main); 12582 12583 Fn->setDeletedAsWritten(); 12584 } 12585 12586 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12587 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12588 12589 if (MD) { 12590 if (MD->getParent()->isDependentType()) { 12591 MD->setDefaulted(); 12592 MD->setExplicitlyDefaulted(); 12593 return; 12594 } 12595 12596 CXXSpecialMember Member = getSpecialMember(MD); 12597 if (Member == CXXInvalid) { 12598 if (!MD->isInvalidDecl()) 12599 Diag(DefaultLoc, diag::err_default_special_members); 12600 return; 12601 } 12602 12603 MD->setDefaulted(); 12604 MD->setExplicitlyDefaulted(); 12605 12606 // If this definition appears within the record, do the checking when 12607 // the record is complete. 12608 const FunctionDecl *Primary = MD; 12609 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12610 // Find the uninstantiated declaration that actually had the '= default' 12611 // on it. 12612 Pattern->isDefined(Primary); 12613 12614 // If the method was defaulted on its first declaration, we will have 12615 // already performed the checking in CheckCompletedCXXClass. Such a 12616 // declaration doesn't trigger an implicit definition. 12617 if (Primary == Primary->getCanonicalDecl()) 12618 return; 12619 12620 CheckExplicitlyDefaultedSpecialMember(MD); 12621 12622 if (MD->isInvalidDecl()) 12623 return; 12624 12625 switch (Member) { 12626 case CXXDefaultConstructor: 12627 DefineImplicitDefaultConstructor(DefaultLoc, 12628 cast<CXXConstructorDecl>(MD)); 12629 break; 12630 case CXXCopyConstructor: 12631 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12632 break; 12633 case CXXCopyAssignment: 12634 DefineImplicitCopyAssignment(DefaultLoc, MD); 12635 break; 12636 case CXXDestructor: 12637 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12638 break; 12639 case CXXMoveConstructor: 12640 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12641 break; 12642 case CXXMoveAssignment: 12643 DefineImplicitMoveAssignment(DefaultLoc, MD); 12644 break; 12645 case CXXInvalid: 12646 llvm_unreachable("Invalid special member."); 12647 } 12648 } else { 12649 Diag(DefaultLoc, diag::err_default_special_members); 12650 } 12651 } 12652 12653 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12654 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12655 Stmt *SubStmt = *CI; 12656 if (!SubStmt) 12657 continue; 12658 if (isa<ReturnStmt>(SubStmt)) 12659 Self.Diag(SubStmt->getLocStart(), 12660 diag::err_return_in_constructor_handler); 12661 if (!isa<Expr>(SubStmt)) 12662 SearchForReturnInStmt(Self, SubStmt); 12663 } 12664 } 12665 12666 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12667 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12668 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12669 SearchForReturnInStmt(*this, Handler); 12670 } 12671 } 12672 12673 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12674 const CXXMethodDecl *Old) { 12675 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12676 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12677 12678 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12679 12680 // If the calling conventions match, everything is fine 12681 if (NewCC == OldCC) 12682 return false; 12683 12684 // If the calling conventions mismatch because the new function is static, 12685 // suppress the calling convention mismatch error; the error about static 12686 // function override (err_static_overrides_virtual from 12687 // Sema::CheckFunctionDeclaration) is more clear. 12688 if (New->getStorageClass() == SC_Static) 12689 return false; 12690 12691 Diag(New->getLocation(), 12692 diag::err_conflicting_overriding_cc_attributes) 12693 << New->getDeclName() << New->getType() << Old->getType(); 12694 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12695 return true; 12696 } 12697 12698 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12699 const CXXMethodDecl *Old) { 12700 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12701 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12702 12703 if (Context.hasSameType(NewTy, OldTy) || 12704 NewTy->isDependentType() || OldTy->isDependentType()) 12705 return false; 12706 12707 // Check if the return types are covariant 12708 QualType NewClassTy, OldClassTy; 12709 12710 /// Both types must be pointers or references to classes. 12711 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12712 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12713 NewClassTy = NewPT->getPointeeType(); 12714 OldClassTy = OldPT->getPointeeType(); 12715 } 12716 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12717 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12718 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12719 NewClassTy = NewRT->getPointeeType(); 12720 OldClassTy = OldRT->getPointeeType(); 12721 } 12722 } 12723 } 12724 12725 // The return types aren't either both pointers or references to a class type. 12726 if (NewClassTy.isNull()) { 12727 Diag(New->getLocation(), 12728 diag::err_different_return_type_for_overriding_virtual_function) 12729 << New->getDeclName() << NewTy << OldTy 12730 << New->getReturnTypeSourceRange(); 12731 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12732 << Old->getReturnTypeSourceRange(); 12733 12734 return true; 12735 } 12736 12737 // C++ [class.virtual]p6: 12738 // If the return type of D::f differs from the return type of B::f, the 12739 // class type in the return type of D::f shall be complete at the point of 12740 // declaration of D::f or shall be the class type D. 12741 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12742 if (!RT->isBeingDefined() && 12743 RequireCompleteType(New->getLocation(), NewClassTy, 12744 diag::err_covariant_return_incomplete, 12745 New->getDeclName())) 12746 return true; 12747 } 12748 12749 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12750 // Check if the new class derives from the old class. 12751 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12752 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12753 << New->getDeclName() << NewTy << OldTy 12754 << New->getReturnTypeSourceRange(); 12755 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12756 << Old->getReturnTypeSourceRange(); 12757 return true; 12758 } 12759 12760 // Check if we the conversion from derived to base is valid. 12761 if (CheckDerivedToBaseConversion( 12762 NewClassTy, OldClassTy, 12763 diag::err_covariant_return_inaccessible_base, 12764 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12765 New->getLocation(), New->getReturnTypeSourceRange(), 12766 New->getDeclName(), nullptr)) { 12767 // FIXME: this note won't trigger for delayed access control 12768 // diagnostics, and it's impossible to get an undelayed error 12769 // here from access control during the original parse because 12770 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12771 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12772 << Old->getReturnTypeSourceRange(); 12773 return true; 12774 } 12775 } 12776 12777 // The qualifiers of the return types must be the same. 12778 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12779 Diag(New->getLocation(), 12780 diag::err_covariant_return_type_different_qualifications) 12781 << New->getDeclName() << NewTy << OldTy 12782 << New->getReturnTypeSourceRange(); 12783 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12784 << Old->getReturnTypeSourceRange(); 12785 return true; 12786 }; 12787 12788 12789 // The new class type must have the same or less qualifiers as the old type. 12790 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12791 Diag(New->getLocation(), 12792 diag::err_covariant_return_type_class_type_more_qualified) 12793 << New->getDeclName() << NewTy << OldTy 12794 << New->getReturnTypeSourceRange(); 12795 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12796 << Old->getReturnTypeSourceRange(); 12797 return true; 12798 }; 12799 12800 return false; 12801 } 12802 12803 /// \brief Mark the given method pure. 12804 /// 12805 /// \param Method the method to be marked pure. 12806 /// 12807 /// \param InitRange the source range that covers the "0" initializer. 12808 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12809 SourceLocation EndLoc = InitRange.getEnd(); 12810 if (EndLoc.isValid()) 12811 Method->setRangeEnd(EndLoc); 12812 12813 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12814 Method->setPure(); 12815 return false; 12816 } 12817 12818 if (!Method->isInvalidDecl()) 12819 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12820 << Method->getDeclName() << InitRange; 12821 return true; 12822 } 12823 12824 /// \brief Determine whether the given declaration is a static data member. 12825 static bool isStaticDataMember(const Decl *D) { 12826 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12827 return Var->isStaticDataMember(); 12828 12829 return false; 12830 } 12831 12832 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12833 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12834 /// is a fresh scope pushed for just this purpose. 12835 /// 12836 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12837 /// static data member of class X, names should be looked up in the scope of 12838 /// class X. 12839 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12840 // If there is no declaration, there was an error parsing it. 12841 if (!D || D->isInvalidDecl()) 12842 return; 12843 12844 // We will always have a nested name specifier here, but this declaration 12845 // might not be out of line if the specifier names the current namespace: 12846 // extern int n; 12847 // int ::n = 0; 12848 if (D->isOutOfLine()) 12849 EnterDeclaratorContext(S, D->getDeclContext()); 12850 12851 // If we are parsing the initializer for a static data member, push a 12852 // new expression evaluation context that is associated with this static 12853 // data member. 12854 if (isStaticDataMember(D)) 12855 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12856 } 12857 12858 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12859 /// initializer for the out-of-line declaration 'D'. 12860 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12861 // If there is no declaration, there was an error parsing it. 12862 if (!D || D->isInvalidDecl()) 12863 return; 12864 12865 if (isStaticDataMember(D)) 12866 PopExpressionEvaluationContext(); 12867 12868 if (D->isOutOfLine()) 12869 ExitDeclaratorContext(S); 12870 } 12871 12872 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12873 /// C++ if/switch/while/for statement. 12874 /// e.g: "if (int x = f()) {...}" 12875 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12876 // C++ 6.4p2: 12877 // The declarator shall not specify a function or an array. 12878 // The type-specifier-seq shall not contain typedef and shall not declare a 12879 // new class or enumeration. 12880 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12881 "Parser allowed 'typedef' as storage class of condition decl."); 12882 12883 Decl *Dcl = ActOnDeclarator(S, D); 12884 if (!Dcl) 12885 return true; 12886 12887 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12888 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12889 << D.getSourceRange(); 12890 return true; 12891 } 12892 12893 return Dcl; 12894 } 12895 12896 void Sema::LoadExternalVTableUses() { 12897 if (!ExternalSource) 12898 return; 12899 12900 SmallVector<ExternalVTableUse, 4> VTables; 12901 ExternalSource->ReadUsedVTables(VTables); 12902 SmallVector<VTableUse, 4> NewUses; 12903 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12904 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12905 = VTablesUsed.find(VTables[I].Record); 12906 // Even if a definition wasn't required before, it may be required now. 12907 if (Pos != VTablesUsed.end()) { 12908 if (!Pos->second && VTables[I].DefinitionRequired) 12909 Pos->second = true; 12910 continue; 12911 } 12912 12913 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12914 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12915 } 12916 12917 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12918 } 12919 12920 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12921 bool DefinitionRequired) { 12922 // Ignore any vtable uses in unevaluated operands or for classes that do 12923 // not have a vtable. 12924 if (!Class->isDynamicClass() || Class->isDependentContext() || 12925 CurContext->isDependentContext() || isUnevaluatedContext()) 12926 return; 12927 12928 // Try to insert this class into the map. 12929 LoadExternalVTableUses(); 12930 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12931 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12932 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12933 if (!Pos.second) { 12934 // If we already had an entry, check to see if we are promoting this vtable 12935 // to required a definition. If so, we need to reappend to the VTableUses 12936 // list, since we may have already processed the first entry. 12937 if (DefinitionRequired && !Pos.first->second) { 12938 Pos.first->second = true; 12939 } else { 12940 // Otherwise, we can early exit. 12941 return; 12942 } 12943 } else { 12944 // The Microsoft ABI requires that we perform the destructor body 12945 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12946 // the deleting destructor is emitted with the vtable, not with the 12947 // destructor definition as in the Itanium ABI. 12948 // If it has a definition, we do the check at that point instead. 12949 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12950 Class->hasUserDeclaredDestructor() && 12951 !Class->getDestructor()->isDefined() && 12952 !Class->getDestructor()->isDeleted()) { 12953 CXXDestructorDecl *DD = Class->getDestructor(); 12954 ContextRAII SavedContext(*this, DD); 12955 CheckDestructor(DD); 12956 } 12957 } 12958 12959 // Local classes need to have their virtual members marked 12960 // immediately. For all other classes, we mark their virtual members 12961 // at the end of the translation unit. 12962 if (Class->isLocalClass()) 12963 MarkVirtualMembersReferenced(Loc, Class); 12964 else 12965 VTableUses.push_back(std::make_pair(Class, Loc)); 12966 } 12967 12968 bool Sema::DefineUsedVTables() { 12969 LoadExternalVTableUses(); 12970 if (VTableUses.empty()) 12971 return false; 12972 12973 // Note: The VTableUses vector could grow as a result of marking 12974 // the members of a class as "used", so we check the size each 12975 // time through the loop and prefer indices (which are stable) to 12976 // iterators (which are not). 12977 bool DefinedAnything = false; 12978 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12979 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12980 if (!Class) 12981 continue; 12982 12983 SourceLocation Loc = VTableUses[I].second; 12984 12985 bool DefineVTable = true; 12986 12987 // If this class has a key function, but that key function is 12988 // defined in another translation unit, we don't need to emit the 12989 // vtable even though we're using it. 12990 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12991 if (KeyFunction && !KeyFunction->hasBody()) { 12992 // The key function is in another translation unit. 12993 DefineVTable = false; 12994 TemplateSpecializationKind TSK = 12995 KeyFunction->getTemplateSpecializationKind(); 12996 assert(TSK != TSK_ExplicitInstantiationDefinition && 12997 TSK != TSK_ImplicitInstantiation && 12998 "Instantiations don't have key functions"); 12999 (void)TSK; 13000 } else if (!KeyFunction) { 13001 // If we have a class with no key function that is the subject 13002 // of an explicit instantiation declaration, suppress the 13003 // vtable; it will live with the explicit instantiation 13004 // definition. 13005 bool IsExplicitInstantiationDeclaration 13006 = Class->getTemplateSpecializationKind() 13007 == TSK_ExplicitInstantiationDeclaration; 13008 for (auto R : Class->redecls()) { 13009 TemplateSpecializationKind TSK 13010 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13011 if (TSK == TSK_ExplicitInstantiationDeclaration) 13012 IsExplicitInstantiationDeclaration = true; 13013 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13014 IsExplicitInstantiationDeclaration = false; 13015 break; 13016 } 13017 } 13018 13019 if (IsExplicitInstantiationDeclaration) 13020 DefineVTable = false; 13021 } 13022 13023 // The exception specifications for all virtual members may be needed even 13024 // if we are not providing an authoritative form of the vtable in this TU. 13025 // We may choose to emit it available_externally anyway. 13026 if (!DefineVTable) { 13027 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13028 continue; 13029 } 13030 13031 // Mark all of the virtual members of this class as referenced, so 13032 // that we can build a vtable. Then, tell the AST consumer that a 13033 // vtable for this class is required. 13034 DefinedAnything = true; 13035 MarkVirtualMembersReferenced(Loc, Class); 13036 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13037 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 13038 13039 // Optionally warn if we're emitting a weak vtable. 13040 if (Class->isExternallyVisible() && 13041 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13042 const FunctionDecl *KeyFunctionDef = nullptr; 13043 if (!KeyFunction || 13044 (KeyFunction->hasBody(KeyFunctionDef) && 13045 KeyFunctionDef->isInlined())) 13046 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13047 TSK_ExplicitInstantiationDefinition 13048 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13049 << Class; 13050 } 13051 } 13052 VTableUses.clear(); 13053 13054 return DefinedAnything; 13055 } 13056 13057 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13058 const CXXRecordDecl *RD) { 13059 for (const auto *I : RD->methods()) 13060 if (I->isVirtual() && !I->isPure()) 13061 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13062 } 13063 13064 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13065 const CXXRecordDecl *RD) { 13066 // Mark all functions which will appear in RD's vtable as used. 13067 CXXFinalOverriderMap FinalOverriders; 13068 RD->getFinalOverriders(FinalOverriders); 13069 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13070 E = FinalOverriders.end(); 13071 I != E; ++I) { 13072 for (OverridingMethods::const_iterator OI = I->second.begin(), 13073 OE = I->second.end(); 13074 OI != OE; ++OI) { 13075 assert(OI->second.size() > 0 && "no final overrider"); 13076 CXXMethodDecl *Overrider = OI->second.front().Method; 13077 13078 // C++ [basic.def.odr]p2: 13079 // [...] A virtual member function is used if it is not pure. [...] 13080 if (!Overrider->isPure()) 13081 MarkFunctionReferenced(Loc, Overrider); 13082 } 13083 } 13084 13085 // Only classes that have virtual bases need a VTT. 13086 if (RD->getNumVBases() == 0) 13087 return; 13088 13089 for (const auto &I : RD->bases()) { 13090 const CXXRecordDecl *Base = 13091 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13092 if (Base->getNumVBases() == 0) 13093 continue; 13094 MarkVirtualMembersReferenced(Loc, Base); 13095 } 13096 } 13097 13098 /// SetIvarInitializers - This routine builds initialization ASTs for the 13099 /// Objective-C implementation whose ivars need be initialized. 13100 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13101 if (!getLangOpts().CPlusPlus) 13102 return; 13103 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13104 SmallVector<ObjCIvarDecl*, 8> ivars; 13105 CollectIvarsToConstructOrDestruct(OID, ivars); 13106 if (ivars.empty()) 13107 return; 13108 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13109 for (unsigned i = 0; i < ivars.size(); i++) { 13110 FieldDecl *Field = ivars[i]; 13111 if (Field->isInvalidDecl()) 13112 continue; 13113 13114 CXXCtorInitializer *Member; 13115 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13116 InitializationKind InitKind = 13117 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13118 13119 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13120 ExprResult MemberInit = 13121 InitSeq.Perform(*this, InitEntity, InitKind, None); 13122 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13123 // Note, MemberInit could actually come back empty if no initialization 13124 // is required (e.g., because it would call a trivial default constructor) 13125 if (!MemberInit.get() || MemberInit.isInvalid()) 13126 continue; 13127 13128 Member = 13129 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13130 SourceLocation(), 13131 MemberInit.getAs<Expr>(), 13132 SourceLocation()); 13133 AllToInit.push_back(Member); 13134 13135 // Be sure that the destructor is accessible and is marked as referenced. 13136 if (const RecordType *RecordTy = 13137 Context.getBaseElementType(Field->getType()) 13138 ->getAs<RecordType>()) { 13139 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13140 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13141 MarkFunctionReferenced(Field->getLocation(), Destructor); 13142 CheckDestructorAccess(Field->getLocation(), Destructor, 13143 PDiag(diag::err_access_dtor_ivar) 13144 << Context.getBaseElementType(Field->getType())); 13145 } 13146 } 13147 } 13148 ObjCImplementation->setIvarInitializers(Context, 13149 AllToInit.data(), AllToInit.size()); 13150 } 13151 } 13152 13153 static 13154 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13155 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13156 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13157 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13158 Sema &S) { 13159 if (Ctor->isInvalidDecl()) 13160 return; 13161 13162 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13163 13164 // Target may not be determinable yet, for instance if this is a dependent 13165 // call in an uninstantiated template. 13166 if (Target) { 13167 const FunctionDecl *FNTarget = nullptr; 13168 (void)Target->hasBody(FNTarget); 13169 Target = const_cast<CXXConstructorDecl*>( 13170 cast_or_null<CXXConstructorDecl>(FNTarget)); 13171 } 13172 13173 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13174 // Avoid dereferencing a null pointer here. 13175 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13176 13177 if (!Current.insert(Canonical).second) 13178 return; 13179 13180 // We know that beyond here, we aren't chaining into a cycle. 13181 if (!Target || !Target->isDelegatingConstructor() || 13182 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13183 Valid.insert(Current.begin(), Current.end()); 13184 Current.clear(); 13185 // We've hit a cycle. 13186 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13187 Current.count(TCanonical)) { 13188 // If we haven't diagnosed this cycle yet, do so now. 13189 if (!Invalid.count(TCanonical)) { 13190 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13191 diag::warn_delegating_ctor_cycle) 13192 << Ctor; 13193 13194 // Don't add a note for a function delegating directly to itself. 13195 if (TCanonical != Canonical) 13196 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13197 13198 CXXConstructorDecl *C = Target; 13199 while (C->getCanonicalDecl() != Canonical) { 13200 const FunctionDecl *FNTarget = nullptr; 13201 (void)C->getTargetConstructor()->hasBody(FNTarget); 13202 assert(FNTarget && "Ctor cycle through bodiless function"); 13203 13204 C = const_cast<CXXConstructorDecl*>( 13205 cast<CXXConstructorDecl>(FNTarget)); 13206 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13207 } 13208 } 13209 13210 Invalid.insert(Current.begin(), Current.end()); 13211 Current.clear(); 13212 } else { 13213 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13214 } 13215 } 13216 13217 13218 void Sema::CheckDelegatingCtorCycles() { 13219 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13220 13221 for (DelegatingCtorDeclsType::iterator 13222 I = DelegatingCtorDecls.begin(ExternalSource), 13223 E = DelegatingCtorDecls.end(); 13224 I != E; ++I) 13225 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13226 13227 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13228 CE = Invalid.end(); 13229 CI != CE; ++CI) 13230 (*CI)->setInvalidDecl(); 13231 } 13232 13233 namespace { 13234 /// \brief AST visitor that finds references to the 'this' expression. 13235 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13236 Sema &S; 13237 13238 public: 13239 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13240 13241 bool VisitCXXThisExpr(CXXThisExpr *E) { 13242 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13243 << E->isImplicit(); 13244 return false; 13245 } 13246 }; 13247 } 13248 13249 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13250 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13251 if (!TSInfo) 13252 return false; 13253 13254 TypeLoc TL = TSInfo->getTypeLoc(); 13255 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13256 if (!ProtoTL) 13257 return false; 13258 13259 // C++11 [expr.prim.general]p3: 13260 // [The expression this] shall not appear before the optional 13261 // cv-qualifier-seq and it shall not appear within the declaration of a 13262 // static member function (although its type and value category are defined 13263 // within a static member function as they are within a non-static member 13264 // function). [ Note: this is because declaration matching does not occur 13265 // until the complete declarator is known. - end note ] 13266 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13267 FindCXXThisExpr Finder(*this); 13268 13269 // If the return type came after the cv-qualifier-seq, check it now. 13270 if (Proto->hasTrailingReturn() && 13271 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13272 return true; 13273 13274 // Check the exception specification. 13275 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13276 return true; 13277 13278 return checkThisInStaticMemberFunctionAttributes(Method); 13279 } 13280 13281 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13282 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13283 if (!TSInfo) 13284 return false; 13285 13286 TypeLoc TL = TSInfo->getTypeLoc(); 13287 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13288 if (!ProtoTL) 13289 return false; 13290 13291 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13292 FindCXXThisExpr Finder(*this); 13293 13294 switch (Proto->getExceptionSpecType()) { 13295 case EST_Unparsed: 13296 case EST_Uninstantiated: 13297 case EST_Unevaluated: 13298 case EST_BasicNoexcept: 13299 case EST_DynamicNone: 13300 case EST_MSAny: 13301 case EST_None: 13302 break; 13303 13304 case EST_ComputedNoexcept: 13305 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13306 return true; 13307 13308 case EST_Dynamic: 13309 for (const auto &E : Proto->exceptions()) { 13310 if (!Finder.TraverseType(E)) 13311 return true; 13312 } 13313 break; 13314 } 13315 13316 return false; 13317 } 13318 13319 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13320 FindCXXThisExpr Finder(*this); 13321 13322 // Check attributes. 13323 for (const auto *A : Method->attrs()) { 13324 // FIXME: This should be emitted by tblgen. 13325 Expr *Arg = nullptr; 13326 ArrayRef<Expr *> Args; 13327 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13328 Arg = G->getArg(); 13329 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13330 Arg = G->getArg(); 13331 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13332 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13333 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13334 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13335 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13336 Arg = ETLF->getSuccessValue(); 13337 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13338 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13339 Arg = STLF->getSuccessValue(); 13340 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13341 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13342 Arg = LR->getArg(); 13343 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13344 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13345 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13346 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13347 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13348 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13349 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13350 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13351 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13352 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13353 13354 if (Arg && !Finder.TraverseStmt(Arg)) 13355 return true; 13356 13357 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13358 if (!Finder.TraverseStmt(Args[I])) 13359 return true; 13360 } 13361 } 13362 13363 return false; 13364 } 13365 13366 void Sema::checkExceptionSpecification( 13367 bool IsTopLevel, ExceptionSpecificationType EST, 13368 ArrayRef<ParsedType> DynamicExceptions, 13369 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13370 SmallVectorImpl<QualType> &Exceptions, 13371 FunctionProtoType::ExceptionSpecInfo &ESI) { 13372 Exceptions.clear(); 13373 ESI.Type = EST; 13374 if (EST == EST_Dynamic) { 13375 Exceptions.reserve(DynamicExceptions.size()); 13376 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13377 // FIXME: Preserve type source info. 13378 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13379 13380 if (IsTopLevel) { 13381 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13382 collectUnexpandedParameterPacks(ET, Unexpanded); 13383 if (!Unexpanded.empty()) { 13384 DiagnoseUnexpandedParameterPacks( 13385 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13386 Unexpanded); 13387 continue; 13388 } 13389 } 13390 13391 // Check that the type is valid for an exception spec, and 13392 // drop it if not. 13393 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13394 Exceptions.push_back(ET); 13395 } 13396 ESI.Exceptions = Exceptions; 13397 return; 13398 } 13399 13400 if (EST == EST_ComputedNoexcept) { 13401 // If an error occurred, there's no expression here. 13402 if (NoexceptExpr) { 13403 assert((NoexceptExpr->isTypeDependent() || 13404 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13405 Context.BoolTy) && 13406 "Parser should have made sure that the expression is boolean"); 13407 if (IsTopLevel && NoexceptExpr && 13408 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13409 ESI.Type = EST_BasicNoexcept; 13410 return; 13411 } 13412 13413 if (!NoexceptExpr->isValueDependent()) 13414 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13415 diag::err_noexcept_needs_constant_expression, 13416 /*AllowFold*/ false).get(); 13417 ESI.NoexceptExpr = NoexceptExpr; 13418 } 13419 return; 13420 } 13421 } 13422 13423 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13424 ExceptionSpecificationType EST, 13425 SourceRange SpecificationRange, 13426 ArrayRef<ParsedType> DynamicExceptions, 13427 ArrayRef<SourceRange> DynamicExceptionRanges, 13428 Expr *NoexceptExpr) { 13429 if (!MethodD) 13430 return; 13431 13432 // Dig out the method we're referring to. 13433 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13434 MethodD = FunTmpl->getTemplatedDecl(); 13435 13436 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13437 if (!Method) 13438 return; 13439 13440 // Check the exception specification. 13441 llvm::SmallVector<QualType, 4> Exceptions; 13442 FunctionProtoType::ExceptionSpecInfo ESI; 13443 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13444 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13445 ESI); 13446 13447 // Update the exception specification on the function type. 13448 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13449 13450 if (Method->isStatic()) 13451 checkThisInStaticMemberFunctionExceptionSpec(Method); 13452 13453 if (Method->isVirtual()) { 13454 // Check overrides, which we previously had to delay. 13455 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13456 OEnd = Method->end_overridden_methods(); 13457 O != OEnd; ++O) 13458 CheckOverridingFunctionExceptionSpec(Method, *O); 13459 } 13460 } 13461 13462 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13463 /// 13464 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13465 SourceLocation DeclStart, 13466 Declarator &D, Expr *BitWidth, 13467 InClassInitStyle InitStyle, 13468 AccessSpecifier AS, 13469 AttributeList *MSPropertyAttr) { 13470 IdentifierInfo *II = D.getIdentifier(); 13471 if (!II) { 13472 Diag(DeclStart, diag::err_anonymous_property); 13473 return nullptr; 13474 } 13475 SourceLocation Loc = D.getIdentifierLoc(); 13476 13477 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13478 QualType T = TInfo->getType(); 13479 if (getLangOpts().CPlusPlus) { 13480 CheckExtraCXXDefaultArguments(D); 13481 13482 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13483 UPPC_DataMemberType)) { 13484 D.setInvalidType(); 13485 T = Context.IntTy; 13486 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13487 } 13488 } 13489 13490 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13491 13492 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13493 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13494 diag::err_invalid_thread) 13495 << DeclSpec::getSpecifierName(TSCS); 13496 13497 // Check to see if this name was declared as a member previously 13498 NamedDecl *PrevDecl = nullptr; 13499 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13500 LookupName(Previous, S); 13501 switch (Previous.getResultKind()) { 13502 case LookupResult::Found: 13503 case LookupResult::FoundUnresolvedValue: 13504 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13505 break; 13506 13507 case LookupResult::FoundOverloaded: 13508 PrevDecl = Previous.getRepresentativeDecl(); 13509 break; 13510 13511 case LookupResult::NotFound: 13512 case LookupResult::NotFoundInCurrentInstantiation: 13513 case LookupResult::Ambiguous: 13514 break; 13515 } 13516 13517 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13518 // Maybe we will complain about the shadowed template parameter. 13519 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13520 // Just pretend that we didn't see the previous declaration. 13521 PrevDecl = nullptr; 13522 } 13523 13524 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13525 PrevDecl = nullptr; 13526 13527 SourceLocation TSSL = D.getLocStart(); 13528 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13529 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13530 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13531 ProcessDeclAttributes(TUScope, NewPD, D); 13532 NewPD->setAccess(AS); 13533 13534 if (NewPD->isInvalidDecl()) 13535 Record->setInvalidDecl(); 13536 13537 if (D.getDeclSpec().isModulePrivateSpecified()) 13538 NewPD->setModulePrivate(); 13539 13540 if (NewPD->isInvalidDecl() && PrevDecl) { 13541 // Don't introduce NewFD into scope; there's already something 13542 // with the same name in the same scope. 13543 } else if (II) { 13544 PushOnScopeChains(NewPD, S); 13545 } else 13546 Record->addDecl(NewPD); 13547 13548 return NewPD; 13549 } 13550