1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for C++ declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Lex/LiteralSupport.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/CXXFieldCollector.h" 32 #include "clang/Sema/DeclSpec.h" 33 #include "clang/Sema/Initialization.h" 34 #include "clang/Sema/Lookup.h" 35 #include "clang/Sema/ParsedTemplate.h" 36 #include "clang/Sema/Scope.h" 37 #include "clang/Sema/ScopeInfo.h" 38 #include "clang/Sema/SemaInternal.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include "llvm/ADT/StringExtras.h" 43 #include <map> 44 #include <set> 45 46 using namespace clang; 47 48 //===----------------------------------------------------------------------===// 49 // CheckDefaultArgumentVisitor 50 //===----------------------------------------------------------------------===// 51 52 namespace { 53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 54 /// the default argument of a parameter to determine whether it 55 /// contains any ill-formed subexpressions. For example, this will 56 /// diagnose the use of local variables or parameters within the 57 /// default argument expression. 58 class CheckDefaultArgumentVisitor 59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 60 Expr *DefaultArg; 61 Sema *S; 62 63 public: 64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 65 : DefaultArg(defarg), S(s) {} 66 67 bool VisitExpr(Expr *Node); 68 bool VisitDeclRefExpr(DeclRefExpr *DRE); 69 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 70 bool VisitLambdaExpr(LambdaExpr *Lambda); 71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 72 }; 73 74 /// VisitExpr - Visit all of the children of this expression. 75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 76 bool IsInvalid = false; 77 for (Stmt *SubStmt : Node->children()) 78 IsInvalid |= Visit(SubStmt); 79 return IsInvalid; 80 } 81 82 /// VisitDeclRefExpr - Visit a reference to a declaration, to 83 /// determine whether this declaration can be used in the default 84 /// argument expression. 85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 86 NamedDecl *Decl = DRE->getDecl(); 87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 88 // C++ [dcl.fct.default]p9 89 // Default arguments are evaluated each time the function is 90 // called. The order of evaluation of function arguments is 91 // unspecified. Consequently, parameters of a function shall not 92 // be used in default argument expressions, even if they are not 93 // evaluated. Parameters of a function declared before a default 94 // argument expression are in scope and can hide namespace and 95 // class member names. 96 return S->Diag(DRE->getLocStart(), 97 diag::err_param_default_argument_references_param) 98 << Param->getDeclName() << DefaultArg->getSourceRange(); 99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 100 // C++ [dcl.fct.default]p7 101 // Local variables shall not be used in default argument 102 // expressions. 103 if (VDecl->isLocalVarDecl()) 104 return S->Diag(DRE->getLocStart(), 105 diag::err_param_default_argument_references_local) 106 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 107 } 108 109 return false; 110 } 111 112 /// VisitCXXThisExpr - Visit a C++ "this" expression. 113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 114 // C++ [dcl.fct.default]p8: 115 // The keyword this shall not be used in a default argument of a 116 // member function. 117 return S->Diag(ThisE->getLocStart(), 118 diag::err_param_default_argument_references_this) 119 << ThisE->getSourceRange(); 120 } 121 122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 123 bool Invalid = false; 124 for (PseudoObjectExpr::semantics_iterator 125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 126 Expr *E = *i; 127 128 // Look through bindings. 129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 130 E = OVE->getSourceExpr(); 131 assert(E && "pseudo-object binding without source expression?"); 132 } 133 134 Invalid |= Visit(E); 135 } 136 return Invalid; 137 } 138 139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 140 // C++11 [expr.lambda.prim]p13: 141 // A lambda-expression appearing in a default argument shall not 142 // implicitly or explicitly capture any entity. 143 if (Lambda->capture_begin() == Lambda->capture_end()) 144 return false; 145 146 return S->Diag(Lambda->getLocStart(), 147 diag::err_lambda_capture_default_arg); 148 } 149 } 150 151 void 152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 153 const CXXMethodDecl *Method) { 154 // If we have an MSAny spec already, don't bother. 155 if (!Method || ComputedEST == EST_MSAny) 156 return; 157 158 const FunctionProtoType *Proto 159 = Method->getType()->getAs<FunctionProtoType>(); 160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 161 if (!Proto) 162 return; 163 164 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 165 166 // If we have a throw-all spec at this point, ignore the function. 167 if (ComputedEST == EST_None) 168 return; 169 170 switch(EST) { 171 // If this function can throw any exceptions, make a note of that. 172 case EST_MSAny: 173 case EST_None: 174 ClearExceptions(); 175 ComputedEST = EST; 176 return; 177 // FIXME: If the call to this decl is using any of its default arguments, we 178 // need to search them for potentially-throwing calls. 179 // If this function has a basic noexcept, it doesn't affect the outcome. 180 case EST_BasicNoexcept: 181 return; 182 // If we're still at noexcept(true) and there's a nothrow() callee, 183 // change to that specification. 184 case EST_DynamicNone: 185 if (ComputedEST == EST_BasicNoexcept) 186 ComputedEST = EST_DynamicNone; 187 return; 188 // Check out noexcept specs. 189 case EST_ComputedNoexcept: 190 { 191 FunctionProtoType::NoexceptResult NR = 192 Proto->getNoexceptSpec(Self->Context); 193 assert(NR != FunctionProtoType::NR_NoNoexcept && 194 "Must have noexcept result for EST_ComputedNoexcept."); 195 assert(NR != FunctionProtoType::NR_Dependent && 196 "Should not generate implicit declarations for dependent cases, " 197 "and don't know how to handle them anyway."); 198 // noexcept(false) -> no spec on the new function 199 if (NR == FunctionProtoType::NR_Throw) { 200 ClearExceptions(); 201 ComputedEST = EST_None; 202 } 203 // noexcept(true) won't change anything either. 204 return; 205 } 206 default: 207 break; 208 } 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // C++11 [dcl.fct.default]p3 321 // A default argument expression [...] shall not be specified for a 322 // parameter pack. 323 if (Param->isParameterPack()) { 324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 325 << DefaultArg->getSourceRange(); 326 return; 327 } 328 329 // Check that the default argument is well-formed 330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 331 if (DefaultArgChecker.Visit(DefaultArg)) { 332 Param->setInvalidDecl(); 333 return; 334 } 335 336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 337 } 338 339 /// ActOnParamUnparsedDefaultArgument - We've seen a default 340 /// argument for a function parameter, but we can't parse it yet 341 /// because we're inside a class definition. Note that this default 342 /// argument will be parsed later. 343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 344 SourceLocation EqualLoc, 345 SourceLocation ArgLoc) { 346 if (!param) 347 return; 348 349 ParmVarDecl *Param = cast<ParmVarDecl>(param); 350 Param->setUnparsedDefaultArg(); 351 UnparsedDefaultArgLocs[Param] = ArgLoc; 352 } 353 354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 355 /// the default argument for the parameter param failed. 356 void Sema::ActOnParamDefaultArgumentError(Decl *param, 357 SourceLocation EqualLoc) { 358 if (!param) 359 return; 360 361 ParmVarDecl *Param = cast<ParmVarDecl>(param); 362 Param->setInvalidDecl(); 363 UnparsedDefaultArgLocs.erase(Param); 364 Param->setDefaultArg(new(Context) 365 OpaqueValueExpr(EqualLoc, 366 Param->getType().getNonReferenceType(), 367 VK_RValue)); 368 } 369 370 /// CheckExtraCXXDefaultArguments - Check for any extra default 371 /// arguments in the declarator, which is not a function declaration 372 /// or definition and therefore is not permitted to have default 373 /// arguments. This routine should be invoked for every declarator 374 /// that is not a function declaration or definition. 375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 376 // C++ [dcl.fct.default]p3 377 // A default argument expression shall be specified only in the 378 // parameter-declaration-clause of a function declaration or in a 379 // template-parameter (14.1). It shall not be specified for a 380 // parameter pack. If it is specified in a 381 // parameter-declaration-clause, it shall not occur within a 382 // declarator or abstract-declarator of a parameter-declaration. 383 bool MightBeFunction = D.isFunctionDeclarationContext(); 384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 385 DeclaratorChunk &chunk = D.getTypeObject(i); 386 if (chunk.Kind == DeclaratorChunk::Function) { 387 if (MightBeFunction) { 388 // This is a function declaration. It can have default arguments, but 389 // keep looking in case its return type is a function type with default 390 // arguments. 391 MightBeFunction = false; 392 continue; 393 } 394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 395 ++argIdx) { 396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 397 if (Param->hasUnparsedDefaultArg()) { 398 std::unique_ptr<CachedTokens> Toks = 399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 400 SourceRange SR; 401 if (Toks->size() > 1) 402 SR = SourceRange((*Toks)[1].getLocation(), 403 Toks->back().getLocation()); 404 else 405 SR = UnparsedDefaultArgLocs[Param]; 406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 407 << SR; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficient, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found the right previous declaration. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter unless the new 551 // function is a friend declaration in a template class. In the latter 552 // case the default arguments will be inherited when the friend 553 // declaration will be instantiated. 554 if (New->getFriendObjectKind() == Decl::FOK_None || 555 !New->getLexicalDeclContext()->isDependentContext()) { 556 // It's important to use getInit() here; getDefaultArg() 557 // strips off any top-level ExprWithCleanups. 558 NewParam->setHasInheritedDefaultArg(); 559 if (OldParam->hasUnparsedDefaultArg()) 560 NewParam->setUnparsedDefaultArg(); 561 else if (OldParam->hasUninstantiatedDefaultArg()) 562 NewParam->setUninstantiatedDefaultArg( 563 OldParam->getUninstantiatedDefaultArg()); 564 else 565 NewParam->setDefaultArg(OldParam->getInit()); 566 } 567 } else if (NewParamHasDfl) { 568 if (New->getDescribedFunctionTemplate()) { 569 // Paragraph 4, quoted above, only applies to non-template functions. 570 Diag(NewParam->getLocation(), 571 diag::err_param_default_argument_template_redecl) 572 << NewParam->getDefaultArgRange(); 573 Diag(PrevForDefaultArgs->getLocation(), 574 diag::note_template_prev_declaration) 575 << false; 576 } else if (New->getTemplateSpecializationKind() 577 != TSK_ImplicitInstantiation && 578 New->getTemplateSpecializationKind() != TSK_Undeclared) { 579 // C++ [temp.expr.spec]p21: 580 // Default function arguments shall not be specified in a declaration 581 // or a definition for one of the following explicit specializations: 582 // - the explicit specialization of a function template; 583 // - the explicit specialization of a member function template; 584 // - the explicit specialization of a member function of a class 585 // template where the class template specialization to which the 586 // member function specialization belongs is implicitly 587 // instantiated. 588 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 589 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 590 << New->getDeclName() 591 << NewParam->getDefaultArgRange(); 592 } else if (New->getDeclContext()->isDependentContext()) { 593 // C++ [dcl.fct.default]p6 (DR217): 594 // Default arguments for a member function of a class template shall 595 // be specified on the initial declaration of the member function 596 // within the class template. 597 // 598 // Reading the tea leaves a bit in DR217 and its reference to DR205 599 // leads me to the conclusion that one cannot add default function 600 // arguments for an out-of-line definition of a member function of a 601 // dependent type. 602 int WhichKind = 2; 603 if (CXXRecordDecl *Record 604 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 605 if (Record->getDescribedClassTemplate()) 606 WhichKind = 0; 607 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 608 WhichKind = 1; 609 else 610 WhichKind = 2; 611 } 612 613 Diag(NewParam->getLocation(), 614 diag::err_param_default_argument_member_template_redecl) 615 << WhichKind 616 << NewParam->getDefaultArgRange(); 617 } 618 } 619 } 620 621 // DR1344: If a default argument is added outside a class definition and that 622 // default argument makes the function a special member function, the program 623 // is ill-formed. This can only happen for constructors. 624 if (isa<CXXConstructorDecl>(New) && 625 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 626 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 627 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 628 if (NewSM != OldSM) { 629 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 630 assert(NewParam->hasDefaultArg()); 631 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 632 << NewParam->getDefaultArgRange() << NewSM; 633 Diag(Old->getLocation(), diag::note_previous_declaration); 634 } 635 } 636 637 const FunctionDecl *Def; 638 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 639 // template has a constexpr specifier then all its declarations shall 640 // contain the constexpr specifier. 641 if (New->isConstexpr() != Old->isConstexpr()) { 642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 643 << New << New->isConstexpr(); 644 Diag(Old->getLocation(), diag::note_previous_declaration); 645 Invalid = true; 646 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 647 Old->isDefined(Def) && 648 // If a friend function is inlined but does not have 'inline' 649 // specifier, it is a definition. Do not report attribute conflict 650 // in this case, redefinition will be diagnosed later. 651 (New->isInlineSpecified() || 652 New->getFriendObjectKind() == Decl::FOK_None)) { 653 // C++11 [dcl.fcn.spec]p4: 654 // If the definition of a function appears in a translation unit before its 655 // first declaration as inline, the program is ill-formed. 656 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 657 Diag(Def->getLocation(), diag::note_previous_definition); 658 Invalid = true; 659 } 660 661 // FIXME: It's not clear what should happen if multiple declarations of a 662 // deduction guide have different explicitness. For now at least we simply 663 // reject any case where the explicitness changes. 664 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 665 if (NewGuide && NewGuide->isExplicitSpecified() != 666 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 667 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 668 << NewGuide->isExplicitSpecified(); 669 Diag(Old->getLocation(), diag::note_previous_declaration); 670 } 671 672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 673 // argument expression, that declaration shall be a definition and shall be 674 // the only declaration of the function or function template in the 675 // translation unit. 676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 677 functionDeclHasDefaultArgument(Old)) { 678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 679 Diag(Old->getLocation(), diag::note_previous_declaration); 680 Invalid = true; 681 } 682 683 return Invalid; 684 } 685 686 NamedDecl * 687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 688 MultiTemplateParamsArg TemplateParamLists) { 689 assert(D.isDecompositionDeclarator()); 690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 691 692 // The syntax only allows a decomposition declarator as a simple-declaration 693 // or a for-range-declaration, but we parse it in more cases than that. 694 if (!D.mayHaveDecompositionDeclarator()) { 695 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 696 << Decomp.getSourceRange(); 697 return nullptr; 698 } 699 700 if (!TemplateParamLists.empty()) { 701 // FIXME: There's no rule against this, but there are also no rules that 702 // would actually make it usable, so we reject it for now. 703 Diag(TemplateParamLists.front()->getTemplateLoc(), 704 diag::err_decomp_decl_template); 705 return nullptr; 706 } 707 708 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z 709 ? diag::warn_cxx14_compat_decomp_decl 710 : diag::ext_decomp_decl) 711 << Decomp.getSourceRange(); 712 713 // The semantic context is always just the current context. 714 DeclContext *const DC = CurContext; 715 716 // C++1z [dcl.dcl]/8: 717 // The decl-specifier-seq shall contain only the type-specifier auto 718 // and cv-qualifiers. 719 auto &DS = D.getDeclSpec(); 720 { 721 SmallVector<StringRef, 8> BadSpecifiers; 722 SmallVector<SourceLocation, 8> BadSpecifierLocs; 723 if (auto SCS = DS.getStorageClassSpec()) { 724 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 725 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 726 } 727 if (auto TSCS = DS.getThreadStorageClassSpec()) { 728 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 729 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 730 } 731 if (DS.isConstexprSpecified()) { 732 BadSpecifiers.push_back("constexpr"); 733 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 734 } 735 if (DS.isInlineSpecified()) { 736 BadSpecifiers.push_back("inline"); 737 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 738 } 739 if (!BadSpecifiers.empty()) { 740 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 741 Err << (int)BadSpecifiers.size() 742 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 743 // Don't add FixItHints to remove the specifiers; we do still respect 744 // them when building the underlying variable. 745 for (auto Loc : BadSpecifierLocs) 746 Err << SourceRange(Loc, Loc); 747 } 748 // We can't recover from it being declared as a typedef. 749 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 750 return nullptr; 751 } 752 753 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 754 QualType R = TInfo->getType(); 755 756 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 757 UPPC_DeclarationType)) 758 D.setInvalidType(); 759 760 // The syntax only allows a single ref-qualifier prior to the decomposition 761 // declarator. No other declarator chunks are permitted. Also check the type 762 // specifier here. 763 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 764 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 765 (D.getNumTypeObjects() == 1 && 766 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 767 Diag(Decomp.getLSquareLoc(), 768 (D.hasGroupingParens() || 769 (D.getNumTypeObjects() && 770 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 771 ? diag::err_decomp_decl_parens 772 : diag::err_decomp_decl_type) 773 << R; 774 775 // In most cases, there's no actual problem with an explicitly-specified 776 // type, but a function type won't work here, and ActOnVariableDeclarator 777 // shouldn't be called for such a type. 778 if (R->isFunctionType()) 779 D.setInvalidType(); 780 } 781 782 // Build the BindingDecls. 783 SmallVector<BindingDecl*, 8> Bindings; 784 785 // Build the BindingDecls. 786 for (auto &B : D.getDecompositionDeclarator().bindings()) { 787 // Check for name conflicts. 788 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 789 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 790 ForRedeclaration); 791 LookupName(Previous, S, 792 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 793 794 // It's not permitted to shadow a template parameter name. 795 if (Previous.isSingleResult() && 796 Previous.getFoundDecl()->isTemplateParameter()) { 797 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 798 Previous.getFoundDecl()); 799 Previous.clear(); 800 } 801 802 bool ConsiderLinkage = DC->isFunctionOrMethod() && 803 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 804 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 805 /*AllowInlineNamespace*/false); 806 if (!Previous.empty()) { 807 auto *Old = Previous.getRepresentativeDecl(); 808 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 809 Diag(Old->getLocation(), diag::note_previous_definition); 810 } 811 812 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 813 PushOnScopeChains(BD, S, true); 814 Bindings.push_back(BD); 815 ParsingInitForAutoVars.insert(BD); 816 } 817 818 // There are no prior lookup results for the variable itself, because it 819 // is unnamed. 820 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 821 Decomp.getLSquareLoc()); 822 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 823 824 // Build the variable that holds the non-decomposed object. 825 bool AddToScope = true; 826 NamedDecl *New = 827 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 828 MultiTemplateParamsArg(), AddToScope, Bindings); 829 CurContext->addHiddenDecl(New); 830 831 if (isInOpenMPDeclareTargetContext()) 832 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 833 834 return New; 835 } 836 837 static bool checkSimpleDecomposition( 838 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 839 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 840 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 841 if ((int64_t)Bindings.size() != NumElems) { 842 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 843 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 844 << (NumElems < Bindings.size()); 845 return true; 846 } 847 848 unsigned I = 0; 849 for (auto *B : Bindings) { 850 SourceLocation Loc = B->getLocation(); 851 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 852 if (E.isInvalid()) 853 return true; 854 E = GetInit(Loc, E.get(), I++); 855 if (E.isInvalid()) 856 return true; 857 B->setBinding(ElemType, E.get()); 858 } 859 860 return false; 861 } 862 863 static bool checkArrayLikeDecomposition(Sema &S, 864 ArrayRef<BindingDecl *> Bindings, 865 ValueDecl *Src, QualType DecompType, 866 const llvm::APSInt &NumElems, 867 QualType ElemType) { 868 return checkSimpleDecomposition( 869 S, Bindings, Src, DecompType, NumElems, ElemType, 870 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 871 ExprResult E = S.ActOnIntegerConstant(Loc, I); 872 if (E.isInvalid()) 873 return ExprError(); 874 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 875 }); 876 } 877 878 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 879 ValueDecl *Src, QualType DecompType, 880 const ConstantArrayType *CAT) { 881 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 882 llvm::APSInt(CAT->getSize()), 883 CAT->getElementType()); 884 } 885 886 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 887 ValueDecl *Src, QualType DecompType, 888 const VectorType *VT) { 889 return checkArrayLikeDecomposition( 890 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 891 S.Context.getQualifiedType(VT->getElementType(), 892 DecompType.getQualifiers())); 893 } 894 895 static bool checkComplexDecomposition(Sema &S, 896 ArrayRef<BindingDecl *> Bindings, 897 ValueDecl *Src, QualType DecompType, 898 const ComplexType *CT) { 899 return checkSimpleDecomposition( 900 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 901 S.Context.getQualifiedType(CT->getElementType(), 902 DecompType.getQualifiers()), 903 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 904 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 905 }); 906 } 907 908 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 909 TemplateArgumentListInfo &Args) { 910 SmallString<128> SS; 911 llvm::raw_svector_ostream OS(SS); 912 bool First = true; 913 for (auto &Arg : Args.arguments()) { 914 if (!First) 915 OS << ", "; 916 Arg.getArgument().print(PrintingPolicy, OS); 917 First = false; 918 } 919 return OS.str(); 920 } 921 922 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 923 SourceLocation Loc, StringRef Trait, 924 TemplateArgumentListInfo &Args, 925 unsigned DiagID) { 926 auto DiagnoseMissing = [&] { 927 if (DiagID) 928 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 929 Args); 930 return true; 931 }; 932 933 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 934 NamespaceDecl *Std = S.getStdNamespace(); 935 if (!Std) 936 return DiagnoseMissing(); 937 938 // Look up the trait itself, within namespace std. We can diagnose various 939 // problems with this lookup even if we've been asked to not diagnose a 940 // missing specialization, because this can only fail if the user has been 941 // declaring their own names in namespace std or we don't support the 942 // standard library implementation in use. 943 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 944 Loc, Sema::LookupOrdinaryName); 945 if (!S.LookupQualifiedName(Result, Std)) 946 return DiagnoseMissing(); 947 if (Result.isAmbiguous()) 948 return true; 949 950 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 951 if (!TraitTD) { 952 Result.suppressDiagnostics(); 953 NamedDecl *Found = *Result.begin(); 954 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 955 S.Diag(Found->getLocation(), diag::note_declared_at); 956 return true; 957 } 958 959 // Build the template-id. 960 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 961 if (TraitTy.isNull()) 962 return true; 963 if (!S.isCompleteType(Loc, TraitTy)) { 964 if (DiagID) 965 S.RequireCompleteType( 966 Loc, TraitTy, DiagID, 967 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 968 return true; 969 } 970 971 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 972 assert(RD && "specialization of class template is not a class?"); 973 974 // Look up the member of the trait type. 975 S.LookupQualifiedName(TraitMemberLookup, RD); 976 return TraitMemberLookup.isAmbiguous(); 977 } 978 979 static TemplateArgumentLoc 980 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 981 uint64_t I) { 982 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 983 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 984 } 985 986 static TemplateArgumentLoc 987 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 988 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 989 } 990 991 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 992 993 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 994 llvm::APSInt &Size) { 995 EnterExpressionEvaluationContext ContextRAII( 996 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 997 998 DeclarationName Value = S.PP.getIdentifierInfo("value"); 999 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1000 1001 // Form template argument list for tuple_size<T>. 1002 TemplateArgumentListInfo Args(Loc, Loc); 1003 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1004 1005 // If there's no tuple_size specialization, it's not tuple-like. 1006 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1007 return IsTupleLike::NotTupleLike; 1008 1009 // If we get this far, we've committed to the tuple interpretation, but 1010 // we can still fail if there actually isn't a usable ::value. 1011 1012 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1013 LookupResult &R; 1014 TemplateArgumentListInfo &Args; 1015 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1016 : R(R), Args(Args) {} 1017 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1018 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1019 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1020 } 1021 } Diagnoser(R, Args); 1022 1023 if (R.empty()) { 1024 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1025 return IsTupleLike::Error; 1026 } 1027 1028 ExprResult E = 1029 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1030 if (E.isInvalid()) 1031 return IsTupleLike::Error; 1032 1033 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1034 if (E.isInvalid()) 1035 return IsTupleLike::Error; 1036 1037 return IsTupleLike::TupleLike; 1038 } 1039 1040 /// \return std::tuple_element<I, T>::type. 1041 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1042 unsigned I, QualType T) { 1043 // Form template argument list for tuple_element<I, T>. 1044 TemplateArgumentListInfo Args(Loc, Loc); 1045 Args.addArgument( 1046 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1047 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1048 1049 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1050 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1051 if (lookupStdTypeTraitMember( 1052 S, R, Loc, "tuple_element", Args, 1053 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1054 return QualType(); 1055 1056 auto *TD = R.getAsSingle<TypeDecl>(); 1057 if (!TD) { 1058 R.suppressDiagnostics(); 1059 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1060 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1061 if (!R.empty()) 1062 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1063 return QualType(); 1064 } 1065 1066 return S.Context.getTypeDeclType(TD); 1067 } 1068 1069 namespace { 1070 struct BindingDiagnosticTrap { 1071 Sema &S; 1072 DiagnosticErrorTrap Trap; 1073 BindingDecl *BD; 1074 1075 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1076 : S(S), Trap(S.Diags), BD(BD) {} 1077 ~BindingDiagnosticTrap() { 1078 if (Trap.hasErrorOccurred()) 1079 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1080 } 1081 }; 1082 } 1083 1084 static bool checkTupleLikeDecomposition(Sema &S, 1085 ArrayRef<BindingDecl *> Bindings, 1086 VarDecl *Src, QualType DecompType, 1087 const llvm::APSInt &TupleSize) { 1088 if ((int64_t)Bindings.size() != TupleSize) { 1089 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1090 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1091 << (TupleSize < Bindings.size()); 1092 return true; 1093 } 1094 1095 if (Bindings.empty()) 1096 return false; 1097 1098 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1099 1100 // [dcl.decomp]p3: 1101 // The unqualified-id get is looked up in the scope of E by class member 1102 // access lookup 1103 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1104 bool UseMemberGet = false; 1105 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1106 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1107 S.LookupQualifiedName(MemberGet, RD); 1108 if (MemberGet.isAmbiguous()) 1109 return true; 1110 UseMemberGet = !MemberGet.empty(); 1111 S.FilterAcceptableTemplateNames(MemberGet); 1112 } 1113 1114 unsigned I = 0; 1115 for (auto *B : Bindings) { 1116 BindingDiagnosticTrap Trap(S, B); 1117 SourceLocation Loc = B->getLocation(); 1118 1119 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1120 if (E.isInvalid()) 1121 return true; 1122 1123 // e is an lvalue if the type of the entity is an lvalue reference and 1124 // an xvalue otherwise 1125 if (!Src->getType()->isLValueReferenceType()) 1126 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1127 E.get(), nullptr, VK_XValue); 1128 1129 TemplateArgumentListInfo Args(Loc, Loc); 1130 Args.addArgument( 1131 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1132 1133 if (UseMemberGet) { 1134 // if [lookup of member get] finds at least one declaration, the 1135 // initializer is e.get<i-1>(). 1136 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1137 CXXScopeSpec(), SourceLocation(), nullptr, 1138 MemberGet, &Args, nullptr); 1139 if (E.isInvalid()) 1140 return true; 1141 1142 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1143 } else { 1144 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1145 // in the associated namespaces. 1146 Expr *Get = UnresolvedLookupExpr::Create( 1147 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1148 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1149 UnresolvedSetIterator(), UnresolvedSetIterator()); 1150 1151 Expr *Arg = E.get(); 1152 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1153 } 1154 if (E.isInvalid()) 1155 return true; 1156 Expr *Init = E.get(); 1157 1158 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1159 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1160 if (T.isNull()) 1161 return true; 1162 1163 // each vi is a variable of type "reference to T" initialized with the 1164 // initializer, where the reference is an lvalue reference if the 1165 // initializer is an lvalue and an rvalue reference otherwise 1166 QualType RefType = 1167 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1168 if (RefType.isNull()) 1169 return true; 1170 auto *RefVD = VarDecl::Create( 1171 S.Context, Src->getDeclContext(), Loc, Loc, 1172 B->getDeclName().getAsIdentifierInfo(), RefType, 1173 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1174 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1175 RefVD->setTSCSpec(Src->getTSCSpec()); 1176 RefVD->setImplicit(); 1177 if (Src->isInlineSpecified()) 1178 RefVD->setInlineSpecified(); 1179 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1180 1181 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1182 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1183 InitializationSequence Seq(S, Entity, Kind, Init); 1184 E = Seq.Perform(S, Entity, Kind, Init); 1185 if (E.isInvalid()) 1186 return true; 1187 E = S.ActOnFinishFullExpr(E.get(), Loc); 1188 if (E.isInvalid()) 1189 return true; 1190 RefVD->setInit(E.get()); 1191 RefVD->checkInitIsICE(); 1192 1193 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1194 DeclarationNameInfo(B->getDeclName(), Loc), 1195 RefVD); 1196 if (E.isInvalid()) 1197 return true; 1198 1199 B->setBinding(T, E.get()); 1200 I++; 1201 } 1202 1203 return false; 1204 } 1205 1206 /// Find the base class to decompose in a built-in decomposition of a class type. 1207 /// This base class search is, unfortunately, not quite like any other that we 1208 /// perform anywhere else in C++. 1209 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1210 SourceLocation Loc, 1211 const CXXRecordDecl *RD, 1212 CXXCastPath &BasePath) { 1213 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1214 CXXBasePath &Path) { 1215 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1216 }; 1217 1218 const CXXRecordDecl *ClassWithFields = nullptr; 1219 if (RD->hasDirectFields()) 1220 // [dcl.decomp]p4: 1221 // Otherwise, all of E's non-static data members shall be public direct 1222 // members of E ... 1223 ClassWithFields = RD; 1224 else { 1225 // ... or of ... 1226 CXXBasePaths Paths; 1227 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1228 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1229 // If no classes have fields, just decompose RD itself. (This will work 1230 // if and only if zero bindings were provided.) 1231 return RD; 1232 } 1233 1234 CXXBasePath *BestPath = nullptr; 1235 for (auto &P : Paths) { 1236 if (!BestPath) 1237 BestPath = &P; 1238 else if (!S.Context.hasSameType(P.back().Base->getType(), 1239 BestPath->back().Base->getType())) { 1240 // ... the same ... 1241 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1242 << false << RD << BestPath->back().Base->getType() 1243 << P.back().Base->getType(); 1244 return nullptr; 1245 } else if (P.Access < BestPath->Access) { 1246 BestPath = &P; 1247 } 1248 } 1249 1250 // ... unambiguous ... 1251 QualType BaseType = BestPath->back().Base->getType(); 1252 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1253 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1254 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1255 return nullptr; 1256 } 1257 1258 // ... public base class of E. 1259 if (BestPath->Access != AS_public) { 1260 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1261 << RD << BaseType; 1262 for (auto &BS : *BestPath) { 1263 if (BS.Base->getAccessSpecifier() != AS_public) { 1264 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1265 << (BS.Base->getAccessSpecifier() == AS_protected) 1266 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1267 break; 1268 } 1269 } 1270 return nullptr; 1271 } 1272 1273 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1274 S.BuildBasePathArray(Paths, BasePath); 1275 } 1276 1277 // The above search did not check whether the selected class itself has base 1278 // classes with fields, so check that now. 1279 CXXBasePaths Paths; 1280 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1281 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1282 << (ClassWithFields == RD) << RD << ClassWithFields 1283 << Paths.front().back().Base->getType(); 1284 return nullptr; 1285 } 1286 1287 return ClassWithFields; 1288 } 1289 1290 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1291 ValueDecl *Src, QualType DecompType, 1292 const CXXRecordDecl *RD) { 1293 CXXCastPath BasePath; 1294 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1295 if (!RD) 1296 return true; 1297 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1298 DecompType.getQualifiers()); 1299 1300 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1301 unsigned NumFields = 1302 std::count_if(RD->field_begin(), RD->field_end(), 1303 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1304 assert(Bindings.size() != NumFields); 1305 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1306 << DecompType << (unsigned)Bindings.size() << NumFields 1307 << (NumFields < Bindings.size()); 1308 return true; 1309 }; 1310 1311 // all of E's non-static data members shall be public [...] members, 1312 // E shall not have an anonymous union member, ... 1313 unsigned I = 0; 1314 for (auto *FD : RD->fields()) { 1315 if (FD->isUnnamedBitfield()) 1316 continue; 1317 1318 if (FD->isAnonymousStructOrUnion()) { 1319 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1320 << DecompType << FD->getType()->isUnionType(); 1321 S.Diag(FD->getLocation(), diag::note_declared_at); 1322 return true; 1323 } 1324 1325 // We have a real field to bind. 1326 if (I >= Bindings.size()) 1327 return DiagnoseBadNumberOfBindings(); 1328 auto *B = Bindings[I++]; 1329 1330 SourceLocation Loc = B->getLocation(); 1331 if (FD->getAccess() != AS_public) { 1332 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1333 1334 // Determine whether the access specifier was explicit. 1335 bool Implicit = true; 1336 for (const auto *D : RD->decls()) { 1337 if (declaresSameEntity(D, FD)) 1338 break; 1339 if (isa<AccessSpecDecl>(D)) { 1340 Implicit = false; 1341 break; 1342 } 1343 } 1344 1345 S.Diag(FD->getLocation(), diag::note_access_natural) 1346 << (FD->getAccess() == AS_protected) << Implicit; 1347 return true; 1348 } 1349 1350 // Initialize the binding to Src.FD. 1351 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1352 if (E.isInvalid()) 1353 return true; 1354 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1355 VK_LValue, &BasePath); 1356 if (E.isInvalid()) 1357 return true; 1358 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1359 CXXScopeSpec(), FD, 1360 DeclAccessPair::make(FD, FD->getAccess()), 1361 DeclarationNameInfo(FD->getDeclName(), Loc)); 1362 if (E.isInvalid()) 1363 return true; 1364 1365 // If the type of the member is T, the referenced type is cv T, where cv is 1366 // the cv-qualification of the decomposition expression. 1367 // 1368 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1369 // 'const' to the type of the field. 1370 Qualifiers Q = DecompType.getQualifiers(); 1371 if (FD->isMutable()) 1372 Q.removeConst(); 1373 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1374 } 1375 1376 if (I != Bindings.size()) 1377 return DiagnoseBadNumberOfBindings(); 1378 1379 return false; 1380 } 1381 1382 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1383 QualType DecompType = DD->getType(); 1384 1385 // If the type of the decomposition is dependent, then so is the type of 1386 // each binding. 1387 if (DecompType->isDependentType()) { 1388 for (auto *B : DD->bindings()) 1389 B->setType(Context.DependentTy); 1390 return; 1391 } 1392 1393 DecompType = DecompType.getNonReferenceType(); 1394 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1395 1396 // C++1z [dcl.decomp]/2: 1397 // If E is an array type [...] 1398 // As an extension, we also support decomposition of built-in complex and 1399 // vector types. 1400 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1401 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1402 DD->setInvalidDecl(); 1403 return; 1404 } 1405 if (auto *VT = DecompType->getAs<VectorType>()) { 1406 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1407 DD->setInvalidDecl(); 1408 return; 1409 } 1410 if (auto *CT = DecompType->getAs<ComplexType>()) { 1411 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1412 DD->setInvalidDecl(); 1413 return; 1414 } 1415 1416 // C++1z [dcl.decomp]/3: 1417 // if the expression std::tuple_size<E>::value is a well-formed integral 1418 // constant expression, [...] 1419 llvm::APSInt TupleSize(32); 1420 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1421 case IsTupleLike::Error: 1422 DD->setInvalidDecl(); 1423 return; 1424 1425 case IsTupleLike::TupleLike: 1426 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1427 DD->setInvalidDecl(); 1428 return; 1429 1430 case IsTupleLike::NotTupleLike: 1431 break; 1432 } 1433 1434 // C++1z [dcl.dcl]/8: 1435 // [E shall be of array or non-union class type] 1436 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1437 if (!RD || RD->isUnion()) { 1438 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1439 << DD << !RD << DecompType; 1440 DD->setInvalidDecl(); 1441 return; 1442 } 1443 1444 // C++1z [dcl.decomp]/4: 1445 // all of E's non-static data members shall be [...] direct members of 1446 // E or of the same unambiguous public base class of E, ... 1447 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1448 DD->setInvalidDecl(); 1449 } 1450 1451 /// \brief Merge the exception specifications of two variable declarations. 1452 /// 1453 /// This is called when there's a redeclaration of a VarDecl. The function 1454 /// checks if the redeclaration might have an exception specification and 1455 /// validates compatibility and merges the specs if necessary. 1456 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1457 // Shortcut if exceptions are disabled. 1458 if (!getLangOpts().CXXExceptions) 1459 return; 1460 1461 assert(Context.hasSameType(New->getType(), Old->getType()) && 1462 "Should only be called if types are otherwise the same."); 1463 1464 QualType NewType = New->getType(); 1465 QualType OldType = Old->getType(); 1466 1467 // We're only interested in pointers and references to functions, as well 1468 // as pointers to member functions. 1469 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1470 NewType = R->getPointeeType(); 1471 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1472 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1473 NewType = P->getPointeeType(); 1474 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1475 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1476 NewType = M->getPointeeType(); 1477 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1478 } 1479 1480 if (!NewType->isFunctionProtoType()) 1481 return; 1482 1483 // There's lots of special cases for functions. For function pointers, system 1484 // libraries are hopefully not as broken so that we don't need these 1485 // workarounds. 1486 if (CheckEquivalentExceptionSpec( 1487 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1488 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1489 New->setInvalidDecl(); 1490 } 1491 } 1492 1493 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1494 /// function declaration are well-formed according to C++ 1495 /// [dcl.fct.default]. 1496 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1497 unsigned NumParams = FD->getNumParams(); 1498 unsigned p; 1499 1500 // Find first parameter with a default argument 1501 for (p = 0; p < NumParams; ++p) { 1502 ParmVarDecl *Param = FD->getParamDecl(p); 1503 if (Param->hasDefaultArg()) 1504 break; 1505 } 1506 1507 // C++11 [dcl.fct.default]p4: 1508 // In a given function declaration, each parameter subsequent to a parameter 1509 // with a default argument shall have a default argument supplied in this or 1510 // a previous declaration or shall be a function parameter pack. A default 1511 // argument shall not be redefined by a later declaration (not even to the 1512 // same value). 1513 unsigned LastMissingDefaultArg = 0; 1514 for (; p < NumParams; ++p) { 1515 ParmVarDecl *Param = FD->getParamDecl(p); 1516 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1517 if (Param->isInvalidDecl()) 1518 /* We already complained about this parameter. */; 1519 else if (Param->getIdentifier()) 1520 Diag(Param->getLocation(), 1521 diag::err_param_default_argument_missing_name) 1522 << Param->getIdentifier(); 1523 else 1524 Diag(Param->getLocation(), 1525 diag::err_param_default_argument_missing); 1526 1527 LastMissingDefaultArg = p; 1528 } 1529 } 1530 1531 if (LastMissingDefaultArg > 0) { 1532 // Some default arguments were missing. Clear out all of the 1533 // default arguments up to (and including) the last missing 1534 // default argument, so that we leave the function parameters 1535 // in a semantically valid state. 1536 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1537 ParmVarDecl *Param = FD->getParamDecl(p); 1538 if (Param->hasDefaultArg()) { 1539 Param->setDefaultArg(nullptr); 1540 } 1541 } 1542 } 1543 } 1544 1545 // CheckConstexprParameterTypes - Check whether a function's parameter types 1546 // are all literal types. If so, return true. If not, produce a suitable 1547 // diagnostic and return false. 1548 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1549 const FunctionDecl *FD) { 1550 unsigned ArgIndex = 0; 1551 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1552 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1553 e = FT->param_type_end(); 1554 i != e; ++i, ++ArgIndex) { 1555 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1556 SourceLocation ParamLoc = PD->getLocation(); 1557 if (!(*i)->isDependentType() && 1558 SemaRef.RequireLiteralType(ParamLoc, *i, 1559 diag::err_constexpr_non_literal_param, 1560 ArgIndex+1, PD->getSourceRange(), 1561 isa<CXXConstructorDecl>(FD))) 1562 return false; 1563 } 1564 return true; 1565 } 1566 1567 /// \brief Get diagnostic %select index for tag kind for 1568 /// record diagnostic message. 1569 /// WARNING: Indexes apply to particular diagnostics only! 1570 /// 1571 /// \returns diagnostic %select index. 1572 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1573 switch (Tag) { 1574 case TTK_Struct: return 0; 1575 case TTK_Interface: return 1; 1576 case TTK_Class: return 2; 1577 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1578 } 1579 } 1580 1581 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1582 // the requirements of a constexpr function definition or a constexpr 1583 // constructor definition. If so, return true. If not, produce appropriate 1584 // diagnostics and return false. 1585 // 1586 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1587 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1588 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1589 if (MD && MD->isInstance()) { 1590 // C++11 [dcl.constexpr]p4: 1591 // The definition of a constexpr constructor shall satisfy the following 1592 // constraints: 1593 // - the class shall not have any virtual base classes; 1594 const CXXRecordDecl *RD = MD->getParent(); 1595 if (RD->getNumVBases()) { 1596 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1597 << isa<CXXConstructorDecl>(NewFD) 1598 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1599 for (const auto &I : RD->vbases()) 1600 Diag(I.getLocStart(), 1601 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1602 return false; 1603 } 1604 } 1605 1606 if (!isa<CXXConstructorDecl>(NewFD)) { 1607 // C++11 [dcl.constexpr]p3: 1608 // The definition of a constexpr function shall satisfy the following 1609 // constraints: 1610 // - it shall not be virtual; 1611 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1612 if (Method && Method->isVirtual()) { 1613 Method = Method->getCanonicalDecl(); 1614 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1615 1616 // If it's not obvious why this function is virtual, find an overridden 1617 // function which uses the 'virtual' keyword. 1618 const CXXMethodDecl *WrittenVirtual = Method; 1619 while (!WrittenVirtual->isVirtualAsWritten()) 1620 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1621 if (WrittenVirtual != Method) 1622 Diag(WrittenVirtual->getLocation(), 1623 diag::note_overridden_virtual_function); 1624 return false; 1625 } 1626 1627 // - its return type shall be a literal type; 1628 QualType RT = NewFD->getReturnType(); 1629 if (!RT->isDependentType() && 1630 RequireLiteralType(NewFD->getLocation(), RT, 1631 diag::err_constexpr_non_literal_return)) 1632 return false; 1633 } 1634 1635 // - each of its parameter types shall be a literal type; 1636 if (!CheckConstexprParameterTypes(*this, NewFD)) 1637 return false; 1638 1639 return true; 1640 } 1641 1642 /// Check the given declaration statement is legal within a constexpr function 1643 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1644 /// 1645 /// \return true if the body is OK (maybe only as an extension), false if we 1646 /// have diagnosed a problem. 1647 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1648 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1649 // C++11 [dcl.constexpr]p3 and p4: 1650 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1651 // contain only 1652 for (const auto *DclIt : DS->decls()) { 1653 switch (DclIt->getKind()) { 1654 case Decl::StaticAssert: 1655 case Decl::Using: 1656 case Decl::UsingShadow: 1657 case Decl::UsingDirective: 1658 case Decl::UnresolvedUsingTypename: 1659 case Decl::UnresolvedUsingValue: 1660 // - static_assert-declarations 1661 // - using-declarations, 1662 // - using-directives, 1663 continue; 1664 1665 case Decl::Typedef: 1666 case Decl::TypeAlias: { 1667 // - typedef declarations and alias-declarations that do not define 1668 // classes or enumerations, 1669 const auto *TN = cast<TypedefNameDecl>(DclIt); 1670 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1671 // Don't allow variably-modified types in constexpr functions. 1672 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1673 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1674 << TL.getSourceRange() << TL.getType() 1675 << isa<CXXConstructorDecl>(Dcl); 1676 return false; 1677 } 1678 continue; 1679 } 1680 1681 case Decl::Enum: 1682 case Decl::CXXRecord: 1683 // C++1y allows types to be defined, not just declared. 1684 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1685 SemaRef.Diag(DS->getLocStart(), 1686 SemaRef.getLangOpts().CPlusPlus14 1687 ? diag::warn_cxx11_compat_constexpr_type_definition 1688 : diag::ext_constexpr_type_definition) 1689 << isa<CXXConstructorDecl>(Dcl); 1690 continue; 1691 1692 case Decl::EnumConstant: 1693 case Decl::IndirectField: 1694 case Decl::ParmVar: 1695 // These can only appear with other declarations which are banned in 1696 // C++11 and permitted in C++1y, so ignore them. 1697 continue; 1698 1699 case Decl::Var: 1700 case Decl::Decomposition: { 1701 // C++1y [dcl.constexpr]p3 allows anything except: 1702 // a definition of a variable of non-literal type or of static or 1703 // thread storage duration or for which no initialization is performed. 1704 const auto *VD = cast<VarDecl>(DclIt); 1705 if (VD->isThisDeclarationADefinition()) { 1706 if (VD->isStaticLocal()) { 1707 SemaRef.Diag(VD->getLocation(), 1708 diag::err_constexpr_local_var_static) 1709 << isa<CXXConstructorDecl>(Dcl) 1710 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1711 return false; 1712 } 1713 if (!VD->getType()->isDependentType() && 1714 SemaRef.RequireLiteralType( 1715 VD->getLocation(), VD->getType(), 1716 diag::err_constexpr_local_var_non_literal_type, 1717 isa<CXXConstructorDecl>(Dcl))) 1718 return false; 1719 if (!VD->getType()->isDependentType() && 1720 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1721 SemaRef.Diag(VD->getLocation(), 1722 diag::err_constexpr_local_var_no_init) 1723 << isa<CXXConstructorDecl>(Dcl); 1724 return false; 1725 } 1726 } 1727 SemaRef.Diag(VD->getLocation(), 1728 SemaRef.getLangOpts().CPlusPlus14 1729 ? diag::warn_cxx11_compat_constexpr_local_var 1730 : diag::ext_constexpr_local_var) 1731 << isa<CXXConstructorDecl>(Dcl); 1732 continue; 1733 } 1734 1735 case Decl::NamespaceAlias: 1736 case Decl::Function: 1737 // These are disallowed in C++11 and permitted in C++1y. Allow them 1738 // everywhere as an extension. 1739 if (!Cxx1yLoc.isValid()) 1740 Cxx1yLoc = DS->getLocStart(); 1741 continue; 1742 1743 default: 1744 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1745 << isa<CXXConstructorDecl>(Dcl); 1746 return false; 1747 } 1748 } 1749 1750 return true; 1751 } 1752 1753 /// Check that the given field is initialized within a constexpr constructor. 1754 /// 1755 /// \param Dcl The constexpr constructor being checked. 1756 /// \param Field The field being checked. This may be a member of an anonymous 1757 /// struct or union nested within the class being checked. 1758 /// \param Inits All declarations, including anonymous struct/union members and 1759 /// indirect members, for which any initialization was provided. 1760 /// \param Diagnosed Set to true if an error is produced. 1761 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1762 const FunctionDecl *Dcl, 1763 FieldDecl *Field, 1764 llvm::SmallSet<Decl*, 16> &Inits, 1765 bool &Diagnosed) { 1766 if (Field->isInvalidDecl()) 1767 return; 1768 1769 if (Field->isUnnamedBitfield()) 1770 return; 1771 1772 // Anonymous unions with no variant members and empty anonymous structs do not 1773 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1774 // indirect fields don't need initializing. 1775 if (Field->isAnonymousStructOrUnion() && 1776 (Field->getType()->isUnionType() 1777 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1778 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1779 return; 1780 1781 if (!Inits.count(Field)) { 1782 if (!Diagnosed) { 1783 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1784 Diagnosed = true; 1785 } 1786 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1787 } else if (Field->isAnonymousStructOrUnion()) { 1788 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1789 for (auto *I : RD->fields()) 1790 // If an anonymous union contains an anonymous struct of which any member 1791 // is initialized, all members must be initialized. 1792 if (!RD->isUnion() || Inits.count(I)) 1793 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1794 } 1795 } 1796 1797 /// Check the provided statement is allowed in a constexpr function 1798 /// definition. 1799 static bool 1800 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1801 SmallVectorImpl<SourceLocation> &ReturnStmts, 1802 SourceLocation &Cxx1yLoc) { 1803 // - its function-body shall be [...] a compound-statement that contains only 1804 switch (S->getStmtClass()) { 1805 case Stmt::NullStmtClass: 1806 // - null statements, 1807 return true; 1808 1809 case Stmt::DeclStmtClass: 1810 // - static_assert-declarations 1811 // - using-declarations, 1812 // - using-directives, 1813 // - typedef declarations and alias-declarations that do not define 1814 // classes or enumerations, 1815 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1816 return false; 1817 return true; 1818 1819 case Stmt::ReturnStmtClass: 1820 // - and exactly one return statement; 1821 if (isa<CXXConstructorDecl>(Dcl)) { 1822 // C++1y allows return statements in constexpr constructors. 1823 if (!Cxx1yLoc.isValid()) 1824 Cxx1yLoc = S->getLocStart(); 1825 return true; 1826 } 1827 1828 ReturnStmts.push_back(S->getLocStart()); 1829 return true; 1830 1831 case Stmt::CompoundStmtClass: { 1832 // C++1y allows compound-statements. 1833 if (!Cxx1yLoc.isValid()) 1834 Cxx1yLoc = S->getLocStart(); 1835 1836 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1837 for (auto *BodyIt : CompStmt->body()) { 1838 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1839 Cxx1yLoc)) 1840 return false; 1841 } 1842 return true; 1843 } 1844 1845 case Stmt::AttributedStmtClass: 1846 if (!Cxx1yLoc.isValid()) 1847 Cxx1yLoc = S->getLocStart(); 1848 return true; 1849 1850 case Stmt::IfStmtClass: { 1851 // C++1y allows if-statements. 1852 if (!Cxx1yLoc.isValid()) 1853 Cxx1yLoc = S->getLocStart(); 1854 1855 IfStmt *If = cast<IfStmt>(S); 1856 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1857 Cxx1yLoc)) 1858 return false; 1859 if (If->getElse() && 1860 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1861 Cxx1yLoc)) 1862 return false; 1863 return true; 1864 } 1865 1866 case Stmt::WhileStmtClass: 1867 case Stmt::DoStmtClass: 1868 case Stmt::ForStmtClass: 1869 case Stmt::CXXForRangeStmtClass: 1870 case Stmt::ContinueStmtClass: 1871 // C++1y allows all of these. We don't allow them as extensions in C++11, 1872 // because they don't make sense without variable mutation. 1873 if (!SemaRef.getLangOpts().CPlusPlus14) 1874 break; 1875 if (!Cxx1yLoc.isValid()) 1876 Cxx1yLoc = S->getLocStart(); 1877 for (Stmt *SubStmt : S->children()) 1878 if (SubStmt && 1879 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1880 Cxx1yLoc)) 1881 return false; 1882 return true; 1883 1884 case Stmt::SwitchStmtClass: 1885 case Stmt::CaseStmtClass: 1886 case Stmt::DefaultStmtClass: 1887 case Stmt::BreakStmtClass: 1888 // C++1y allows switch-statements, and since they don't need variable 1889 // mutation, we can reasonably allow them in C++11 as an extension. 1890 if (!Cxx1yLoc.isValid()) 1891 Cxx1yLoc = S->getLocStart(); 1892 for (Stmt *SubStmt : S->children()) 1893 if (SubStmt && 1894 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1895 Cxx1yLoc)) 1896 return false; 1897 return true; 1898 1899 default: 1900 if (!isa<Expr>(S)) 1901 break; 1902 1903 // C++1y allows expression-statements. 1904 if (!Cxx1yLoc.isValid()) 1905 Cxx1yLoc = S->getLocStart(); 1906 return true; 1907 } 1908 1909 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1910 << isa<CXXConstructorDecl>(Dcl); 1911 return false; 1912 } 1913 1914 /// Check the body for the given constexpr function declaration only contains 1915 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1916 /// 1917 /// \return true if the body is OK, false if we have diagnosed a problem. 1918 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1919 if (isa<CXXTryStmt>(Body)) { 1920 // C++11 [dcl.constexpr]p3: 1921 // The definition of a constexpr function shall satisfy the following 1922 // constraints: [...] 1923 // - its function-body shall be = delete, = default, or a 1924 // compound-statement 1925 // 1926 // C++11 [dcl.constexpr]p4: 1927 // In the definition of a constexpr constructor, [...] 1928 // - its function-body shall not be a function-try-block; 1929 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1930 << isa<CXXConstructorDecl>(Dcl); 1931 return false; 1932 } 1933 1934 SmallVector<SourceLocation, 4> ReturnStmts; 1935 1936 // - its function-body shall be [...] a compound-statement that contains only 1937 // [... list of cases ...] 1938 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1939 SourceLocation Cxx1yLoc; 1940 for (auto *BodyIt : CompBody->body()) { 1941 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1942 return false; 1943 } 1944 1945 if (Cxx1yLoc.isValid()) 1946 Diag(Cxx1yLoc, 1947 getLangOpts().CPlusPlus14 1948 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1949 : diag::ext_constexpr_body_invalid_stmt) 1950 << isa<CXXConstructorDecl>(Dcl); 1951 1952 if (const CXXConstructorDecl *Constructor 1953 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1954 const CXXRecordDecl *RD = Constructor->getParent(); 1955 // DR1359: 1956 // - every non-variant non-static data member and base class sub-object 1957 // shall be initialized; 1958 // DR1460: 1959 // - if the class is a union having variant members, exactly one of them 1960 // shall be initialized; 1961 if (RD->isUnion()) { 1962 if (Constructor->getNumCtorInitializers() == 0 && 1963 RD->hasVariantMembers()) { 1964 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1965 return false; 1966 } 1967 } else if (!Constructor->isDependentContext() && 1968 !Constructor->isDelegatingConstructor()) { 1969 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1970 1971 // Skip detailed checking if we have enough initializers, and we would 1972 // allow at most one initializer per member. 1973 bool AnyAnonStructUnionMembers = false; 1974 unsigned Fields = 0; 1975 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1976 E = RD->field_end(); I != E; ++I, ++Fields) { 1977 if (I->isAnonymousStructOrUnion()) { 1978 AnyAnonStructUnionMembers = true; 1979 break; 1980 } 1981 } 1982 // DR1460: 1983 // - if the class is a union-like class, but is not a union, for each of 1984 // its anonymous union members having variant members, exactly one of 1985 // them shall be initialized; 1986 if (AnyAnonStructUnionMembers || 1987 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1988 // Check initialization of non-static data members. Base classes are 1989 // always initialized so do not need to be checked. Dependent bases 1990 // might not have initializers in the member initializer list. 1991 llvm::SmallSet<Decl*, 16> Inits; 1992 for (const auto *I: Constructor->inits()) { 1993 if (FieldDecl *FD = I->getMember()) 1994 Inits.insert(FD); 1995 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1996 Inits.insert(ID->chain_begin(), ID->chain_end()); 1997 } 1998 1999 bool Diagnosed = false; 2000 for (auto *I : RD->fields()) 2001 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2002 if (Diagnosed) 2003 return false; 2004 } 2005 } 2006 } else { 2007 if (ReturnStmts.empty()) { 2008 // C++1y doesn't require constexpr functions to contain a 'return' 2009 // statement. We still do, unless the return type might be void, because 2010 // otherwise if there's no return statement, the function cannot 2011 // be used in a core constant expression. 2012 bool OK = getLangOpts().CPlusPlus14 && 2013 (Dcl->getReturnType()->isVoidType() || 2014 Dcl->getReturnType()->isDependentType()); 2015 Diag(Dcl->getLocation(), 2016 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2017 : diag::err_constexpr_body_no_return); 2018 if (!OK) 2019 return false; 2020 } else if (ReturnStmts.size() > 1) { 2021 Diag(ReturnStmts.back(), 2022 getLangOpts().CPlusPlus14 2023 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2024 : diag::ext_constexpr_body_multiple_return); 2025 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2026 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2027 } 2028 } 2029 2030 // C++11 [dcl.constexpr]p5: 2031 // if no function argument values exist such that the function invocation 2032 // substitution would produce a constant expression, the program is 2033 // ill-formed; no diagnostic required. 2034 // C++11 [dcl.constexpr]p3: 2035 // - every constructor call and implicit conversion used in initializing the 2036 // return value shall be one of those allowed in a constant expression. 2037 // C++11 [dcl.constexpr]p4: 2038 // - every constructor involved in initializing non-static data members and 2039 // base class sub-objects shall be a constexpr constructor. 2040 SmallVector<PartialDiagnosticAt, 8> Diags; 2041 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2042 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2043 << isa<CXXConstructorDecl>(Dcl); 2044 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2045 Diag(Diags[I].first, Diags[I].second); 2046 // Don't return false here: we allow this for compatibility in 2047 // system headers. 2048 } 2049 2050 return true; 2051 } 2052 2053 /// isCurrentClassName - Determine whether the identifier II is the 2054 /// name of the class type currently being defined. In the case of 2055 /// nested classes, this will only return true if II is the name of 2056 /// the innermost class. 2057 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2058 const CXXScopeSpec *SS) { 2059 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2060 2061 CXXRecordDecl *CurDecl; 2062 if (SS && SS->isSet() && !SS->isInvalid()) { 2063 DeclContext *DC = computeDeclContext(*SS, true); 2064 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2065 } else 2066 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2067 2068 if (CurDecl && CurDecl->getIdentifier()) 2069 return &II == CurDecl->getIdentifier(); 2070 return false; 2071 } 2072 2073 /// \brief Determine whether the identifier II is a typo for the name of 2074 /// the class type currently being defined. If so, update it to the identifier 2075 /// that should have been used. 2076 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2077 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2078 2079 if (!getLangOpts().SpellChecking) 2080 return false; 2081 2082 CXXRecordDecl *CurDecl; 2083 if (SS && SS->isSet() && !SS->isInvalid()) { 2084 DeclContext *DC = computeDeclContext(*SS, true); 2085 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2086 } else 2087 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2088 2089 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2090 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2091 < II->getLength()) { 2092 II = CurDecl->getIdentifier(); 2093 return true; 2094 } 2095 2096 return false; 2097 } 2098 2099 /// \brief Determine whether the given class is a base class of the given 2100 /// class, including looking at dependent bases. 2101 static bool findCircularInheritance(const CXXRecordDecl *Class, 2102 const CXXRecordDecl *Current) { 2103 SmallVector<const CXXRecordDecl*, 8> Queue; 2104 2105 Class = Class->getCanonicalDecl(); 2106 while (true) { 2107 for (const auto &I : Current->bases()) { 2108 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2109 if (!Base) 2110 continue; 2111 2112 Base = Base->getDefinition(); 2113 if (!Base) 2114 continue; 2115 2116 if (Base->getCanonicalDecl() == Class) 2117 return true; 2118 2119 Queue.push_back(Base); 2120 } 2121 2122 if (Queue.empty()) 2123 return false; 2124 2125 Current = Queue.pop_back_val(); 2126 } 2127 2128 return false; 2129 } 2130 2131 /// \brief Check the validity of a C++ base class specifier. 2132 /// 2133 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2134 /// and returns NULL otherwise. 2135 CXXBaseSpecifier * 2136 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2137 SourceRange SpecifierRange, 2138 bool Virtual, AccessSpecifier Access, 2139 TypeSourceInfo *TInfo, 2140 SourceLocation EllipsisLoc) { 2141 QualType BaseType = TInfo->getType(); 2142 2143 // C++ [class.union]p1: 2144 // A union shall not have base classes. 2145 if (Class->isUnion()) { 2146 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2147 << SpecifierRange; 2148 return nullptr; 2149 } 2150 2151 if (EllipsisLoc.isValid() && 2152 !TInfo->getType()->containsUnexpandedParameterPack()) { 2153 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2154 << TInfo->getTypeLoc().getSourceRange(); 2155 EllipsisLoc = SourceLocation(); 2156 } 2157 2158 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2159 2160 if (BaseType->isDependentType()) { 2161 // Make sure that we don't have circular inheritance among our dependent 2162 // bases. For non-dependent bases, the check for completeness below handles 2163 // this. 2164 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2165 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2166 ((BaseDecl = BaseDecl->getDefinition()) && 2167 findCircularInheritance(Class, BaseDecl))) { 2168 Diag(BaseLoc, diag::err_circular_inheritance) 2169 << BaseType << Context.getTypeDeclType(Class); 2170 2171 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2172 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2173 << BaseType; 2174 2175 return nullptr; 2176 } 2177 } 2178 2179 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2180 Class->getTagKind() == TTK_Class, 2181 Access, TInfo, EllipsisLoc); 2182 } 2183 2184 // Base specifiers must be record types. 2185 if (!BaseType->isRecordType()) { 2186 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2187 return nullptr; 2188 } 2189 2190 // C++ [class.union]p1: 2191 // A union shall not be used as a base class. 2192 if (BaseType->isUnionType()) { 2193 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2194 return nullptr; 2195 } 2196 2197 // For the MS ABI, propagate DLL attributes to base class templates. 2198 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2199 if (Attr *ClassAttr = getDLLAttr(Class)) { 2200 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2201 BaseType->getAsCXXRecordDecl())) { 2202 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2203 BaseLoc); 2204 } 2205 } 2206 } 2207 2208 // C++ [class.derived]p2: 2209 // The class-name in a base-specifier shall not be an incompletely 2210 // defined class. 2211 if (RequireCompleteType(BaseLoc, BaseType, 2212 diag::err_incomplete_base_class, SpecifierRange)) { 2213 Class->setInvalidDecl(); 2214 return nullptr; 2215 } 2216 2217 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2218 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2219 assert(BaseDecl && "Record type has no declaration"); 2220 BaseDecl = BaseDecl->getDefinition(); 2221 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2222 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2223 assert(CXXBaseDecl && "Base type is not a C++ type"); 2224 2225 // A class which contains a flexible array member is not suitable for use as a 2226 // base class: 2227 // - If the layout determines that a base comes before another base, 2228 // the flexible array member would index into the subsequent base. 2229 // - If the layout determines that base comes before the derived class, 2230 // the flexible array member would index into the derived class. 2231 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2232 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2233 << CXXBaseDecl->getDeclName(); 2234 return nullptr; 2235 } 2236 2237 // C++ [class]p3: 2238 // If a class is marked final and it appears as a base-type-specifier in 2239 // base-clause, the program is ill-formed. 2240 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2241 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2242 << CXXBaseDecl->getDeclName() 2243 << FA->isSpelledAsSealed(); 2244 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2245 << CXXBaseDecl->getDeclName() << FA->getRange(); 2246 return nullptr; 2247 } 2248 2249 if (BaseDecl->isInvalidDecl()) 2250 Class->setInvalidDecl(); 2251 2252 // Create the base specifier. 2253 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2254 Class->getTagKind() == TTK_Class, 2255 Access, TInfo, EllipsisLoc); 2256 } 2257 2258 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2259 /// one entry in the base class list of a class specifier, for 2260 /// example: 2261 /// class foo : public bar, virtual private baz { 2262 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2263 BaseResult 2264 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2265 ParsedAttributes &Attributes, 2266 bool Virtual, AccessSpecifier Access, 2267 ParsedType basetype, SourceLocation BaseLoc, 2268 SourceLocation EllipsisLoc) { 2269 if (!classdecl) 2270 return true; 2271 2272 AdjustDeclIfTemplate(classdecl); 2273 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2274 if (!Class) 2275 return true; 2276 2277 // We haven't yet attached the base specifiers. 2278 Class->setIsParsingBaseSpecifiers(); 2279 2280 // We do not support any C++11 attributes on base-specifiers yet. 2281 // Diagnose any attributes we see. 2282 if (!Attributes.empty()) { 2283 for (AttributeList *Attr = Attributes.getList(); Attr; 2284 Attr = Attr->getNext()) { 2285 if (Attr->isInvalid() || 2286 Attr->getKind() == AttributeList::IgnoredAttribute) 2287 continue; 2288 Diag(Attr->getLoc(), 2289 Attr->getKind() == AttributeList::UnknownAttribute 2290 ? diag::warn_unknown_attribute_ignored 2291 : diag::err_base_specifier_attribute) 2292 << Attr->getName(); 2293 } 2294 } 2295 2296 TypeSourceInfo *TInfo = nullptr; 2297 GetTypeFromParser(basetype, &TInfo); 2298 2299 if (EllipsisLoc.isInvalid() && 2300 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2301 UPPC_BaseType)) 2302 return true; 2303 2304 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2305 Virtual, Access, TInfo, 2306 EllipsisLoc)) 2307 return BaseSpec; 2308 else 2309 Class->setInvalidDecl(); 2310 2311 return true; 2312 } 2313 2314 /// Use small set to collect indirect bases. As this is only used 2315 /// locally, there's no need to abstract the small size parameter. 2316 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2317 2318 /// \brief Recursively add the bases of Type. Don't add Type itself. 2319 static void 2320 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2321 const QualType &Type) 2322 { 2323 // Even though the incoming type is a base, it might not be 2324 // a class -- it could be a template parm, for instance. 2325 if (auto Rec = Type->getAs<RecordType>()) { 2326 auto Decl = Rec->getAsCXXRecordDecl(); 2327 2328 // Iterate over its bases. 2329 for (const auto &BaseSpec : Decl->bases()) { 2330 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2331 .getUnqualifiedType(); 2332 if (Set.insert(Base).second) 2333 // If we've not already seen it, recurse. 2334 NoteIndirectBases(Context, Set, Base); 2335 } 2336 } 2337 } 2338 2339 /// \brief Performs the actual work of attaching the given base class 2340 /// specifiers to a C++ class. 2341 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2342 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2343 if (Bases.empty()) 2344 return false; 2345 2346 // Used to keep track of which base types we have already seen, so 2347 // that we can properly diagnose redundant direct base types. Note 2348 // that the key is always the unqualified canonical type of the base 2349 // class. 2350 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2351 2352 // Used to track indirect bases so we can see if a direct base is 2353 // ambiguous. 2354 IndirectBaseSet IndirectBaseTypes; 2355 2356 // Copy non-redundant base specifiers into permanent storage. 2357 unsigned NumGoodBases = 0; 2358 bool Invalid = false; 2359 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2360 QualType NewBaseType 2361 = Context.getCanonicalType(Bases[idx]->getType()); 2362 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2363 2364 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2365 if (KnownBase) { 2366 // C++ [class.mi]p3: 2367 // A class shall not be specified as a direct base class of a 2368 // derived class more than once. 2369 Diag(Bases[idx]->getLocStart(), 2370 diag::err_duplicate_base_class) 2371 << KnownBase->getType() 2372 << Bases[idx]->getSourceRange(); 2373 2374 // Delete the duplicate base class specifier; we're going to 2375 // overwrite its pointer later. 2376 Context.Deallocate(Bases[idx]); 2377 2378 Invalid = true; 2379 } else { 2380 // Okay, add this new base class. 2381 KnownBase = Bases[idx]; 2382 Bases[NumGoodBases++] = Bases[idx]; 2383 2384 // Note this base's direct & indirect bases, if there could be ambiguity. 2385 if (Bases.size() > 1) 2386 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2387 2388 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2389 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2390 if (Class->isInterface() && 2391 (!RD->isInterfaceLike() || 2392 KnownBase->getAccessSpecifier() != AS_public)) { 2393 // The Microsoft extension __interface does not permit bases that 2394 // are not themselves public interfaces. 2395 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2396 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 2397 << RD->getSourceRange(); 2398 Invalid = true; 2399 } 2400 if (RD->hasAttr<WeakAttr>()) 2401 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2402 } 2403 } 2404 } 2405 2406 // Attach the remaining base class specifiers to the derived class. 2407 Class->setBases(Bases.data(), NumGoodBases); 2408 2409 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2410 // Check whether this direct base is inaccessible due to ambiguity. 2411 QualType BaseType = Bases[idx]->getType(); 2412 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2413 .getUnqualifiedType(); 2414 2415 if (IndirectBaseTypes.count(CanonicalBase)) { 2416 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2417 /*DetectVirtual=*/true); 2418 bool found 2419 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2420 assert(found); 2421 (void)found; 2422 2423 if (Paths.isAmbiguous(CanonicalBase)) 2424 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2425 << BaseType << getAmbiguousPathsDisplayString(Paths) 2426 << Bases[idx]->getSourceRange(); 2427 else 2428 assert(Bases[idx]->isVirtual()); 2429 } 2430 2431 // Delete the base class specifier, since its data has been copied 2432 // into the CXXRecordDecl. 2433 Context.Deallocate(Bases[idx]); 2434 } 2435 2436 return Invalid; 2437 } 2438 2439 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2440 /// class, after checking whether there are any duplicate base 2441 /// classes. 2442 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2443 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2444 if (!ClassDecl || Bases.empty()) 2445 return; 2446 2447 AdjustDeclIfTemplate(ClassDecl); 2448 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2449 } 2450 2451 /// \brief Determine whether the type \p Derived is a C++ class that is 2452 /// derived from the type \p Base. 2453 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2454 if (!getLangOpts().CPlusPlus) 2455 return false; 2456 2457 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2458 if (!DerivedRD) 2459 return false; 2460 2461 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2462 if (!BaseRD) 2463 return false; 2464 2465 // If either the base or the derived type is invalid, don't try to 2466 // check whether one is derived from the other. 2467 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2468 return false; 2469 2470 // FIXME: In a modules build, do we need the entire path to be visible for us 2471 // to be able to use the inheritance relationship? 2472 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2473 return false; 2474 2475 return DerivedRD->isDerivedFrom(BaseRD); 2476 } 2477 2478 /// \brief Determine whether the type \p Derived is a C++ class that is 2479 /// derived from the type \p Base. 2480 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2481 CXXBasePaths &Paths) { 2482 if (!getLangOpts().CPlusPlus) 2483 return false; 2484 2485 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2486 if (!DerivedRD) 2487 return false; 2488 2489 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2490 if (!BaseRD) 2491 return false; 2492 2493 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2494 return false; 2495 2496 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2497 } 2498 2499 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2500 CXXCastPath &BasePathArray) { 2501 assert(BasePathArray.empty() && "Base path array must be empty!"); 2502 assert(Paths.isRecordingPaths() && "Must record paths!"); 2503 2504 const CXXBasePath &Path = Paths.front(); 2505 2506 // We first go backward and check if we have a virtual base. 2507 // FIXME: It would be better if CXXBasePath had the base specifier for 2508 // the nearest virtual base. 2509 unsigned Start = 0; 2510 for (unsigned I = Path.size(); I != 0; --I) { 2511 if (Path[I - 1].Base->isVirtual()) { 2512 Start = I - 1; 2513 break; 2514 } 2515 } 2516 2517 // Now add all bases. 2518 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2519 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2520 } 2521 2522 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2523 /// conversion (where Derived and Base are class types) is 2524 /// well-formed, meaning that the conversion is unambiguous (and 2525 /// that all of the base classes are accessible). Returns true 2526 /// and emits a diagnostic if the code is ill-formed, returns false 2527 /// otherwise. Loc is the location where this routine should point to 2528 /// if there is an error, and Range is the source range to highlight 2529 /// if there is an error. 2530 /// 2531 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2532 /// diagnostic for the respective type of error will be suppressed, but the 2533 /// check for ill-formed code will still be performed. 2534 bool 2535 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2536 unsigned InaccessibleBaseID, 2537 unsigned AmbigiousBaseConvID, 2538 SourceLocation Loc, SourceRange Range, 2539 DeclarationName Name, 2540 CXXCastPath *BasePath, 2541 bool IgnoreAccess) { 2542 // First, determine whether the path from Derived to Base is 2543 // ambiguous. This is slightly more expensive than checking whether 2544 // the Derived to Base conversion exists, because here we need to 2545 // explore multiple paths to determine if there is an ambiguity. 2546 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2547 /*DetectVirtual=*/false); 2548 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2549 assert(DerivationOkay && 2550 "Can only be used with a derived-to-base conversion"); 2551 (void)DerivationOkay; 2552 2553 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 2554 if (!IgnoreAccess) { 2555 // Check that the base class can be accessed. 2556 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 2557 InaccessibleBaseID)) { 2558 case AR_inaccessible: 2559 return true; 2560 case AR_accessible: 2561 case AR_dependent: 2562 case AR_delayed: 2563 break; 2564 } 2565 } 2566 2567 // Build a base path if necessary. 2568 if (BasePath) 2569 BuildBasePathArray(Paths, *BasePath); 2570 return false; 2571 } 2572 2573 if (AmbigiousBaseConvID) { 2574 // We know that the derived-to-base conversion is ambiguous, and 2575 // we're going to produce a diagnostic. Perform the derived-to-base 2576 // search just one more time to compute all of the possible paths so 2577 // that we can print them out. This is more expensive than any of 2578 // the previous derived-to-base checks we've done, but at this point 2579 // performance isn't as much of an issue. 2580 Paths.clear(); 2581 Paths.setRecordingPaths(true); 2582 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2583 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2584 (void)StillOkay; 2585 2586 // Build up a textual representation of the ambiguous paths, e.g., 2587 // D -> B -> A, that will be used to illustrate the ambiguous 2588 // conversions in the diagnostic. We only print one of the paths 2589 // to each base class subobject. 2590 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2591 2592 Diag(Loc, AmbigiousBaseConvID) 2593 << Derived << Base << PathDisplayStr << Range << Name; 2594 } 2595 return true; 2596 } 2597 2598 bool 2599 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2600 SourceLocation Loc, SourceRange Range, 2601 CXXCastPath *BasePath, 2602 bool IgnoreAccess) { 2603 return CheckDerivedToBaseConversion( 2604 Derived, Base, diag::err_upcast_to_inaccessible_base, 2605 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2606 BasePath, IgnoreAccess); 2607 } 2608 2609 2610 /// @brief Builds a string representing ambiguous paths from a 2611 /// specific derived class to different subobjects of the same base 2612 /// class. 2613 /// 2614 /// This function builds a string that can be used in error messages 2615 /// to show the different paths that one can take through the 2616 /// inheritance hierarchy to go from the derived class to different 2617 /// subobjects of a base class. The result looks something like this: 2618 /// @code 2619 /// struct D -> struct B -> struct A 2620 /// struct D -> struct C -> struct A 2621 /// @endcode 2622 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2623 std::string PathDisplayStr; 2624 std::set<unsigned> DisplayedPaths; 2625 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2626 Path != Paths.end(); ++Path) { 2627 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2628 // We haven't displayed a path to this particular base 2629 // class subobject yet. 2630 PathDisplayStr += "\n "; 2631 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2632 for (CXXBasePath::const_iterator Element = Path->begin(); 2633 Element != Path->end(); ++Element) 2634 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2635 } 2636 } 2637 2638 return PathDisplayStr; 2639 } 2640 2641 //===----------------------------------------------------------------------===// 2642 // C++ class member Handling 2643 //===----------------------------------------------------------------------===// 2644 2645 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2646 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2647 SourceLocation ASLoc, 2648 SourceLocation ColonLoc, 2649 AttributeList *Attrs) { 2650 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2651 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2652 ASLoc, ColonLoc); 2653 CurContext->addHiddenDecl(ASDecl); 2654 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2655 } 2656 2657 /// CheckOverrideControl - Check C++11 override control semantics. 2658 void Sema::CheckOverrideControl(NamedDecl *D) { 2659 if (D->isInvalidDecl()) 2660 return; 2661 2662 // We only care about "override" and "final" declarations. 2663 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2664 return; 2665 2666 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2667 2668 // We can't check dependent instance methods. 2669 if (MD && MD->isInstance() && 2670 (MD->getParent()->hasAnyDependentBases() || 2671 MD->getType()->isDependentType())) 2672 return; 2673 2674 if (MD && !MD->isVirtual()) { 2675 // If we have a non-virtual method, check if if hides a virtual method. 2676 // (In that case, it's most likely the method has the wrong type.) 2677 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2678 FindHiddenVirtualMethods(MD, OverloadedMethods); 2679 2680 if (!OverloadedMethods.empty()) { 2681 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2682 Diag(OA->getLocation(), 2683 diag::override_keyword_hides_virtual_member_function) 2684 << "override" << (OverloadedMethods.size() > 1); 2685 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2686 Diag(FA->getLocation(), 2687 diag::override_keyword_hides_virtual_member_function) 2688 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2689 << (OverloadedMethods.size() > 1); 2690 } 2691 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2692 MD->setInvalidDecl(); 2693 return; 2694 } 2695 // Fall through into the general case diagnostic. 2696 // FIXME: We might want to attempt typo correction here. 2697 } 2698 2699 if (!MD || !MD->isVirtual()) { 2700 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2701 Diag(OA->getLocation(), 2702 diag::override_keyword_only_allowed_on_virtual_member_functions) 2703 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2704 D->dropAttr<OverrideAttr>(); 2705 } 2706 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2707 Diag(FA->getLocation(), 2708 diag::override_keyword_only_allowed_on_virtual_member_functions) 2709 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2710 << FixItHint::CreateRemoval(FA->getLocation()); 2711 D->dropAttr<FinalAttr>(); 2712 } 2713 return; 2714 } 2715 2716 // C++11 [class.virtual]p5: 2717 // If a function is marked with the virt-specifier override and 2718 // does not override a member function of a base class, the program is 2719 // ill-formed. 2720 bool HasOverriddenMethods = 2721 MD->begin_overridden_methods() != MD->end_overridden_methods(); 2722 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2723 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2724 << MD->getDeclName(); 2725 } 2726 2727 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2728 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2729 return; 2730 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2731 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2732 return; 2733 2734 SourceLocation Loc = MD->getLocation(); 2735 SourceLocation SpellingLoc = Loc; 2736 if (getSourceManager().isMacroArgExpansion(Loc)) 2737 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 2738 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2739 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2740 return; 2741 2742 if (MD->size_overridden_methods() > 0) { 2743 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2744 ? diag::warn_destructor_marked_not_override_overriding 2745 : diag::warn_function_marked_not_override_overriding; 2746 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2747 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2748 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2749 } 2750 } 2751 2752 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2753 /// function overrides a virtual member function marked 'final', according to 2754 /// C++11 [class.virtual]p4. 2755 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2756 const CXXMethodDecl *Old) { 2757 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2758 if (!FA) 2759 return false; 2760 2761 Diag(New->getLocation(), diag::err_final_function_overridden) 2762 << New->getDeclName() 2763 << FA->isSpelledAsSealed(); 2764 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2765 return true; 2766 } 2767 2768 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2769 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2770 // FIXME: Destruction of ObjC lifetime types has side-effects. 2771 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2772 return !RD->isCompleteDefinition() || 2773 !RD->hasTrivialDefaultConstructor() || 2774 !RD->hasTrivialDestructor(); 2775 return false; 2776 } 2777 2778 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2779 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2780 if (it->isDeclspecPropertyAttribute()) 2781 return it; 2782 return nullptr; 2783 } 2784 2785 // Check if there is a field shadowing. 2786 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2787 DeclarationName FieldName, 2788 const CXXRecordDecl *RD) { 2789 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2790 return; 2791 2792 // To record a shadowed field in a base 2793 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2794 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2795 CXXBasePath &Path) { 2796 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2797 // Record an ambiguous path directly 2798 if (Bases.find(Base) != Bases.end()) 2799 return true; 2800 for (const auto Field : Base->lookup(FieldName)) { 2801 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2802 Field->getAccess() != AS_private) { 2803 assert(Field->getAccess() != AS_none); 2804 assert(Bases.find(Base) == Bases.end()); 2805 Bases[Base] = Field; 2806 return true; 2807 } 2808 } 2809 return false; 2810 }; 2811 2812 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2813 /*DetectVirtual=*/true); 2814 if (!RD->lookupInBases(FieldShadowed, Paths)) 2815 return; 2816 2817 for (const auto &P : Paths) { 2818 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2819 auto It = Bases.find(Base); 2820 // Skip duplicated bases 2821 if (It == Bases.end()) 2822 continue; 2823 auto BaseField = It->second; 2824 assert(BaseField->getAccess() != AS_private); 2825 if (AS_none != 2826 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2827 Diag(Loc, diag::warn_shadow_field) 2828 << FieldName.getAsString() << RD->getName() << Base->getName(); 2829 Diag(BaseField->getLocation(), diag::note_shadow_field); 2830 Bases.erase(It); 2831 } 2832 } 2833 } 2834 2835 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2836 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2837 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2838 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2839 /// present (but parsing it has been deferred). 2840 NamedDecl * 2841 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2842 MultiTemplateParamsArg TemplateParameterLists, 2843 Expr *BW, const VirtSpecifiers &VS, 2844 InClassInitStyle InitStyle) { 2845 const DeclSpec &DS = D.getDeclSpec(); 2846 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2847 DeclarationName Name = NameInfo.getName(); 2848 SourceLocation Loc = NameInfo.getLoc(); 2849 2850 // For anonymous bitfields, the location should point to the type. 2851 if (Loc.isInvalid()) 2852 Loc = D.getLocStart(); 2853 2854 Expr *BitWidth = static_cast<Expr*>(BW); 2855 2856 assert(isa<CXXRecordDecl>(CurContext)); 2857 assert(!DS.isFriendSpecified()); 2858 2859 bool isFunc = D.isDeclarationOfFunction(); 2860 AttributeList *MSPropertyAttr = 2861 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2862 2863 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2864 // The Microsoft extension __interface only permits public member functions 2865 // and prohibits constructors, destructors, operators, non-public member 2866 // functions, static methods and data members. 2867 unsigned InvalidDecl; 2868 bool ShowDeclName = true; 2869 if (!isFunc && 2870 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2871 InvalidDecl = 0; 2872 else if (!isFunc) 2873 InvalidDecl = 1; 2874 else if (AS != AS_public) 2875 InvalidDecl = 2; 2876 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2877 InvalidDecl = 3; 2878 else switch (Name.getNameKind()) { 2879 case DeclarationName::CXXConstructorName: 2880 InvalidDecl = 4; 2881 ShowDeclName = false; 2882 break; 2883 2884 case DeclarationName::CXXDestructorName: 2885 InvalidDecl = 5; 2886 ShowDeclName = false; 2887 break; 2888 2889 case DeclarationName::CXXOperatorName: 2890 case DeclarationName::CXXConversionFunctionName: 2891 InvalidDecl = 6; 2892 break; 2893 2894 default: 2895 InvalidDecl = 0; 2896 break; 2897 } 2898 2899 if (InvalidDecl) { 2900 if (ShowDeclName) 2901 Diag(Loc, diag::err_invalid_member_in_interface) 2902 << (InvalidDecl-1) << Name; 2903 else 2904 Diag(Loc, diag::err_invalid_member_in_interface) 2905 << (InvalidDecl-1) << ""; 2906 return nullptr; 2907 } 2908 } 2909 2910 // C++ 9.2p6: A member shall not be declared to have automatic storage 2911 // duration (auto, register) or with the extern storage-class-specifier. 2912 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2913 // data members and cannot be applied to names declared const or static, 2914 // and cannot be applied to reference members. 2915 switch (DS.getStorageClassSpec()) { 2916 case DeclSpec::SCS_unspecified: 2917 case DeclSpec::SCS_typedef: 2918 case DeclSpec::SCS_static: 2919 break; 2920 case DeclSpec::SCS_mutable: 2921 if (isFunc) { 2922 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2923 2924 // FIXME: It would be nicer if the keyword was ignored only for this 2925 // declarator. Otherwise we could get follow-up errors. 2926 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2927 } 2928 break; 2929 default: 2930 Diag(DS.getStorageClassSpecLoc(), 2931 diag::err_storageclass_invalid_for_member); 2932 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2933 break; 2934 } 2935 2936 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2937 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2938 !isFunc); 2939 2940 if (DS.isConstexprSpecified() && isInstField) { 2941 SemaDiagnosticBuilder B = 2942 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2943 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2944 if (InitStyle == ICIS_NoInit) { 2945 B << 0 << 0; 2946 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2947 B << FixItHint::CreateRemoval(ConstexprLoc); 2948 else { 2949 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2950 D.getMutableDeclSpec().ClearConstexprSpec(); 2951 const char *PrevSpec; 2952 unsigned DiagID; 2953 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2954 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2955 (void)Failed; 2956 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2957 } 2958 } else { 2959 B << 1; 2960 const char *PrevSpec; 2961 unsigned DiagID; 2962 if (D.getMutableDeclSpec().SetStorageClassSpec( 2963 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2964 Context.getPrintingPolicy())) { 2965 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2966 "This is the only DeclSpec that should fail to be applied"); 2967 B << 1; 2968 } else { 2969 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2970 isInstField = false; 2971 } 2972 } 2973 } 2974 2975 NamedDecl *Member; 2976 if (isInstField) { 2977 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2978 2979 // Data members must have identifiers for names. 2980 if (!Name.isIdentifier()) { 2981 Diag(Loc, diag::err_bad_variable_name) 2982 << Name; 2983 return nullptr; 2984 } 2985 2986 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2987 2988 // Member field could not be with "template" keyword. 2989 // So TemplateParameterLists should be empty in this case. 2990 if (TemplateParameterLists.size()) { 2991 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2992 if (TemplateParams->size()) { 2993 // There is no such thing as a member field template. 2994 Diag(D.getIdentifierLoc(), diag::err_template_member) 2995 << II 2996 << SourceRange(TemplateParams->getTemplateLoc(), 2997 TemplateParams->getRAngleLoc()); 2998 } else { 2999 // There is an extraneous 'template<>' for this member. 3000 Diag(TemplateParams->getTemplateLoc(), 3001 diag::err_template_member_noparams) 3002 << II 3003 << SourceRange(TemplateParams->getTemplateLoc(), 3004 TemplateParams->getRAngleLoc()); 3005 } 3006 return nullptr; 3007 } 3008 3009 if (SS.isSet() && !SS.isInvalid()) { 3010 // The user provided a superfluous scope specifier inside a class 3011 // definition: 3012 // 3013 // class X { 3014 // int X::member; 3015 // }; 3016 if (DeclContext *DC = computeDeclContext(SS, false)) 3017 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 3018 else 3019 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3020 << Name << SS.getRange(); 3021 3022 SS.clear(); 3023 } 3024 3025 if (MSPropertyAttr) { 3026 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3027 BitWidth, InitStyle, AS, MSPropertyAttr); 3028 if (!Member) 3029 return nullptr; 3030 isInstField = false; 3031 } else { 3032 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3033 BitWidth, InitStyle, AS); 3034 if (!Member) 3035 return nullptr; 3036 } 3037 3038 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3039 } else { 3040 Member = HandleDeclarator(S, D, TemplateParameterLists); 3041 if (!Member) 3042 return nullptr; 3043 3044 // Non-instance-fields can't have a bitfield. 3045 if (BitWidth) { 3046 if (Member->isInvalidDecl()) { 3047 // don't emit another diagnostic. 3048 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3049 // C++ 9.6p3: A bit-field shall not be a static member. 3050 // "static member 'A' cannot be a bit-field" 3051 Diag(Loc, diag::err_static_not_bitfield) 3052 << Name << BitWidth->getSourceRange(); 3053 } else if (isa<TypedefDecl>(Member)) { 3054 // "typedef member 'x' cannot be a bit-field" 3055 Diag(Loc, diag::err_typedef_not_bitfield) 3056 << Name << BitWidth->getSourceRange(); 3057 } else { 3058 // A function typedef ("typedef int f(); f a;"). 3059 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3060 Diag(Loc, diag::err_not_integral_type_bitfield) 3061 << Name << cast<ValueDecl>(Member)->getType() 3062 << BitWidth->getSourceRange(); 3063 } 3064 3065 BitWidth = nullptr; 3066 Member->setInvalidDecl(); 3067 } 3068 3069 Member->setAccess(AS); 3070 3071 // If we have declared a member function template or static data member 3072 // template, set the access of the templated declaration as well. 3073 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3074 FunTmpl->getTemplatedDecl()->setAccess(AS); 3075 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3076 VarTmpl->getTemplatedDecl()->setAccess(AS); 3077 } 3078 3079 if (VS.isOverrideSpecified()) 3080 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3081 if (VS.isFinalSpecified()) 3082 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3083 VS.isFinalSpelledSealed())); 3084 3085 if (VS.getLastLocation().isValid()) { 3086 // Update the end location of a method that has a virt-specifiers. 3087 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3088 MD->setRangeEnd(VS.getLastLocation()); 3089 } 3090 3091 CheckOverrideControl(Member); 3092 3093 assert((Name || isInstField) && "No identifier for non-field ?"); 3094 3095 if (isInstField) { 3096 FieldDecl *FD = cast<FieldDecl>(Member); 3097 FieldCollector->Add(FD); 3098 3099 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3100 // Remember all explicit private FieldDecls that have a name, no side 3101 // effects and are not part of a dependent type declaration. 3102 if (!FD->isImplicit() && FD->getDeclName() && 3103 FD->getAccess() == AS_private && 3104 !FD->hasAttr<UnusedAttr>() && 3105 !FD->getParent()->isDependentContext() && 3106 !InitializationHasSideEffects(*FD)) 3107 UnusedPrivateFields.insert(FD); 3108 } 3109 } 3110 3111 return Member; 3112 } 3113 3114 namespace { 3115 class UninitializedFieldVisitor 3116 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3117 Sema &S; 3118 // List of Decls to generate a warning on. Also remove Decls that become 3119 // initialized. 3120 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3121 // List of base classes of the record. Classes are removed after their 3122 // initializers. 3123 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3124 // Vector of decls to be removed from the Decl set prior to visiting the 3125 // nodes. These Decls may have been initialized in the prior initializer. 3126 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3127 // If non-null, add a note to the warning pointing back to the constructor. 3128 const CXXConstructorDecl *Constructor; 3129 // Variables to hold state when processing an initializer list. When 3130 // InitList is true, special case initialization of FieldDecls matching 3131 // InitListFieldDecl. 3132 bool InitList; 3133 FieldDecl *InitListFieldDecl; 3134 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3135 3136 public: 3137 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3138 UninitializedFieldVisitor(Sema &S, 3139 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3140 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3141 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3142 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3143 3144 // Returns true if the use of ME is not an uninitialized use. 3145 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3146 bool CheckReferenceOnly) { 3147 llvm::SmallVector<FieldDecl*, 4> Fields; 3148 bool ReferenceField = false; 3149 while (ME) { 3150 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3151 if (!FD) 3152 return false; 3153 Fields.push_back(FD); 3154 if (FD->getType()->isReferenceType()) 3155 ReferenceField = true; 3156 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3157 } 3158 3159 // Binding a reference to an unintialized field is not an 3160 // uninitialized use. 3161 if (CheckReferenceOnly && !ReferenceField) 3162 return true; 3163 3164 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3165 // Discard the first field since it is the field decl that is being 3166 // initialized. 3167 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3168 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3169 } 3170 3171 for (auto UsedIter = UsedFieldIndex.begin(), 3172 UsedEnd = UsedFieldIndex.end(), 3173 OrigIter = InitFieldIndex.begin(), 3174 OrigEnd = InitFieldIndex.end(); 3175 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3176 if (*UsedIter < *OrigIter) 3177 return true; 3178 if (*UsedIter > *OrigIter) 3179 break; 3180 } 3181 3182 return false; 3183 } 3184 3185 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3186 bool AddressOf) { 3187 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3188 return; 3189 3190 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3191 // or union. 3192 MemberExpr *FieldME = ME; 3193 3194 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3195 3196 Expr *Base = ME; 3197 while (MemberExpr *SubME = 3198 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3199 3200 if (isa<VarDecl>(SubME->getMemberDecl())) 3201 return; 3202 3203 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3204 if (!FD->isAnonymousStructOrUnion()) 3205 FieldME = SubME; 3206 3207 if (!FieldME->getType().isPODType(S.Context)) 3208 AllPODFields = false; 3209 3210 Base = SubME->getBase(); 3211 } 3212 3213 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3214 return; 3215 3216 if (AddressOf && AllPODFields) 3217 return; 3218 3219 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3220 3221 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3222 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3223 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3224 } 3225 3226 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3227 QualType T = BaseCast->getType(); 3228 if (T->isPointerType() && 3229 BaseClasses.count(T->getPointeeType())) { 3230 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3231 << T->getPointeeType() << FoundVD; 3232 } 3233 } 3234 } 3235 3236 if (!Decls.count(FoundVD)) 3237 return; 3238 3239 const bool IsReference = FoundVD->getType()->isReferenceType(); 3240 3241 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3242 // Special checking for initializer lists. 3243 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3244 return; 3245 } 3246 } else { 3247 // Prevent double warnings on use of unbounded references. 3248 if (CheckReferenceOnly && !IsReference) 3249 return; 3250 } 3251 3252 unsigned diag = IsReference 3253 ? diag::warn_reference_field_is_uninit 3254 : diag::warn_field_is_uninit; 3255 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3256 if (Constructor) 3257 S.Diag(Constructor->getLocation(), 3258 diag::note_uninit_in_this_constructor) 3259 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3260 3261 } 3262 3263 void HandleValue(Expr *E, bool AddressOf) { 3264 E = E->IgnoreParens(); 3265 3266 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3267 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3268 AddressOf /*AddressOf*/); 3269 return; 3270 } 3271 3272 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3273 Visit(CO->getCond()); 3274 HandleValue(CO->getTrueExpr(), AddressOf); 3275 HandleValue(CO->getFalseExpr(), AddressOf); 3276 return; 3277 } 3278 3279 if (BinaryConditionalOperator *BCO = 3280 dyn_cast<BinaryConditionalOperator>(E)) { 3281 Visit(BCO->getCond()); 3282 HandleValue(BCO->getFalseExpr(), AddressOf); 3283 return; 3284 } 3285 3286 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3287 HandleValue(OVE->getSourceExpr(), AddressOf); 3288 return; 3289 } 3290 3291 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3292 switch (BO->getOpcode()) { 3293 default: 3294 break; 3295 case(BO_PtrMemD): 3296 case(BO_PtrMemI): 3297 HandleValue(BO->getLHS(), AddressOf); 3298 Visit(BO->getRHS()); 3299 return; 3300 case(BO_Comma): 3301 Visit(BO->getLHS()); 3302 HandleValue(BO->getRHS(), AddressOf); 3303 return; 3304 } 3305 } 3306 3307 Visit(E); 3308 } 3309 3310 void CheckInitListExpr(InitListExpr *ILE) { 3311 InitFieldIndex.push_back(0); 3312 for (auto Child : ILE->children()) { 3313 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3314 CheckInitListExpr(SubList); 3315 } else { 3316 Visit(Child); 3317 } 3318 ++InitFieldIndex.back(); 3319 } 3320 InitFieldIndex.pop_back(); 3321 } 3322 3323 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3324 FieldDecl *Field, const Type *BaseClass) { 3325 // Remove Decls that may have been initialized in the previous 3326 // initializer. 3327 for (ValueDecl* VD : DeclsToRemove) 3328 Decls.erase(VD); 3329 DeclsToRemove.clear(); 3330 3331 Constructor = FieldConstructor; 3332 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3333 3334 if (ILE && Field) { 3335 InitList = true; 3336 InitListFieldDecl = Field; 3337 InitFieldIndex.clear(); 3338 CheckInitListExpr(ILE); 3339 } else { 3340 InitList = false; 3341 Visit(E); 3342 } 3343 3344 if (Field) 3345 Decls.erase(Field); 3346 if (BaseClass) 3347 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3348 } 3349 3350 void VisitMemberExpr(MemberExpr *ME) { 3351 // All uses of unbounded reference fields will warn. 3352 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3353 } 3354 3355 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3356 if (E->getCastKind() == CK_LValueToRValue) { 3357 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3358 return; 3359 } 3360 3361 Inherited::VisitImplicitCastExpr(E); 3362 } 3363 3364 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3365 if (E->getConstructor()->isCopyConstructor()) { 3366 Expr *ArgExpr = E->getArg(0); 3367 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3368 if (ILE->getNumInits() == 1) 3369 ArgExpr = ILE->getInit(0); 3370 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3371 if (ICE->getCastKind() == CK_NoOp) 3372 ArgExpr = ICE->getSubExpr(); 3373 HandleValue(ArgExpr, false /*AddressOf*/); 3374 return; 3375 } 3376 Inherited::VisitCXXConstructExpr(E); 3377 } 3378 3379 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3380 Expr *Callee = E->getCallee(); 3381 if (isa<MemberExpr>(Callee)) { 3382 HandleValue(Callee, false /*AddressOf*/); 3383 for (auto Arg : E->arguments()) 3384 Visit(Arg); 3385 return; 3386 } 3387 3388 Inherited::VisitCXXMemberCallExpr(E); 3389 } 3390 3391 void VisitCallExpr(CallExpr *E) { 3392 // Treat std::move as a use. 3393 if (E->getNumArgs() == 1) { 3394 if (FunctionDecl *FD = E->getDirectCallee()) { 3395 if (FD->isInStdNamespace() && FD->getIdentifier() && 3396 FD->getIdentifier()->isStr("move")) { 3397 HandleValue(E->getArg(0), false /*AddressOf*/); 3398 return; 3399 } 3400 } 3401 } 3402 3403 Inherited::VisitCallExpr(E); 3404 } 3405 3406 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3407 Expr *Callee = E->getCallee(); 3408 3409 if (isa<UnresolvedLookupExpr>(Callee)) 3410 return Inherited::VisitCXXOperatorCallExpr(E); 3411 3412 Visit(Callee); 3413 for (auto Arg : E->arguments()) 3414 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3415 } 3416 3417 void VisitBinaryOperator(BinaryOperator *E) { 3418 // If a field assignment is detected, remove the field from the 3419 // uninitiailized field set. 3420 if (E->getOpcode() == BO_Assign) 3421 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3422 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3423 if (!FD->getType()->isReferenceType()) 3424 DeclsToRemove.push_back(FD); 3425 3426 if (E->isCompoundAssignmentOp()) { 3427 HandleValue(E->getLHS(), false /*AddressOf*/); 3428 Visit(E->getRHS()); 3429 return; 3430 } 3431 3432 Inherited::VisitBinaryOperator(E); 3433 } 3434 3435 void VisitUnaryOperator(UnaryOperator *E) { 3436 if (E->isIncrementDecrementOp()) { 3437 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3438 return; 3439 } 3440 if (E->getOpcode() == UO_AddrOf) { 3441 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3442 HandleValue(ME->getBase(), true /*AddressOf*/); 3443 return; 3444 } 3445 } 3446 3447 Inherited::VisitUnaryOperator(E); 3448 } 3449 }; 3450 3451 // Diagnose value-uses of fields to initialize themselves, e.g. 3452 // foo(foo) 3453 // where foo is not also a parameter to the constructor. 3454 // Also diagnose across field uninitialized use such as 3455 // x(y), y(x) 3456 // TODO: implement -Wuninitialized and fold this into that framework. 3457 static void DiagnoseUninitializedFields( 3458 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3459 3460 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3461 Constructor->getLocation())) { 3462 return; 3463 } 3464 3465 if (Constructor->isInvalidDecl()) 3466 return; 3467 3468 const CXXRecordDecl *RD = Constructor->getParent(); 3469 3470 if (RD->getDescribedClassTemplate()) 3471 return; 3472 3473 // Holds fields that are uninitialized. 3474 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3475 3476 // At the beginning, all fields are uninitialized. 3477 for (auto *I : RD->decls()) { 3478 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3479 UninitializedFields.insert(FD); 3480 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3481 UninitializedFields.insert(IFD->getAnonField()); 3482 } 3483 } 3484 3485 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3486 for (auto I : RD->bases()) 3487 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3488 3489 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3490 return; 3491 3492 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3493 UninitializedFields, 3494 UninitializedBaseClasses); 3495 3496 for (const auto *FieldInit : Constructor->inits()) { 3497 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3498 break; 3499 3500 Expr *InitExpr = FieldInit->getInit(); 3501 if (!InitExpr) 3502 continue; 3503 3504 if (CXXDefaultInitExpr *Default = 3505 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3506 InitExpr = Default->getExpr(); 3507 if (!InitExpr) 3508 continue; 3509 // In class initializers will point to the constructor. 3510 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3511 FieldInit->getAnyMember(), 3512 FieldInit->getBaseClass()); 3513 } else { 3514 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3515 FieldInit->getAnyMember(), 3516 FieldInit->getBaseClass()); 3517 } 3518 } 3519 } 3520 } // namespace 3521 3522 /// \brief Enter a new C++ default initializer scope. After calling this, the 3523 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3524 /// parsing or instantiating the initializer failed. 3525 void Sema::ActOnStartCXXInClassMemberInitializer() { 3526 // Create a synthetic function scope to represent the call to the constructor 3527 // that notionally surrounds a use of this initializer. 3528 PushFunctionScope(); 3529 } 3530 3531 /// \brief This is invoked after parsing an in-class initializer for a 3532 /// non-static C++ class member, and after instantiating an in-class initializer 3533 /// in a class template. Such actions are deferred until the class is complete. 3534 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3535 SourceLocation InitLoc, 3536 Expr *InitExpr) { 3537 // Pop the notional constructor scope we created earlier. 3538 PopFunctionScopeInfo(nullptr, D); 3539 3540 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3541 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3542 "must set init style when field is created"); 3543 3544 if (!InitExpr) { 3545 D->setInvalidDecl(); 3546 if (FD) 3547 FD->removeInClassInitializer(); 3548 return; 3549 } 3550 3551 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3552 FD->setInvalidDecl(); 3553 FD->removeInClassInitializer(); 3554 return; 3555 } 3556 3557 ExprResult Init = InitExpr; 3558 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3559 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3560 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 3561 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 3562 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3563 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3564 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3565 if (Init.isInvalid()) { 3566 FD->setInvalidDecl(); 3567 return; 3568 } 3569 } 3570 3571 // C++11 [class.base.init]p7: 3572 // The initialization of each base and member constitutes a 3573 // full-expression. 3574 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3575 if (Init.isInvalid()) { 3576 FD->setInvalidDecl(); 3577 return; 3578 } 3579 3580 InitExpr = Init.get(); 3581 3582 FD->setInClassInitializer(InitExpr); 3583 } 3584 3585 /// \brief Find the direct and/or virtual base specifiers that 3586 /// correspond to the given base type, for use in base initialization 3587 /// within a constructor. 3588 static bool FindBaseInitializer(Sema &SemaRef, 3589 CXXRecordDecl *ClassDecl, 3590 QualType BaseType, 3591 const CXXBaseSpecifier *&DirectBaseSpec, 3592 const CXXBaseSpecifier *&VirtualBaseSpec) { 3593 // First, check for a direct base class. 3594 DirectBaseSpec = nullptr; 3595 for (const auto &Base : ClassDecl->bases()) { 3596 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3597 // We found a direct base of this type. That's what we're 3598 // initializing. 3599 DirectBaseSpec = &Base; 3600 break; 3601 } 3602 } 3603 3604 // Check for a virtual base class. 3605 // FIXME: We might be able to short-circuit this if we know in advance that 3606 // there are no virtual bases. 3607 VirtualBaseSpec = nullptr; 3608 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3609 // We haven't found a base yet; search the class hierarchy for a 3610 // virtual base class. 3611 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3612 /*DetectVirtual=*/false); 3613 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3614 SemaRef.Context.getTypeDeclType(ClassDecl), 3615 BaseType, Paths)) { 3616 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3617 Path != Paths.end(); ++Path) { 3618 if (Path->back().Base->isVirtual()) { 3619 VirtualBaseSpec = Path->back().Base; 3620 break; 3621 } 3622 } 3623 } 3624 } 3625 3626 return DirectBaseSpec || VirtualBaseSpec; 3627 } 3628 3629 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3630 MemInitResult 3631 Sema::ActOnMemInitializer(Decl *ConstructorD, 3632 Scope *S, 3633 CXXScopeSpec &SS, 3634 IdentifierInfo *MemberOrBase, 3635 ParsedType TemplateTypeTy, 3636 const DeclSpec &DS, 3637 SourceLocation IdLoc, 3638 Expr *InitList, 3639 SourceLocation EllipsisLoc) { 3640 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3641 DS, IdLoc, InitList, 3642 EllipsisLoc); 3643 } 3644 3645 /// \brief Handle a C++ member initializer using parentheses syntax. 3646 MemInitResult 3647 Sema::ActOnMemInitializer(Decl *ConstructorD, 3648 Scope *S, 3649 CXXScopeSpec &SS, 3650 IdentifierInfo *MemberOrBase, 3651 ParsedType TemplateTypeTy, 3652 const DeclSpec &DS, 3653 SourceLocation IdLoc, 3654 SourceLocation LParenLoc, 3655 ArrayRef<Expr *> Args, 3656 SourceLocation RParenLoc, 3657 SourceLocation EllipsisLoc) { 3658 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3659 Args, RParenLoc); 3660 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3661 DS, IdLoc, List, EllipsisLoc); 3662 } 3663 3664 namespace { 3665 3666 // Callback to only accept typo corrections that can be a valid C++ member 3667 // intializer: either a non-static field member or a base class. 3668 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3669 public: 3670 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3671 : ClassDecl(ClassDecl) {} 3672 3673 bool ValidateCandidate(const TypoCorrection &candidate) override { 3674 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3675 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3676 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3677 return isa<TypeDecl>(ND); 3678 } 3679 return false; 3680 } 3681 3682 private: 3683 CXXRecordDecl *ClassDecl; 3684 }; 3685 3686 } 3687 3688 /// \brief Handle a C++ member initializer. 3689 MemInitResult 3690 Sema::BuildMemInitializer(Decl *ConstructorD, 3691 Scope *S, 3692 CXXScopeSpec &SS, 3693 IdentifierInfo *MemberOrBase, 3694 ParsedType TemplateTypeTy, 3695 const DeclSpec &DS, 3696 SourceLocation IdLoc, 3697 Expr *Init, 3698 SourceLocation EllipsisLoc) { 3699 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3700 if (!Res.isUsable()) 3701 return true; 3702 Init = Res.get(); 3703 3704 if (!ConstructorD) 3705 return true; 3706 3707 AdjustDeclIfTemplate(ConstructorD); 3708 3709 CXXConstructorDecl *Constructor 3710 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3711 if (!Constructor) { 3712 // The user wrote a constructor initializer on a function that is 3713 // not a C++ constructor. Ignore the error for now, because we may 3714 // have more member initializers coming; we'll diagnose it just 3715 // once in ActOnMemInitializers. 3716 return true; 3717 } 3718 3719 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3720 3721 // C++ [class.base.init]p2: 3722 // Names in a mem-initializer-id are looked up in the scope of the 3723 // constructor's class and, if not found in that scope, are looked 3724 // up in the scope containing the constructor's definition. 3725 // [Note: if the constructor's class contains a member with the 3726 // same name as a direct or virtual base class of the class, a 3727 // mem-initializer-id naming the member or base class and composed 3728 // of a single identifier refers to the class member. A 3729 // mem-initializer-id for the hidden base class may be specified 3730 // using a qualified name. ] 3731 if (!SS.getScopeRep() && !TemplateTypeTy) { 3732 // Look for a member, first. 3733 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3734 if (!Result.empty()) { 3735 ValueDecl *Member; 3736 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3737 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3738 if (EllipsisLoc.isValid()) 3739 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3740 << MemberOrBase 3741 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3742 3743 return BuildMemberInitializer(Member, Init, IdLoc); 3744 } 3745 } 3746 } 3747 // It didn't name a member, so see if it names a class. 3748 QualType BaseType; 3749 TypeSourceInfo *TInfo = nullptr; 3750 3751 if (TemplateTypeTy) { 3752 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3753 } else if (DS.getTypeSpecType() == TST_decltype) { 3754 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3755 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3756 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3757 return true; 3758 } else { 3759 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3760 LookupParsedName(R, S, &SS); 3761 3762 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3763 if (!TyD) { 3764 if (R.isAmbiguous()) return true; 3765 3766 // We don't want access-control diagnostics here. 3767 R.suppressDiagnostics(); 3768 3769 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3770 bool NotUnknownSpecialization = false; 3771 DeclContext *DC = computeDeclContext(SS, false); 3772 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3773 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3774 3775 if (!NotUnknownSpecialization) { 3776 // When the scope specifier can refer to a member of an unknown 3777 // specialization, we take it as a type name. 3778 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3779 SS.getWithLocInContext(Context), 3780 *MemberOrBase, IdLoc); 3781 if (BaseType.isNull()) 3782 return true; 3783 3784 TInfo = Context.CreateTypeSourceInfo(BaseType); 3785 DependentNameTypeLoc TL = 3786 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3787 if (!TL.isNull()) { 3788 TL.setNameLoc(IdLoc); 3789 TL.setElaboratedKeywordLoc(SourceLocation()); 3790 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3791 } 3792 3793 R.clear(); 3794 R.setLookupName(MemberOrBase); 3795 } 3796 } 3797 3798 // If no results were found, try to correct typos. 3799 TypoCorrection Corr; 3800 if (R.empty() && BaseType.isNull() && 3801 (Corr = CorrectTypo( 3802 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3803 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3804 CTK_ErrorRecovery, ClassDecl))) { 3805 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3806 // We have found a non-static data member with a similar 3807 // name to what was typed; complain and initialize that 3808 // member. 3809 diagnoseTypo(Corr, 3810 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3811 << MemberOrBase << true); 3812 return BuildMemberInitializer(Member, Init, IdLoc); 3813 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3814 const CXXBaseSpecifier *DirectBaseSpec; 3815 const CXXBaseSpecifier *VirtualBaseSpec; 3816 if (FindBaseInitializer(*this, ClassDecl, 3817 Context.getTypeDeclType(Type), 3818 DirectBaseSpec, VirtualBaseSpec)) { 3819 // We have found a direct or virtual base class with a 3820 // similar name to what was typed; complain and initialize 3821 // that base class. 3822 diagnoseTypo(Corr, 3823 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3824 << MemberOrBase << false, 3825 PDiag() /*Suppress note, we provide our own.*/); 3826 3827 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3828 : VirtualBaseSpec; 3829 Diag(BaseSpec->getLocStart(), 3830 diag::note_base_class_specified_here) 3831 << BaseSpec->getType() 3832 << BaseSpec->getSourceRange(); 3833 3834 TyD = Type; 3835 } 3836 } 3837 } 3838 3839 if (!TyD && BaseType.isNull()) { 3840 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3841 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3842 return true; 3843 } 3844 } 3845 3846 if (BaseType.isNull()) { 3847 BaseType = Context.getTypeDeclType(TyD); 3848 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3849 if (SS.isSet()) { 3850 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3851 BaseType); 3852 TInfo = Context.CreateTypeSourceInfo(BaseType); 3853 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3854 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3855 TL.setElaboratedKeywordLoc(SourceLocation()); 3856 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3857 } 3858 } 3859 } 3860 3861 if (!TInfo) 3862 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3863 3864 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3865 } 3866 3867 /// Checks a member initializer expression for cases where reference (or 3868 /// pointer) members are bound to by-value parameters (or their addresses). 3869 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3870 Expr *Init, 3871 SourceLocation IdLoc) { 3872 QualType MemberTy = Member->getType(); 3873 3874 // We only handle pointers and references currently. 3875 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3876 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3877 return; 3878 3879 const bool IsPointer = MemberTy->isPointerType(); 3880 if (IsPointer) { 3881 if (const UnaryOperator *Op 3882 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3883 // The only case we're worried about with pointers requires taking the 3884 // address. 3885 if (Op->getOpcode() != UO_AddrOf) 3886 return; 3887 3888 Init = Op->getSubExpr(); 3889 } else { 3890 // We only handle address-of expression initializers for pointers. 3891 return; 3892 } 3893 } 3894 3895 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3896 // We only warn when referring to a non-reference parameter declaration. 3897 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3898 if (!Parameter || Parameter->getType()->isReferenceType()) 3899 return; 3900 3901 S.Diag(Init->getExprLoc(), 3902 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3903 : diag::warn_bind_ref_member_to_parameter) 3904 << Member << Parameter << Init->getSourceRange(); 3905 } else { 3906 // Other initializers are fine. 3907 return; 3908 } 3909 3910 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3911 << (unsigned)IsPointer; 3912 } 3913 3914 MemInitResult 3915 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3916 SourceLocation IdLoc) { 3917 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3918 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3919 assert((DirectMember || IndirectMember) && 3920 "Member must be a FieldDecl or IndirectFieldDecl"); 3921 3922 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3923 return true; 3924 3925 if (Member->isInvalidDecl()) 3926 return true; 3927 3928 MultiExprArg Args; 3929 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3930 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3931 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3932 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3933 } else { 3934 // Template instantiation doesn't reconstruct ParenListExprs for us. 3935 Args = Init; 3936 } 3937 3938 SourceRange InitRange = Init->getSourceRange(); 3939 3940 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3941 // Can't check initialization for a member of dependent type or when 3942 // any of the arguments are type-dependent expressions. 3943 DiscardCleanupsInEvaluationContext(); 3944 } else { 3945 bool InitList = false; 3946 if (isa<InitListExpr>(Init)) { 3947 InitList = true; 3948 Args = Init; 3949 } 3950 3951 // Initialize the member. 3952 InitializedEntity MemberEntity = 3953 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3954 : InitializedEntity::InitializeMember(IndirectMember, 3955 nullptr); 3956 InitializationKind Kind = 3957 InitList ? InitializationKind::CreateDirectList(IdLoc) 3958 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3959 InitRange.getEnd()); 3960 3961 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3962 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3963 nullptr); 3964 if (MemberInit.isInvalid()) 3965 return true; 3966 3967 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3968 3969 // C++11 [class.base.init]p7: 3970 // The initialization of each base and member constitutes a 3971 // full-expression. 3972 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3973 if (MemberInit.isInvalid()) 3974 return true; 3975 3976 Init = MemberInit.get(); 3977 } 3978 3979 if (DirectMember) { 3980 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3981 InitRange.getBegin(), Init, 3982 InitRange.getEnd()); 3983 } else { 3984 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3985 InitRange.getBegin(), Init, 3986 InitRange.getEnd()); 3987 } 3988 } 3989 3990 MemInitResult 3991 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3992 CXXRecordDecl *ClassDecl) { 3993 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3994 if (!LangOpts.CPlusPlus11) 3995 return Diag(NameLoc, diag::err_delegating_ctor) 3996 << TInfo->getTypeLoc().getLocalSourceRange(); 3997 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3998 3999 bool InitList = true; 4000 MultiExprArg Args = Init; 4001 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4002 InitList = false; 4003 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4004 } 4005 4006 SourceRange InitRange = Init->getSourceRange(); 4007 // Initialize the object. 4008 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4009 QualType(ClassDecl->getTypeForDecl(), 0)); 4010 InitializationKind Kind = 4011 InitList ? InitializationKind::CreateDirectList(NameLoc) 4012 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4013 InitRange.getEnd()); 4014 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4015 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4016 Args, nullptr); 4017 if (DelegationInit.isInvalid()) 4018 return true; 4019 4020 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4021 "Delegating constructor with no target?"); 4022 4023 // C++11 [class.base.init]p7: 4024 // The initialization of each base and member constitutes a 4025 // full-expression. 4026 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4027 InitRange.getBegin()); 4028 if (DelegationInit.isInvalid()) 4029 return true; 4030 4031 // If we are in a dependent context, template instantiation will 4032 // perform this type-checking again. Just save the arguments that we 4033 // received in a ParenListExpr. 4034 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4035 // of the information that we have about the base 4036 // initializer. However, deconstructing the ASTs is a dicey process, 4037 // and this approach is far more likely to get the corner cases right. 4038 if (CurContext->isDependentContext()) 4039 DelegationInit = Init; 4040 4041 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4042 DelegationInit.getAs<Expr>(), 4043 InitRange.getEnd()); 4044 } 4045 4046 MemInitResult 4047 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4048 Expr *Init, CXXRecordDecl *ClassDecl, 4049 SourceLocation EllipsisLoc) { 4050 SourceLocation BaseLoc 4051 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4052 4053 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4054 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4055 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4056 4057 // C++ [class.base.init]p2: 4058 // [...] Unless the mem-initializer-id names a nonstatic data 4059 // member of the constructor's class or a direct or virtual base 4060 // of that class, the mem-initializer is ill-formed. A 4061 // mem-initializer-list can initialize a base class using any 4062 // name that denotes that base class type. 4063 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4064 4065 SourceRange InitRange = Init->getSourceRange(); 4066 if (EllipsisLoc.isValid()) { 4067 // This is a pack expansion. 4068 if (!BaseType->containsUnexpandedParameterPack()) { 4069 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4070 << SourceRange(BaseLoc, InitRange.getEnd()); 4071 4072 EllipsisLoc = SourceLocation(); 4073 } 4074 } else { 4075 // Check for any unexpanded parameter packs. 4076 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4077 return true; 4078 4079 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4080 return true; 4081 } 4082 4083 // Check for direct and virtual base classes. 4084 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4085 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4086 if (!Dependent) { 4087 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4088 BaseType)) 4089 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4090 4091 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4092 VirtualBaseSpec); 4093 4094 // C++ [base.class.init]p2: 4095 // Unless the mem-initializer-id names a nonstatic data member of the 4096 // constructor's class or a direct or virtual base of that class, the 4097 // mem-initializer is ill-formed. 4098 if (!DirectBaseSpec && !VirtualBaseSpec) { 4099 // If the class has any dependent bases, then it's possible that 4100 // one of those types will resolve to the same type as 4101 // BaseType. Therefore, just treat this as a dependent base 4102 // class initialization. FIXME: Should we try to check the 4103 // initialization anyway? It seems odd. 4104 if (ClassDecl->hasAnyDependentBases()) 4105 Dependent = true; 4106 else 4107 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4108 << BaseType << Context.getTypeDeclType(ClassDecl) 4109 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4110 } 4111 } 4112 4113 if (Dependent) { 4114 DiscardCleanupsInEvaluationContext(); 4115 4116 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4117 /*IsVirtual=*/false, 4118 InitRange.getBegin(), Init, 4119 InitRange.getEnd(), EllipsisLoc); 4120 } 4121 4122 // C++ [base.class.init]p2: 4123 // If a mem-initializer-id is ambiguous because it designates both 4124 // a direct non-virtual base class and an inherited virtual base 4125 // class, the mem-initializer is ill-formed. 4126 if (DirectBaseSpec && VirtualBaseSpec) 4127 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4128 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4129 4130 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4131 if (!BaseSpec) 4132 BaseSpec = VirtualBaseSpec; 4133 4134 // Initialize the base. 4135 bool InitList = true; 4136 MultiExprArg Args = Init; 4137 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4138 InitList = false; 4139 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4140 } 4141 4142 InitializedEntity BaseEntity = 4143 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4144 InitializationKind Kind = 4145 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4146 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4147 InitRange.getEnd()); 4148 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4149 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4150 if (BaseInit.isInvalid()) 4151 return true; 4152 4153 // C++11 [class.base.init]p7: 4154 // The initialization of each base and member constitutes a 4155 // full-expression. 4156 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4157 if (BaseInit.isInvalid()) 4158 return true; 4159 4160 // If we are in a dependent context, template instantiation will 4161 // perform this type-checking again. Just save the arguments that we 4162 // received in a ParenListExpr. 4163 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4164 // of the information that we have about the base 4165 // initializer. However, deconstructing the ASTs is a dicey process, 4166 // and this approach is far more likely to get the corner cases right. 4167 if (CurContext->isDependentContext()) 4168 BaseInit = Init; 4169 4170 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4171 BaseSpec->isVirtual(), 4172 InitRange.getBegin(), 4173 BaseInit.getAs<Expr>(), 4174 InitRange.getEnd(), EllipsisLoc); 4175 } 4176 4177 // Create a static_cast\<T&&>(expr). 4178 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4179 if (T.isNull()) T = E->getType(); 4180 QualType TargetType = SemaRef.BuildReferenceType( 4181 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4182 SourceLocation ExprLoc = E->getLocStart(); 4183 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4184 TargetType, ExprLoc); 4185 4186 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4187 SourceRange(ExprLoc, ExprLoc), 4188 E->getSourceRange()).get(); 4189 } 4190 4191 /// ImplicitInitializerKind - How an implicit base or member initializer should 4192 /// initialize its base or member. 4193 enum ImplicitInitializerKind { 4194 IIK_Default, 4195 IIK_Copy, 4196 IIK_Move, 4197 IIK_Inherit 4198 }; 4199 4200 static bool 4201 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4202 ImplicitInitializerKind ImplicitInitKind, 4203 CXXBaseSpecifier *BaseSpec, 4204 bool IsInheritedVirtualBase, 4205 CXXCtorInitializer *&CXXBaseInit) { 4206 InitializedEntity InitEntity 4207 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4208 IsInheritedVirtualBase); 4209 4210 ExprResult BaseInit; 4211 4212 switch (ImplicitInitKind) { 4213 case IIK_Inherit: 4214 case IIK_Default: { 4215 InitializationKind InitKind 4216 = InitializationKind::CreateDefault(Constructor->getLocation()); 4217 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4218 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4219 break; 4220 } 4221 4222 case IIK_Move: 4223 case IIK_Copy: { 4224 bool Moving = ImplicitInitKind == IIK_Move; 4225 ParmVarDecl *Param = Constructor->getParamDecl(0); 4226 QualType ParamType = Param->getType().getNonReferenceType(); 4227 4228 Expr *CopyCtorArg = 4229 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4230 SourceLocation(), Param, false, 4231 Constructor->getLocation(), ParamType, 4232 VK_LValue, nullptr); 4233 4234 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4235 4236 // Cast to the base class to avoid ambiguities. 4237 QualType ArgTy = 4238 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4239 ParamType.getQualifiers()); 4240 4241 if (Moving) { 4242 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4243 } 4244 4245 CXXCastPath BasePath; 4246 BasePath.push_back(BaseSpec); 4247 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4248 CK_UncheckedDerivedToBase, 4249 Moving ? VK_XValue : VK_LValue, 4250 &BasePath).get(); 4251 4252 InitializationKind InitKind 4253 = InitializationKind::CreateDirect(Constructor->getLocation(), 4254 SourceLocation(), SourceLocation()); 4255 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4256 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4257 break; 4258 } 4259 } 4260 4261 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4262 if (BaseInit.isInvalid()) 4263 return true; 4264 4265 CXXBaseInit = 4266 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4267 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4268 SourceLocation()), 4269 BaseSpec->isVirtual(), 4270 SourceLocation(), 4271 BaseInit.getAs<Expr>(), 4272 SourceLocation(), 4273 SourceLocation()); 4274 4275 return false; 4276 } 4277 4278 static bool RefersToRValueRef(Expr *MemRef) { 4279 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4280 return Referenced->getType()->isRValueReferenceType(); 4281 } 4282 4283 static bool 4284 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4285 ImplicitInitializerKind ImplicitInitKind, 4286 FieldDecl *Field, IndirectFieldDecl *Indirect, 4287 CXXCtorInitializer *&CXXMemberInit) { 4288 if (Field->isInvalidDecl()) 4289 return true; 4290 4291 SourceLocation Loc = Constructor->getLocation(); 4292 4293 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4294 bool Moving = ImplicitInitKind == IIK_Move; 4295 ParmVarDecl *Param = Constructor->getParamDecl(0); 4296 QualType ParamType = Param->getType().getNonReferenceType(); 4297 4298 // Suppress copying zero-width bitfields. 4299 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4300 return false; 4301 4302 Expr *MemberExprBase = 4303 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4304 SourceLocation(), Param, false, 4305 Loc, ParamType, VK_LValue, nullptr); 4306 4307 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4308 4309 if (Moving) { 4310 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4311 } 4312 4313 // Build a reference to this field within the parameter. 4314 CXXScopeSpec SS; 4315 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4316 Sema::LookupMemberName); 4317 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4318 : cast<ValueDecl>(Field), AS_public); 4319 MemberLookup.resolveKind(); 4320 ExprResult CtorArg 4321 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4322 ParamType, Loc, 4323 /*IsArrow=*/false, 4324 SS, 4325 /*TemplateKWLoc=*/SourceLocation(), 4326 /*FirstQualifierInScope=*/nullptr, 4327 MemberLookup, 4328 /*TemplateArgs=*/nullptr, 4329 /*S*/nullptr); 4330 if (CtorArg.isInvalid()) 4331 return true; 4332 4333 // C++11 [class.copy]p15: 4334 // - if a member m has rvalue reference type T&&, it is direct-initialized 4335 // with static_cast<T&&>(x.m); 4336 if (RefersToRValueRef(CtorArg.get())) { 4337 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4338 } 4339 4340 InitializedEntity Entity = 4341 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4342 /*Implicit*/ true) 4343 : InitializedEntity::InitializeMember(Field, nullptr, 4344 /*Implicit*/ true); 4345 4346 // Direct-initialize to use the copy constructor. 4347 InitializationKind InitKind = 4348 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4349 4350 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4351 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4352 ExprResult MemberInit = 4353 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4354 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4355 if (MemberInit.isInvalid()) 4356 return true; 4357 4358 if (Indirect) 4359 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4360 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4361 else 4362 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4363 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4364 return false; 4365 } 4366 4367 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4368 "Unhandled implicit init kind!"); 4369 4370 QualType FieldBaseElementType = 4371 SemaRef.Context.getBaseElementType(Field->getType()); 4372 4373 if (FieldBaseElementType->isRecordType()) { 4374 InitializedEntity InitEntity = 4375 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4376 /*Implicit*/ true) 4377 : InitializedEntity::InitializeMember(Field, nullptr, 4378 /*Implicit*/ true); 4379 InitializationKind InitKind = 4380 InitializationKind::CreateDefault(Loc); 4381 4382 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4383 ExprResult MemberInit = 4384 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4385 4386 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4387 if (MemberInit.isInvalid()) 4388 return true; 4389 4390 if (Indirect) 4391 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4392 Indirect, Loc, 4393 Loc, 4394 MemberInit.get(), 4395 Loc); 4396 else 4397 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4398 Field, Loc, Loc, 4399 MemberInit.get(), 4400 Loc); 4401 return false; 4402 } 4403 4404 if (!Field->getParent()->isUnion()) { 4405 if (FieldBaseElementType->isReferenceType()) { 4406 SemaRef.Diag(Constructor->getLocation(), 4407 diag::err_uninitialized_member_in_ctor) 4408 << (int)Constructor->isImplicit() 4409 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4410 << 0 << Field->getDeclName(); 4411 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4412 return true; 4413 } 4414 4415 if (FieldBaseElementType.isConstQualified()) { 4416 SemaRef.Diag(Constructor->getLocation(), 4417 diag::err_uninitialized_member_in_ctor) 4418 << (int)Constructor->isImplicit() 4419 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4420 << 1 << Field->getDeclName(); 4421 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4422 return true; 4423 } 4424 } 4425 4426 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4427 // ARC and Weak: 4428 // Default-initialize Objective-C pointers to NULL. 4429 CXXMemberInit 4430 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4431 Loc, Loc, 4432 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4433 Loc); 4434 return false; 4435 } 4436 4437 // Nothing to initialize. 4438 CXXMemberInit = nullptr; 4439 return false; 4440 } 4441 4442 namespace { 4443 struct BaseAndFieldInfo { 4444 Sema &S; 4445 CXXConstructorDecl *Ctor; 4446 bool AnyErrorsInInits; 4447 ImplicitInitializerKind IIK; 4448 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4449 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4450 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4451 4452 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4453 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4454 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4455 if (Ctor->getInheritedConstructor()) 4456 IIK = IIK_Inherit; 4457 else if (Generated && Ctor->isCopyConstructor()) 4458 IIK = IIK_Copy; 4459 else if (Generated && Ctor->isMoveConstructor()) 4460 IIK = IIK_Move; 4461 else 4462 IIK = IIK_Default; 4463 } 4464 4465 bool isImplicitCopyOrMove() const { 4466 switch (IIK) { 4467 case IIK_Copy: 4468 case IIK_Move: 4469 return true; 4470 4471 case IIK_Default: 4472 case IIK_Inherit: 4473 return false; 4474 } 4475 4476 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4477 } 4478 4479 bool addFieldInitializer(CXXCtorInitializer *Init) { 4480 AllToInit.push_back(Init); 4481 4482 // Check whether this initializer makes the field "used". 4483 if (Init->getInit()->HasSideEffects(S.Context)) 4484 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4485 4486 return false; 4487 } 4488 4489 bool isInactiveUnionMember(FieldDecl *Field) { 4490 RecordDecl *Record = Field->getParent(); 4491 if (!Record->isUnion()) 4492 return false; 4493 4494 if (FieldDecl *Active = 4495 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4496 return Active != Field->getCanonicalDecl(); 4497 4498 // In an implicit copy or move constructor, ignore any in-class initializer. 4499 if (isImplicitCopyOrMove()) 4500 return true; 4501 4502 // If there's no explicit initialization, the field is active only if it 4503 // has an in-class initializer... 4504 if (Field->hasInClassInitializer()) 4505 return false; 4506 // ... or it's an anonymous struct or union whose class has an in-class 4507 // initializer. 4508 if (!Field->isAnonymousStructOrUnion()) 4509 return true; 4510 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4511 return !FieldRD->hasInClassInitializer(); 4512 } 4513 4514 /// \brief Determine whether the given field is, or is within, a union member 4515 /// that is inactive (because there was an initializer given for a different 4516 /// member of the union, or because the union was not initialized at all). 4517 bool isWithinInactiveUnionMember(FieldDecl *Field, 4518 IndirectFieldDecl *Indirect) { 4519 if (!Indirect) 4520 return isInactiveUnionMember(Field); 4521 4522 for (auto *C : Indirect->chain()) { 4523 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4524 if (Field && isInactiveUnionMember(Field)) 4525 return true; 4526 } 4527 return false; 4528 } 4529 }; 4530 } 4531 4532 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4533 /// array type. 4534 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4535 if (T->isIncompleteArrayType()) 4536 return true; 4537 4538 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4539 if (!ArrayT->getSize()) 4540 return true; 4541 4542 T = ArrayT->getElementType(); 4543 } 4544 4545 return false; 4546 } 4547 4548 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4549 FieldDecl *Field, 4550 IndirectFieldDecl *Indirect = nullptr) { 4551 if (Field->isInvalidDecl()) 4552 return false; 4553 4554 // Overwhelmingly common case: we have a direct initializer for this field. 4555 if (CXXCtorInitializer *Init = 4556 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4557 return Info.addFieldInitializer(Init); 4558 4559 // C++11 [class.base.init]p8: 4560 // if the entity is a non-static data member that has a 4561 // brace-or-equal-initializer and either 4562 // -- the constructor's class is a union and no other variant member of that 4563 // union is designated by a mem-initializer-id or 4564 // -- the constructor's class is not a union, and, if the entity is a member 4565 // of an anonymous union, no other member of that union is designated by 4566 // a mem-initializer-id, 4567 // the entity is initialized as specified in [dcl.init]. 4568 // 4569 // We also apply the same rules to handle anonymous structs within anonymous 4570 // unions. 4571 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4572 return false; 4573 4574 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4575 ExprResult DIE = 4576 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4577 if (DIE.isInvalid()) 4578 return true; 4579 CXXCtorInitializer *Init; 4580 if (Indirect) 4581 Init = new (SemaRef.Context) 4582 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4583 SourceLocation(), DIE.get(), SourceLocation()); 4584 else 4585 Init = new (SemaRef.Context) 4586 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4587 SourceLocation(), DIE.get(), SourceLocation()); 4588 return Info.addFieldInitializer(Init); 4589 } 4590 4591 // Don't initialize incomplete or zero-length arrays. 4592 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4593 return false; 4594 4595 // Don't try to build an implicit initializer if there were semantic 4596 // errors in any of the initializers (and therefore we might be 4597 // missing some that the user actually wrote). 4598 if (Info.AnyErrorsInInits) 4599 return false; 4600 4601 CXXCtorInitializer *Init = nullptr; 4602 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4603 Indirect, Init)) 4604 return true; 4605 4606 if (!Init) 4607 return false; 4608 4609 return Info.addFieldInitializer(Init); 4610 } 4611 4612 bool 4613 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4614 CXXCtorInitializer *Initializer) { 4615 assert(Initializer->isDelegatingInitializer()); 4616 Constructor->setNumCtorInitializers(1); 4617 CXXCtorInitializer **initializer = 4618 new (Context) CXXCtorInitializer*[1]; 4619 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4620 Constructor->setCtorInitializers(initializer); 4621 4622 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4623 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4624 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4625 } 4626 4627 DelegatingCtorDecls.push_back(Constructor); 4628 4629 DiagnoseUninitializedFields(*this, Constructor); 4630 4631 return false; 4632 } 4633 4634 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4635 ArrayRef<CXXCtorInitializer *> Initializers) { 4636 if (Constructor->isDependentContext()) { 4637 // Just store the initializers as written, they will be checked during 4638 // instantiation. 4639 if (!Initializers.empty()) { 4640 Constructor->setNumCtorInitializers(Initializers.size()); 4641 CXXCtorInitializer **baseOrMemberInitializers = 4642 new (Context) CXXCtorInitializer*[Initializers.size()]; 4643 memcpy(baseOrMemberInitializers, Initializers.data(), 4644 Initializers.size() * sizeof(CXXCtorInitializer*)); 4645 Constructor->setCtorInitializers(baseOrMemberInitializers); 4646 } 4647 4648 // Let template instantiation know whether we had errors. 4649 if (AnyErrors) 4650 Constructor->setInvalidDecl(); 4651 4652 return false; 4653 } 4654 4655 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4656 4657 // We need to build the initializer AST according to order of construction 4658 // and not what user specified in the Initializers list. 4659 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4660 if (!ClassDecl) 4661 return true; 4662 4663 bool HadError = false; 4664 4665 for (unsigned i = 0; i < Initializers.size(); i++) { 4666 CXXCtorInitializer *Member = Initializers[i]; 4667 4668 if (Member->isBaseInitializer()) 4669 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4670 else { 4671 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4672 4673 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4674 for (auto *C : F->chain()) { 4675 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4676 if (FD && FD->getParent()->isUnion()) 4677 Info.ActiveUnionMember.insert(std::make_pair( 4678 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4679 } 4680 } else if (FieldDecl *FD = Member->getMember()) { 4681 if (FD->getParent()->isUnion()) 4682 Info.ActiveUnionMember.insert(std::make_pair( 4683 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4684 } 4685 } 4686 } 4687 4688 // Keep track of the direct virtual bases. 4689 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4690 for (auto &I : ClassDecl->bases()) { 4691 if (I.isVirtual()) 4692 DirectVBases.insert(&I); 4693 } 4694 4695 // Push virtual bases before others. 4696 for (auto &VBase : ClassDecl->vbases()) { 4697 if (CXXCtorInitializer *Value 4698 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4699 // [class.base.init]p7, per DR257: 4700 // A mem-initializer where the mem-initializer-id names a virtual base 4701 // class is ignored during execution of a constructor of any class that 4702 // is not the most derived class. 4703 if (ClassDecl->isAbstract()) { 4704 // FIXME: Provide a fixit to remove the base specifier. This requires 4705 // tracking the location of the associated comma for a base specifier. 4706 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4707 << VBase.getType() << ClassDecl; 4708 DiagnoseAbstractType(ClassDecl); 4709 } 4710 4711 Info.AllToInit.push_back(Value); 4712 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4713 // [class.base.init]p8, per DR257: 4714 // If a given [...] base class is not named by a mem-initializer-id 4715 // [...] and the entity is not a virtual base class of an abstract 4716 // class, then [...] the entity is default-initialized. 4717 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4718 CXXCtorInitializer *CXXBaseInit; 4719 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4720 &VBase, IsInheritedVirtualBase, 4721 CXXBaseInit)) { 4722 HadError = true; 4723 continue; 4724 } 4725 4726 Info.AllToInit.push_back(CXXBaseInit); 4727 } 4728 } 4729 4730 // Non-virtual bases. 4731 for (auto &Base : ClassDecl->bases()) { 4732 // Virtuals are in the virtual base list and already constructed. 4733 if (Base.isVirtual()) 4734 continue; 4735 4736 if (CXXCtorInitializer *Value 4737 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4738 Info.AllToInit.push_back(Value); 4739 } else if (!AnyErrors) { 4740 CXXCtorInitializer *CXXBaseInit; 4741 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4742 &Base, /*IsInheritedVirtualBase=*/false, 4743 CXXBaseInit)) { 4744 HadError = true; 4745 continue; 4746 } 4747 4748 Info.AllToInit.push_back(CXXBaseInit); 4749 } 4750 } 4751 4752 // Fields. 4753 for (auto *Mem : ClassDecl->decls()) { 4754 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4755 // C++ [class.bit]p2: 4756 // A declaration for a bit-field that omits the identifier declares an 4757 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4758 // initialized. 4759 if (F->isUnnamedBitfield()) 4760 continue; 4761 4762 // If we're not generating the implicit copy/move constructor, then we'll 4763 // handle anonymous struct/union fields based on their individual 4764 // indirect fields. 4765 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4766 continue; 4767 4768 if (CollectFieldInitializer(*this, Info, F)) 4769 HadError = true; 4770 continue; 4771 } 4772 4773 // Beyond this point, we only consider default initialization. 4774 if (Info.isImplicitCopyOrMove()) 4775 continue; 4776 4777 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4778 if (F->getType()->isIncompleteArrayType()) { 4779 assert(ClassDecl->hasFlexibleArrayMember() && 4780 "Incomplete array type is not valid"); 4781 continue; 4782 } 4783 4784 // Initialize each field of an anonymous struct individually. 4785 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4786 HadError = true; 4787 4788 continue; 4789 } 4790 } 4791 4792 unsigned NumInitializers = Info.AllToInit.size(); 4793 if (NumInitializers > 0) { 4794 Constructor->setNumCtorInitializers(NumInitializers); 4795 CXXCtorInitializer **baseOrMemberInitializers = 4796 new (Context) CXXCtorInitializer*[NumInitializers]; 4797 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4798 NumInitializers * sizeof(CXXCtorInitializer*)); 4799 Constructor->setCtorInitializers(baseOrMemberInitializers); 4800 4801 // Constructors implicitly reference the base and member 4802 // destructors. 4803 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4804 Constructor->getParent()); 4805 } 4806 4807 return HadError; 4808 } 4809 4810 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4811 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4812 const RecordDecl *RD = RT->getDecl(); 4813 if (RD->isAnonymousStructOrUnion()) { 4814 for (auto *Field : RD->fields()) 4815 PopulateKeysForFields(Field, IdealInits); 4816 return; 4817 } 4818 } 4819 IdealInits.push_back(Field->getCanonicalDecl()); 4820 } 4821 4822 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4823 return Context.getCanonicalType(BaseType).getTypePtr(); 4824 } 4825 4826 static const void *GetKeyForMember(ASTContext &Context, 4827 CXXCtorInitializer *Member) { 4828 if (!Member->isAnyMemberInitializer()) 4829 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4830 4831 return Member->getAnyMember()->getCanonicalDecl(); 4832 } 4833 4834 static void DiagnoseBaseOrMemInitializerOrder( 4835 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4836 ArrayRef<CXXCtorInitializer *> Inits) { 4837 if (Constructor->getDeclContext()->isDependentContext()) 4838 return; 4839 4840 // Don't check initializers order unless the warning is enabled at the 4841 // location of at least one initializer. 4842 bool ShouldCheckOrder = false; 4843 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4844 CXXCtorInitializer *Init = Inits[InitIndex]; 4845 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4846 Init->getSourceLocation())) { 4847 ShouldCheckOrder = true; 4848 break; 4849 } 4850 } 4851 if (!ShouldCheckOrder) 4852 return; 4853 4854 // Build the list of bases and members in the order that they'll 4855 // actually be initialized. The explicit initializers should be in 4856 // this same order but may be missing things. 4857 SmallVector<const void*, 32> IdealInitKeys; 4858 4859 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4860 4861 // 1. Virtual bases. 4862 for (const auto &VBase : ClassDecl->vbases()) 4863 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4864 4865 // 2. Non-virtual bases. 4866 for (const auto &Base : ClassDecl->bases()) { 4867 if (Base.isVirtual()) 4868 continue; 4869 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4870 } 4871 4872 // 3. Direct fields. 4873 for (auto *Field : ClassDecl->fields()) { 4874 if (Field->isUnnamedBitfield()) 4875 continue; 4876 4877 PopulateKeysForFields(Field, IdealInitKeys); 4878 } 4879 4880 unsigned NumIdealInits = IdealInitKeys.size(); 4881 unsigned IdealIndex = 0; 4882 4883 CXXCtorInitializer *PrevInit = nullptr; 4884 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4885 CXXCtorInitializer *Init = Inits[InitIndex]; 4886 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4887 4888 // Scan forward to try to find this initializer in the idealized 4889 // initializers list. 4890 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4891 if (InitKey == IdealInitKeys[IdealIndex]) 4892 break; 4893 4894 // If we didn't find this initializer, it must be because we 4895 // scanned past it on a previous iteration. That can only 4896 // happen if we're out of order; emit a warning. 4897 if (IdealIndex == NumIdealInits && PrevInit) { 4898 Sema::SemaDiagnosticBuilder D = 4899 SemaRef.Diag(PrevInit->getSourceLocation(), 4900 diag::warn_initializer_out_of_order); 4901 4902 if (PrevInit->isAnyMemberInitializer()) 4903 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4904 else 4905 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4906 4907 if (Init->isAnyMemberInitializer()) 4908 D << 0 << Init->getAnyMember()->getDeclName(); 4909 else 4910 D << 1 << Init->getTypeSourceInfo()->getType(); 4911 4912 // Move back to the initializer's location in the ideal list. 4913 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4914 if (InitKey == IdealInitKeys[IdealIndex]) 4915 break; 4916 4917 assert(IdealIndex < NumIdealInits && 4918 "initializer not found in initializer list"); 4919 } 4920 4921 PrevInit = Init; 4922 } 4923 } 4924 4925 namespace { 4926 bool CheckRedundantInit(Sema &S, 4927 CXXCtorInitializer *Init, 4928 CXXCtorInitializer *&PrevInit) { 4929 if (!PrevInit) { 4930 PrevInit = Init; 4931 return false; 4932 } 4933 4934 if (FieldDecl *Field = Init->getAnyMember()) 4935 S.Diag(Init->getSourceLocation(), 4936 diag::err_multiple_mem_initialization) 4937 << Field->getDeclName() 4938 << Init->getSourceRange(); 4939 else { 4940 const Type *BaseClass = Init->getBaseClass(); 4941 assert(BaseClass && "neither field nor base"); 4942 S.Diag(Init->getSourceLocation(), 4943 diag::err_multiple_base_initialization) 4944 << QualType(BaseClass, 0) 4945 << Init->getSourceRange(); 4946 } 4947 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4948 << 0 << PrevInit->getSourceRange(); 4949 4950 return true; 4951 } 4952 4953 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4954 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4955 4956 bool CheckRedundantUnionInit(Sema &S, 4957 CXXCtorInitializer *Init, 4958 RedundantUnionMap &Unions) { 4959 FieldDecl *Field = Init->getAnyMember(); 4960 RecordDecl *Parent = Field->getParent(); 4961 NamedDecl *Child = Field; 4962 4963 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4964 if (Parent->isUnion()) { 4965 UnionEntry &En = Unions[Parent]; 4966 if (En.first && En.first != Child) { 4967 S.Diag(Init->getSourceLocation(), 4968 diag::err_multiple_mem_union_initialization) 4969 << Field->getDeclName() 4970 << Init->getSourceRange(); 4971 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4972 << 0 << En.second->getSourceRange(); 4973 return true; 4974 } 4975 if (!En.first) { 4976 En.first = Child; 4977 En.second = Init; 4978 } 4979 if (!Parent->isAnonymousStructOrUnion()) 4980 return false; 4981 } 4982 4983 Child = Parent; 4984 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4985 } 4986 4987 return false; 4988 } 4989 } 4990 4991 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4992 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4993 SourceLocation ColonLoc, 4994 ArrayRef<CXXCtorInitializer*> MemInits, 4995 bool AnyErrors) { 4996 if (!ConstructorDecl) 4997 return; 4998 4999 AdjustDeclIfTemplate(ConstructorDecl); 5000 5001 CXXConstructorDecl *Constructor 5002 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5003 5004 if (!Constructor) { 5005 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5006 return; 5007 } 5008 5009 // Mapping for the duplicate initializers check. 5010 // For member initializers, this is keyed with a FieldDecl*. 5011 // For base initializers, this is keyed with a Type*. 5012 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5013 5014 // Mapping for the inconsistent anonymous-union initializers check. 5015 RedundantUnionMap MemberUnions; 5016 5017 bool HadError = false; 5018 for (unsigned i = 0; i < MemInits.size(); i++) { 5019 CXXCtorInitializer *Init = MemInits[i]; 5020 5021 // Set the source order index. 5022 Init->setSourceOrder(i); 5023 5024 if (Init->isAnyMemberInitializer()) { 5025 const void *Key = GetKeyForMember(Context, Init); 5026 if (CheckRedundantInit(*this, Init, Members[Key]) || 5027 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5028 HadError = true; 5029 } else if (Init->isBaseInitializer()) { 5030 const void *Key = GetKeyForMember(Context, Init); 5031 if (CheckRedundantInit(*this, Init, Members[Key])) 5032 HadError = true; 5033 } else { 5034 assert(Init->isDelegatingInitializer()); 5035 // This must be the only initializer 5036 if (MemInits.size() != 1) { 5037 Diag(Init->getSourceLocation(), 5038 diag::err_delegating_initializer_alone) 5039 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5040 // We will treat this as being the only initializer. 5041 } 5042 SetDelegatingInitializer(Constructor, MemInits[i]); 5043 // Return immediately as the initializer is set. 5044 return; 5045 } 5046 } 5047 5048 if (HadError) 5049 return; 5050 5051 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5052 5053 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5054 5055 DiagnoseUninitializedFields(*this, Constructor); 5056 } 5057 5058 void 5059 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5060 CXXRecordDecl *ClassDecl) { 5061 // Ignore dependent contexts. Also ignore unions, since their members never 5062 // have destructors implicitly called. 5063 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5064 return; 5065 5066 // FIXME: all the access-control diagnostics are positioned on the 5067 // field/base declaration. That's probably good; that said, the 5068 // user might reasonably want to know why the destructor is being 5069 // emitted, and we currently don't say. 5070 5071 // Non-static data members. 5072 for (auto *Field : ClassDecl->fields()) { 5073 if (Field->isInvalidDecl()) 5074 continue; 5075 5076 // Don't destroy incomplete or zero-length arrays. 5077 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5078 continue; 5079 5080 QualType FieldType = Context.getBaseElementType(Field->getType()); 5081 5082 const RecordType* RT = FieldType->getAs<RecordType>(); 5083 if (!RT) 5084 continue; 5085 5086 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5087 if (FieldClassDecl->isInvalidDecl()) 5088 continue; 5089 if (FieldClassDecl->hasIrrelevantDestructor()) 5090 continue; 5091 // The destructor for an implicit anonymous union member is never invoked. 5092 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5093 continue; 5094 5095 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5096 assert(Dtor && "No dtor found for FieldClassDecl!"); 5097 CheckDestructorAccess(Field->getLocation(), Dtor, 5098 PDiag(diag::err_access_dtor_field) 5099 << Field->getDeclName() 5100 << FieldType); 5101 5102 MarkFunctionReferenced(Location, Dtor); 5103 DiagnoseUseOfDecl(Dtor, Location); 5104 } 5105 5106 // We only potentially invoke the destructors of potentially constructed 5107 // subobjects. 5108 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5109 5110 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5111 5112 // Bases. 5113 for (const auto &Base : ClassDecl->bases()) { 5114 // Bases are always records in a well-formed non-dependent class. 5115 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5116 5117 // Remember direct virtual bases. 5118 if (Base.isVirtual()) { 5119 if (!VisitVirtualBases) 5120 continue; 5121 DirectVirtualBases.insert(RT); 5122 } 5123 5124 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5125 // If our base class is invalid, we probably can't get its dtor anyway. 5126 if (BaseClassDecl->isInvalidDecl()) 5127 continue; 5128 if (BaseClassDecl->hasIrrelevantDestructor()) 5129 continue; 5130 5131 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5132 assert(Dtor && "No dtor found for BaseClassDecl!"); 5133 5134 // FIXME: caret should be on the start of the class name 5135 CheckDestructorAccess(Base.getLocStart(), Dtor, 5136 PDiag(diag::err_access_dtor_base) 5137 << Base.getType() 5138 << Base.getSourceRange(), 5139 Context.getTypeDeclType(ClassDecl)); 5140 5141 MarkFunctionReferenced(Location, Dtor); 5142 DiagnoseUseOfDecl(Dtor, Location); 5143 } 5144 5145 if (!VisitVirtualBases) 5146 return; 5147 5148 // Virtual bases. 5149 for (const auto &VBase : ClassDecl->vbases()) { 5150 // Bases are always records in a well-formed non-dependent class. 5151 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5152 5153 // Ignore direct virtual bases. 5154 if (DirectVirtualBases.count(RT)) 5155 continue; 5156 5157 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5158 // If our base class is invalid, we probably can't get its dtor anyway. 5159 if (BaseClassDecl->isInvalidDecl()) 5160 continue; 5161 if (BaseClassDecl->hasIrrelevantDestructor()) 5162 continue; 5163 5164 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5165 assert(Dtor && "No dtor found for BaseClassDecl!"); 5166 if (CheckDestructorAccess( 5167 ClassDecl->getLocation(), Dtor, 5168 PDiag(diag::err_access_dtor_vbase) 5169 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5170 Context.getTypeDeclType(ClassDecl)) == 5171 AR_accessible) { 5172 CheckDerivedToBaseConversion( 5173 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5174 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5175 SourceRange(), DeclarationName(), nullptr); 5176 } 5177 5178 MarkFunctionReferenced(Location, Dtor); 5179 DiagnoseUseOfDecl(Dtor, Location); 5180 } 5181 } 5182 5183 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5184 if (!CDtorDecl) 5185 return; 5186 5187 if (CXXConstructorDecl *Constructor 5188 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5189 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5190 DiagnoseUninitializedFields(*this, Constructor); 5191 } 5192 } 5193 5194 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5195 if (!getLangOpts().CPlusPlus) 5196 return false; 5197 5198 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5199 if (!RD) 5200 return false; 5201 5202 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5203 // class template specialization here, but doing so breaks a lot of code. 5204 5205 // We can't answer whether something is abstract until it has a 5206 // definition. If it's currently being defined, we'll walk back 5207 // over all the declarations when we have a full definition. 5208 const CXXRecordDecl *Def = RD->getDefinition(); 5209 if (!Def || Def->isBeingDefined()) 5210 return false; 5211 5212 return RD->isAbstract(); 5213 } 5214 5215 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5216 TypeDiagnoser &Diagnoser) { 5217 if (!isAbstractType(Loc, T)) 5218 return false; 5219 5220 T = Context.getBaseElementType(T); 5221 Diagnoser.diagnose(*this, Loc, T); 5222 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5223 return true; 5224 } 5225 5226 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5227 // Check if we've already emitted the list of pure virtual functions 5228 // for this class. 5229 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5230 return; 5231 5232 // If the diagnostic is suppressed, don't emit the notes. We're only 5233 // going to emit them once, so try to attach them to a diagnostic we're 5234 // actually going to show. 5235 if (Diags.isLastDiagnosticIgnored()) 5236 return; 5237 5238 CXXFinalOverriderMap FinalOverriders; 5239 RD->getFinalOverriders(FinalOverriders); 5240 5241 // Keep a set of seen pure methods so we won't diagnose the same method 5242 // more than once. 5243 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5244 5245 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5246 MEnd = FinalOverriders.end(); 5247 M != MEnd; 5248 ++M) { 5249 for (OverridingMethods::iterator SO = M->second.begin(), 5250 SOEnd = M->second.end(); 5251 SO != SOEnd; ++SO) { 5252 // C++ [class.abstract]p4: 5253 // A class is abstract if it contains or inherits at least one 5254 // pure virtual function for which the final overrider is pure 5255 // virtual. 5256 5257 // 5258 if (SO->second.size() != 1) 5259 continue; 5260 5261 if (!SO->second.front().Method->isPure()) 5262 continue; 5263 5264 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5265 continue; 5266 5267 Diag(SO->second.front().Method->getLocation(), 5268 diag::note_pure_virtual_function) 5269 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5270 } 5271 } 5272 5273 if (!PureVirtualClassDiagSet) 5274 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5275 PureVirtualClassDiagSet->insert(RD); 5276 } 5277 5278 namespace { 5279 struct AbstractUsageInfo { 5280 Sema &S; 5281 CXXRecordDecl *Record; 5282 CanQualType AbstractType; 5283 bool Invalid; 5284 5285 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5286 : S(S), Record(Record), 5287 AbstractType(S.Context.getCanonicalType( 5288 S.Context.getTypeDeclType(Record))), 5289 Invalid(false) {} 5290 5291 void DiagnoseAbstractType() { 5292 if (Invalid) return; 5293 S.DiagnoseAbstractType(Record); 5294 Invalid = true; 5295 } 5296 5297 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5298 }; 5299 5300 struct CheckAbstractUsage { 5301 AbstractUsageInfo &Info; 5302 const NamedDecl *Ctx; 5303 5304 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5305 : Info(Info), Ctx(Ctx) {} 5306 5307 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5308 switch (TL.getTypeLocClass()) { 5309 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5310 #define TYPELOC(CLASS, PARENT) \ 5311 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5312 #include "clang/AST/TypeLocNodes.def" 5313 } 5314 } 5315 5316 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5317 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5318 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5319 if (!TL.getParam(I)) 5320 continue; 5321 5322 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5323 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5324 } 5325 } 5326 5327 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5328 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5329 } 5330 5331 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5332 // Visit the type parameters from a permissive context. 5333 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5334 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5335 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5336 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5337 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5338 // TODO: other template argument types? 5339 } 5340 } 5341 5342 // Visit pointee types from a permissive context. 5343 #define CheckPolymorphic(Type) \ 5344 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5345 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5346 } 5347 CheckPolymorphic(PointerTypeLoc) 5348 CheckPolymorphic(ReferenceTypeLoc) 5349 CheckPolymorphic(MemberPointerTypeLoc) 5350 CheckPolymorphic(BlockPointerTypeLoc) 5351 CheckPolymorphic(AtomicTypeLoc) 5352 5353 /// Handle all the types we haven't given a more specific 5354 /// implementation for above. 5355 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5356 // Every other kind of type that we haven't called out already 5357 // that has an inner type is either (1) sugar or (2) contains that 5358 // inner type in some way as a subobject. 5359 if (TypeLoc Next = TL.getNextTypeLoc()) 5360 return Visit(Next, Sel); 5361 5362 // If there's no inner type and we're in a permissive context, 5363 // don't diagnose. 5364 if (Sel == Sema::AbstractNone) return; 5365 5366 // Check whether the type matches the abstract type. 5367 QualType T = TL.getType(); 5368 if (T->isArrayType()) { 5369 Sel = Sema::AbstractArrayType; 5370 T = Info.S.Context.getBaseElementType(T); 5371 } 5372 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5373 if (CT != Info.AbstractType) return; 5374 5375 // It matched; do some magic. 5376 if (Sel == Sema::AbstractArrayType) { 5377 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5378 << T << TL.getSourceRange(); 5379 } else { 5380 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5381 << Sel << T << TL.getSourceRange(); 5382 } 5383 Info.DiagnoseAbstractType(); 5384 } 5385 }; 5386 5387 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5388 Sema::AbstractDiagSelID Sel) { 5389 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5390 } 5391 5392 } 5393 5394 /// Check for invalid uses of an abstract type in a method declaration. 5395 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5396 CXXMethodDecl *MD) { 5397 // No need to do the check on definitions, which require that 5398 // the return/param types be complete. 5399 if (MD->doesThisDeclarationHaveABody()) 5400 return; 5401 5402 // For safety's sake, just ignore it if we don't have type source 5403 // information. This should never happen for non-implicit methods, 5404 // but... 5405 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5406 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5407 } 5408 5409 /// Check for invalid uses of an abstract type within a class definition. 5410 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5411 CXXRecordDecl *RD) { 5412 for (auto *D : RD->decls()) { 5413 if (D->isImplicit()) continue; 5414 5415 // Methods and method templates. 5416 if (isa<CXXMethodDecl>(D)) { 5417 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5418 } else if (isa<FunctionTemplateDecl>(D)) { 5419 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5420 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5421 5422 // Fields and static variables. 5423 } else if (isa<FieldDecl>(D)) { 5424 FieldDecl *FD = cast<FieldDecl>(D); 5425 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5426 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5427 } else if (isa<VarDecl>(D)) { 5428 VarDecl *VD = cast<VarDecl>(D); 5429 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5430 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5431 5432 // Nested classes and class templates. 5433 } else if (isa<CXXRecordDecl>(D)) { 5434 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5435 } else if (isa<ClassTemplateDecl>(D)) { 5436 CheckAbstractClassUsage(Info, 5437 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5438 } 5439 } 5440 } 5441 5442 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 5443 Attr *ClassAttr = getDLLAttr(Class); 5444 if (!ClassAttr) 5445 return; 5446 5447 assert(ClassAttr->getKind() == attr::DLLExport); 5448 5449 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5450 5451 if (TSK == TSK_ExplicitInstantiationDeclaration) 5452 // Don't go any further if this is just an explicit instantiation 5453 // declaration. 5454 return; 5455 5456 for (Decl *Member : Class->decls()) { 5457 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5458 if (!MD) 5459 continue; 5460 5461 if (Member->getAttr<DLLExportAttr>()) { 5462 if (MD->isUserProvided()) { 5463 // Instantiate non-default class member functions ... 5464 5465 // .. except for certain kinds of template specializations. 5466 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5467 continue; 5468 5469 S.MarkFunctionReferenced(Class->getLocation(), MD); 5470 5471 // The function will be passed to the consumer when its definition is 5472 // encountered. 5473 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5474 MD->isCopyAssignmentOperator() || 5475 MD->isMoveAssignmentOperator()) { 5476 // Synthesize and instantiate non-trivial implicit methods, explicitly 5477 // defaulted methods, and the copy and move assignment operators. The 5478 // latter are exported even if they are trivial, because the address of 5479 // an operator can be taken and should compare equal across libraries. 5480 DiagnosticErrorTrap Trap(S.Diags); 5481 S.MarkFunctionReferenced(Class->getLocation(), MD); 5482 if (Trap.hasErrorOccurred()) { 5483 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5484 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5485 break; 5486 } 5487 5488 // There is no later point when we will see the definition of this 5489 // function, so pass it to the consumer now. 5490 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5491 } 5492 } 5493 } 5494 } 5495 5496 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5497 CXXRecordDecl *Class) { 5498 // Only the MS ABI has default constructor closures, so we don't need to do 5499 // this semantic checking anywhere else. 5500 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5501 return; 5502 5503 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5504 for (Decl *Member : Class->decls()) { 5505 // Look for exported default constructors. 5506 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5507 if (!CD || !CD->isDefaultConstructor()) 5508 continue; 5509 auto *Attr = CD->getAttr<DLLExportAttr>(); 5510 if (!Attr) 5511 continue; 5512 5513 // If the class is non-dependent, mark the default arguments as ODR-used so 5514 // that we can properly codegen the constructor closure. 5515 if (!Class->isDependentContext()) { 5516 for (ParmVarDecl *PD : CD->parameters()) { 5517 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5518 S.DiscardCleanupsInEvaluationContext(); 5519 } 5520 } 5521 5522 if (LastExportedDefaultCtor) { 5523 S.Diag(LastExportedDefaultCtor->getLocation(), 5524 diag::err_attribute_dll_ambiguous_default_ctor) 5525 << Class; 5526 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5527 << CD->getDeclName(); 5528 return; 5529 } 5530 LastExportedDefaultCtor = CD; 5531 } 5532 } 5533 5534 /// \brief Check class-level dllimport/dllexport attribute. 5535 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5536 Attr *ClassAttr = getDLLAttr(Class); 5537 5538 // MSVC inherits DLL attributes to partial class template specializations. 5539 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5540 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5541 if (Attr *TemplateAttr = 5542 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5543 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5544 A->setInherited(true); 5545 ClassAttr = A; 5546 } 5547 } 5548 } 5549 5550 if (!ClassAttr) 5551 return; 5552 5553 if (!Class->isExternallyVisible()) { 5554 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5555 << Class << ClassAttr; 5556 return; 5557 } 5558 5559 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5560 !ClassAttr->isInherited()) { 5561 // Diagnose dll attributes on members of class with dll attribute. 5562 for (Decl *Member : Class->decls()) { 5563 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5564 continue; 5565 InheritableAttr *MemberAttr = getDLLAttr(Member); 5566 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5567 continue; 5568 5569 Diag(MemberAttr->getLocation(), 5570 diag::err_attribute_dll_member_of_dll_class) 5571 << MemberAttr << ClassAttr; 5572 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5573 Member->setInvalidDecl(); 5574 } 5575 } 5576 5577 if (Class->getDescribedClassTemplate()) 5578 // Don't inherit dll attribute until the template is instantiated. 5579 return; 5580 5581 // The class is either imported or exported. 5582 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5583 5584 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5585 5586 // Ignore explicit dllexport on explicit class template instantiation declarations. 5587 if (ClassExported && !ClassAttr->isInherited() && 5588 TSK == TSK_ExplicitInstantiationDeclaration) { 5589 Class->dropAttr<DLLExportAttr>(); 5590 return; 5591 } 5592 5593 // Force declaration of implicit members so they can inherit the attribute. 5594 ForceDeclarationOfImplicitMembers(Class); 5595 5596 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5597 // seem to be true in practice? 5598 5599 for (Decl *Member : Class->decls()) { 5600 VarDecl *VD = dyn_cast<VarDecl>(Member); 5601 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5602 5603 // Only methods and static fields inherit the attributes. 5604 if (!VD && !MD) 5605 continue; 5606 5607 if (MD) { 5608 // Don't process deleted methods. 5609 if (MD->isDeleted()) 5610 continue; 5611 5612 if (MD->isInlined()) { 5613 // MinGW does not import or export inline methods. 5614 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5615 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5616 continue; 5617 5618 // MSVC versions before 2015 don't export the move assignment operators 5619 // and move constructor, so don't attempt to import/export them if 5620 // we have a definition. 5621 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5622 if ((MD->isMoveAssignmentOperator() || 5623 (Ctor && Ctor->isMoveConstructor())) && 5624 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5625 continue; 5626 5627 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5628 // operator is exported anyway. 5629 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5630 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5631 continue; 5632 } 5633 } 5634 5635 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5636 continue; 5637 5638 if (!getDLLAttr(Member)) { 5639 auto *NewAttr = 5640 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5641 NewAttr->setInherited(true); 5642 Member->addAttr(NewAttr); 5643 } 5644 } 5645 5646 if (ClassExported) 5647 DelayedDllExportClasses.push_back(Class); 5648 } 5649 5650 /// \brief Perform propagation of DLL attributes from a derived class to a 5651 /// templated base class for MS compatibility. 5652 void Sema::propagateDLLAttrToBaseClassTemplate( 5653 CXXRecordDecl *Class, Attr *ClassAttr, 5654 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5655 if (getDLLAttr( 5656 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5657 // If the base class template has a DLL attribute, don't try to change it. 5658 return; 5659 } 5660 5661 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5662 if (!getDLLAttr(BaseTemplateSpec) && 5663 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5664 TSK == TSK_ImplicitInstantiation)) { 5665 // The template hasn't been instantiated yet (or it has, but only as an 5666 // explicit instantiation declaration or implicit instantiation, which means 5667 // we haven't codegenned any members yet), so propagate the attribute. 5668 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5669 NewAttr->setInherited(true); 5670 BaseTemplateSpec->addAttr(NewAttr); 5671 5672 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5673 // needs to be run again to work see the new attribute. Otherwise this will 5674 // get run whenever the template is instantiated. 5675 if (TSK != TSK_Undeclared) 5676 checkClassLevelDLLAttribute(BaseTemplateSpec); 5677 5678 return; 5679 } 5680 5681 if (getDLLAttr(BaseTemplateSpec)) { 5682 // The template has already been specialized or instantiated with an 5683 // attribute, explicitly or through propagation. We should not try to change 5684 // it. 5685 return; 5686 } 5687 5688 // The template was previously instantiated or explicitly specialized without 5689 // a dll attribute, It's too late for us to add an attribute, so warn that 5690 // this is unsupported. 5691 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5692 << BaseTemplateSpec->isExplicitSpecialization(); 5693 Diag(ClassAttr->getLocation(), diag::note_attribute); 5694 if (BaseTemplateSpec->isExplicitSpecialization()) { 5695 Diag(BaseTemplateSpec->getLocation(), 5696 diag::note_template_class_explicit_specialization_was_here) 5697 << BaseTemplateSpec; 5698 } else { 5699 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5700 diag::note_template_class_instantiation_was_here) 5701 << BaseTemplateSpec; 5702 } 5703 } 5704 5705 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5706 SourceLocation DefaultLoc) { 5707 switch (S.getSpecialMember(MD)) { 5708 case Sema::CXXDefaultConstructor: 5709 S.DefineImplicitDefaultConstructor(DefaultLoc, 5710 cast<CXXConstructorDecl>(MD)); 5711 break; 5712 case Sema::CXXCopyConstructor: 5713 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5714 break; 5715 case Sema::CXXCopyAssignment: 5716 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5717 break; 5718 case Sema::CXXDestructor: 5719 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5720 break; 5721 case Sema::CXXMoveConstructor: 5722 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5723 break; 5724 case Sema::CXXMoveAssignment: 5725 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5726 break; 5727 case Sema::CXXInvalid: 5728 llvm_unreachable("Invalid special member."); 5729 } 5730 } 5731 5732 /// Determine whether a type is permitted to be passed or returned in 5733 /// registers, per C++ [class.temporary]p3. 5734 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) { 5735 if (D->isDependentType() || D->isInvalidDecl()) 5736 return false; 5737 5738 // Per C++ [class.temporary]p3, the relevant condition is: 5739 // each copy constructor, move constructor, and destructor of X is 5740 // either trivial or deleted, and X has at least one non-deleted copy 5741 // or move constructor 5742 bool HasNonDeletedCopyOrMove = false; 5743 5744 if (D->needsImplicitCopyConstructor() && 5745 !D->defaultedCopyConstructorIsDeleted()) { 5746 if (!D->hasTrivialCopyConstructor()) 5747 return false; 5748 HasNonDeletedCopyOrMove = true; 5749 } 5750 5751 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5752 !D->defaultedMoveConstructorIsDeleted()) { 5753 if (!D->hasTrivialMoveConstructor()) 5754 return false; 5755 HasNonDeletedCopyOrMove = true; 5756 } 5757 5758 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5759 !D->hasTrivialDestructor()) 5760 return false; 5761 5762 for (const CXXMethodDecl *MD : D->methods()) { 5763 if (MD->isDeleted()) 5764 continue; 5765 5766 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5767 if (CD && CD->isCopyOrMoveConstructor()) 5768 HasNonDeletedCopyOrMove = true; 5769 else if (!isa<CXXDestructorDecl>(MD)) 5770 continue; 5771 5772 if (!MD->isTrivial()) 5773 return false; 5774 } 5775 5776 return HasNonDeletedCopyOrMove; 5777 } 5778 5779 /// \brief Perform semantic checks on a class definition that has been 5780 /// completing, introducing implicitly-declared members, checking for 5781 /// abstract types, etc. 5782 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5783 if (!Record) 5784 return; 5785 5786 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5787 AbstractUsageInfo Info(*this, Record); 5788 CheckAbstractClassUsage(Info, Record); 5789 } 5790 5791 // If this is not an aggregate type and has no user-declared constructor, 5792 // complain about any non-static data members of reference or const scalar 5793 // type, since they will never get initializers. 5794 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5795 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5796 !Record->isLambda()) { 5797 bool Complained = false; 5798 for (const auto *F : Record->fields()) { 5799 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5800 continue; 5801 5802 if (F->getType()->isReferenceType() || 5803 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5804 if (!Complained) { 5805 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5806 << Record->getTagKind() << Record; 5807 Complained = true; 5808 } 5809 5810 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5811 << F->getType()->isReferenceType() 5812 << F->getDeclName(); 5813 } 5814 } 5815 } 5816 5817 if (Record->getIdentifier()) { 5818 // C++ [class.mem]p13: 5819 // If T is the name of a class, then each of the following shall have a 5820 // name different from T: 5821 // - every member of every anonymous union that is a member of class T. 5822 // 5823 // C++ [class.mem]p14: 5824 // In addition, if class T has a user-declared constructor (12.1), every 5825 // non-static data member of class T shall have a name different from T. 5826 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5827 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5828 ++I) { 5829 NamedDecl *D = *I; 5830 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5831 isa<IndirectFieldDecl>(D)) { 5832 Diag(D->getLocation(), diag::err_member_name_of_class) 5833 << D->getDeclName(); 5834 break; 5835 } 5836 } 5837 } 5838 5839 // Warn if the class has virtual methods but non-virtual public destructor. 5840 if (Record->isPolymorphic() && !Record->isDependentType()) { 5841 CXXDestructorDecl *dtor = Record->getDestructor(); 5842 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5843 !Record->hasAttr<FinalAttr>()) 5844 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5845 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5846 } 5847 5848 if (Record->isAbstract()) { 5849 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5850 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5851 << FA->isSpelledAsSealed(); 5852 DiagnoseAbstractType(Record); 5853 } 5854 } 5855 5856 bool HasMethodWithOverrideControl = false, 5857 HasOverridingMethodWithoutOverrideControl = false; 5858 if (!Record->isDependentType()) { 5859 for (auto *M : Record->methods()) { 5860 // See if a method overloads virtual methods in a base 5861 // class without overriding any. 5862 if (!M->isStatic()) 5863 DiagnoseHiddenVirtualMethods(M); 5864 if (M->hasAttr<OverrideAttr>()) 5865 HasMethodWithOverrideControl = true; 5866 else if (M->size_overridden_methods() > 0) 5867 HasOverridingMethodWithoutOverrideControl = true; 5868 // Check whether the explicitly-defaulted special members are valid. 5869 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5870 CheckExplicitlyDefaultedSpecialMember(M); 5871 5872 // For an explicitly defaulted or deleted special member, we defer 5873 // determining triviality until the class is complete. That time is now! 5874 CXXSpecialMember CSM = getSpecialMember(M); 5875 if (!M->isImplicit() && !M->isUserProvided()) { 5876 if (CSM != CXXInvalid) { 5877 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5878 5879 // Inform the class that we've finished declaring this member. 5880 Record->finishedDefaultedOrDeletedMember(M); 5881 } 5882 } 5883 5884 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5885 M->hasAttr<DLLExportAttr>()) { 5886 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5887 M->isTrivial() && 5888 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5889 CSM == CXXDestructor)) 5890 M->dropAttr<DLLExportAttr>(); 5891 5892 if (M->hasAttr<DLLExportAttr>()) { 5893 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5894 ActOnFinishInlineFunctionDef(M); 5895 } 5896 } 5897 } 5898 } 5899 5900 if (HasMethodWithOverrideControl && 5901 HasOverridingMethodWithoutOverrideControl) { 5902 // At least one method has the 'override' control declared. 5903 // Diagnose all other overridden methods which do not have 'override' specified on them. 5904 for (auto *M : Record->methods()) 5905 DiagnoseAbsenceOfOverrideControl(M); 5906 } 5907 5908 // ms_struct is a request to use the same ABI rules as MSVC. Check 5909 // whether this class uses any C++ features that are implemented 5910 // completely differently in MSVC, and if so, emit a diagnostic. 5911 // That diagnostic defaults to an error, but we allow projects to 5912 // map it down to a warning (or ignore it). It's a fairly common 5913 // practice among users of the ms_struct pragma to mass-annotate 5914 // headers, sweeping up a bunch of types that the project doesn't 5915 // really rely on MSVC-compatible layout for. We must therefore 5916 // support "ms_struct except for C++ stuff" as a secondary ABI. 5917 if (Record->isMsStruct(Context) && 5918 (Record->isPolymorphic() || Record->getNumBases())) { 5919 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5920 } 5921 5922 checkClassLevelDLLAttribute(Record); 5923 5924 Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record)); 5925 } 5926 5927 /// Look up the special member function that would be called by a special 5928 /// member function for a subobject of class type. 5929 /// 5930 /// \param Class The class type of the subobject. 5931 /// \param CSM The kind of special member function. 5932 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5933 /// \param ConstRHS True if this is a copy operation with a const object 5934 /// on its RHS, that is, if the argument to the outer special member 5935 /// function is 'const' and this is not a field marked 'mutable'. 5936 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 5937 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5938 unsigned FieldQuals, bool ConstRHS) { 5939 unsigned LHSQuals = 0; 5940 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5941 LHSQuals = FieldQuals; 5942 5943 unsigned RHSQuals = FieldQuals; 5944 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5945 RHSQuals = 0; 5946 else if (ConstRHS) 5947 RHSQuals |= Qualifiers::Const; 5948 5949 return S.LookupSpecialMember(Class, CSM, 5950 RHSQuals & Qualifiers::Const, 5951 RHSQuals & Qualifiers::Volatile, 5952 false, 5953 LHSQuals & Qualifiers::Const, 5954 LHSQuals & Qualifiers::Volatile); 5955 } 5956 5957 class Sema::InheritedConstructorInfo { 5958 Sema &S; 5959 SourceLocation UseLoc; 5960 5961 /// A mapping from the base classes through which the constructor was 5962 /// inherited to the using shadow declaration in that base class (or a null 5963 /// pointer if the constructor was declared in that base class). 5964 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 5965 InheritedFromBases; 5966 5967 public: 5968 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 5969 ConstructorUsingShadowDecl *Shadow) 5970 : S(S), UseLoc(UseLoc) { 5971 bool DiagnosedMultipleConstructedBases = false; 5972 CXXRecordDecl *ConstructedBase = nullptr; 5973 UsingDecl *ConstructedBaseUsing = nullptr; 5974 5975 // Find the set of such base class subobjects and check that there's a 5976 // unique constructed subobject. 5977 for (auto *D : Shadow->redecls()) { 5978 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 5979 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 5980 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 5981 5982 InheritedFromBases.insert( 5983 std::make_pair(DNominatedBase->getCanonicalDecl(), 5984 DShadow->getNominatedBaseClassShadowDecl())); 5985 if (DShadow->constructsVirtualBase()) 5986 InheritedFromBases.insert( 5987 std::make_pair(DConstructedBase->getCanonicalDecl(), 5988 DShadow->getConstructedBaseClassShadowDecl())); 5989 else 5990 assert(DNominatedBase == DConstructedBase); 5991 5992 // [class.inhctor.init]p2: 5993 // If the constructor was inherited from multiple base class subobjects 5994 // of type B, the program is ill-formed. 5995 if (!ConstructedBase) { 5996 ConstructedBase = DConstructedBase; 5997 ConstructedBaseUsing = D->getUsingDecl(); 5998 } else if (ConstructedBase != DConstructedBase && 5999 !Shadow->isInvalidDecl()) { 6000 if (!DiagnosedMultipleConstructedBases) { 6001 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6002 << Shadow->getTargetDecl(); 6003 S.Diag(ConstructedBaseUsing->getLocation(), 6004 diag::note_ambiguous_inherited_constructor_using) 6005 << ConstructedBase; 6006 DiagnosedMultipleConstructedBases = true; 6007 } 6008 S.Diag(D->getUsingDecl()->getLocation(), 6009 diag::note_ambiguous_inherited_constructor_using) 6010 << DConstructedBase; 6011 } 6012 } 6013 6014 if (DiagnosedMultipleConstructedBases) 6015 Shadow->setInvalidDecl(); 6016 } 6017 6018 /// Find the constructor to use for inherited construction of a base class, 6019 /// and whether that base class constructor inherits the constructor from a 6020 /// virtual base class (in which case it won't actually invoke it). 6021 std::pair<CXXConstructorDecl *, bool> 6022 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6023 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6024 if (It == InheritedFromBases.end()) 6025 return std::make_pair(nullptr, false); 6026 6027 // This is an intermediary class. 6028 if (It->second) 6029 return std::make_pair( 6030 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6031 It->second->constructsVirtualBase()); 6032 6033 // This is the base class from which the constructor was inherited. 6034 return std::make_pair(Ctor, false); 6035 } 6036 }; 6037 6038 /// Is the special member function which would be selected to perform the 6039 /// specified operation on the specified class type a constexpr constructor? 6040 static bool 6041 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6042 Sema::CXXSpecialMember CSM, unsigned Quals, 6043 bool ConstRHS, 6044 CXXConstructorDecl *InheritedCtor = nullptr, 6045 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6046 // If we're inheriting a constructor, see if we need to call it for this base 6047 // class. 6048 if (InheritedCtor) { 6049 assert(CSM == Sema::CXXDefaultConstructor); 6050 auto BaseCtor = 6051 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6052 if (BaseCtor) 6053 return BaseCtor->isConstexpr(); 6054 } 6055 6056 if (CSM == Sema::CXXDefaultConstructor) 6057 return ClassDecl->hasConstexprDefaultConstructor(); 6058 6059 Sema::SpecialMemberOverloadResult SMOR = 6060 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6061 if (!SMOR.getMethod()) 6062 // A constructor we wouldn't select can't be "involved in initializing" 6063 // anything. 6064 return true; 6065 return SMOR.getMethod()->isConstexpr(); 6066 } 6067 6068 /// Determine whether the specified special member function would be constexpr 6069 /// if it were implicitly defined. 6070 static bool defaultedSpecialMemberIsConstexpr( 6071 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6072 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6073 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6074 if (!S.getLangOpts().CPlusPlus11) 6075 return false; 6076 6077 // C++11 [dcl.constexpr]p4: 6078 // In the definition of a constexpr constructor [...] 6079 bool Ctor = true; 6080 switch (CSM) { 6081 case Sema::CXXDefaultConstructor: 6082 if (Inherited) 6083 break; 6084 // Since default constructor lookup is essentially trivial (and cannot 6085 // involve, for instance, template instantiation), we compute whether a 6086 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6087 // 6088 // This is important for performance; we need to know whether the default 6089 // constructor is constexpr to determine whether the type is a literal type. 6090 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6091 6092 case Sema::CXXCopyConstructor: 6093 case Sema::CXXMoveConstructor: 6094 // For copy or move constructors, we need to perform overload resolution. 6095 break; 6096 6097 case Sema::CXXCopyAssignment: 6098 case Sema::CXXMoveAssignment: 6099 if (!S.getLangOpts().CPlusPlus14) 6100 return false; 6101 // In C++1y, we need to perform overload resolution. 6102 Ctor = false; 6103 break; 6104 6105 case Sema::CXXDestructor: 6106 case Sema::CXXInvalid: 6107 return false; 6108 } 6109 6110 // -- if the class is a non-empty union, or for each non-empty anonymous 6111 // union member of a non-union class, exactly one non-static data member 6112 // shall be initialized; [DR1359] 6113 // 6114 // If we squint, this is guaranteed, since exactly one non-static data member 6115 // will be initialized (if the constructor isn't deleted), we just don't know 6116 // which one. 6117 if (Ctor && ClassDecl->isUnion()) 6118 return CSM == Sema::CXXDefaultConstructor 6119 ? ClassDecl->hasInClassInitializer() || 6120 !ClassDecl->hasVariantMembers() 6121 : true; 6122 6123 // -- the class shall not have any virtual base classes; 6124 if (Ctor && ClassDecl->getNumVBases()) 6125 return false; 6126 6127 // C++1y [class.copy]p26: 6128 // -- [the class] is a literal type, and 6129 if (!Ctor && !ClassDecl->isLiteral()) 6130 return false; 6131 6132 // -- every constructor involved in initializing [...] base class 6133 // sub-objects shall be a constexpr constructor; 6134 // -- the assignment operator selected to copy/move each direct base 6135 // class is a constexpr function, and 6136 for (const auto &B : ClassDecl->bases()) { 6137 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6138 if (!BaseType) continue; 6139 6140 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6141 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6142 InheritedCtor, Inherited)) 6143 return false; 6144 } 6145 6146 // -- every constructor involved in initializing non-static data members 6147 // [...] shall be a constexpr constructor; 6148 // -- every non-static data member and base class sub-object shall be 6149 // initialized 6150 // -- for each non-static data member of X that is of class type (or array 6151 // thereof), the assignment operator selected to copy/move that member is 6152 // a constexpr function 6153 for (const auto *F : ClassDecl->fields()) { 6154 if (F->isInvalidDecl()) 6155 continue; 6156 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6157 continue; 6158 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6159 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6160 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6161 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6162 BaseType.getCVRQualifiers(), 6163 ConstArg && !F->isMutable())) 6164 return false; 6165 } else if (CSM == Sema::CXXDefaultConstructor) { 6166 return false; 6167 } 6168 } 6169 6170 // All OK, it's constexpr! 6171 return true; 6172 } 6173 6174 static Sema::ImplicitExceptionSpecification 6175 ComputeDefaultedSpecialMemberExceptionSpec( 6176 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6177 Sema::InheritedConstructorInfo *ICI); 6178 6179 static Sema::ImplicitExceptionSpecification 6180 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6181 auto CSM = S.getSpecialMember(MD); 6182 if (CSM != Sema::CXXInvalid) 6183 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6184 6185 auto *CD = cast<CXXConstructorDecl>(MD); 6186 assert(CD->getInheritedConstructor() && 6187 "only special members have implicit exception specs"); 6188 Sema::InheritedConstructorInfo ICI( 6189 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6190 return ComputeDefaultedSpecialMemberExceptionSpec( 6191 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6192 } 6193 6194 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6195 CXXMethodDecl *MD) { 6196 FunctionProtoType::ExtProtoInfo EPI; 6197 6198 // Build an exception specification pointing back at this member. 6199 EPI.ExceptionSpec.Type = EST_Unevaluated; 6200 EPI.ExceptionSpec.SourceDecl = MD; 6201 6202 // Set the calling convention to the default for C++ instance methods. 6203 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6204 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6205 /*IsCXXMethod=*/true)); 6206 return EPI; 6207 } 6208 6209 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6210 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6211 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6212 return; 6213 6214 // Evaluate the exception specification. 6215 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6216 auto ESI = IES.getExceptionSpec(); 6217 6218 // Update the type of the special member to use it. 6219 UpdateExceptionSpec(MD, ESI); 6220 6221 // A user-provided destructor can be defined outside the class. When that 6222 // happens, be sure to update the exception specification on both 6223 // declarations. 6224 const FunctionProtoType *CanonicalFPT = 6225 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6226 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6227 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6228 } 6229 6230 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6231 CXXRecordDecl *RD = MD->getParent(); 6232 CXXSpecialMember CSM = getSpecialMember(MD); 6233 6234 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6235 "not an explicitly-defaulted special member"); 6236 6237 // Whether this was the first-declared instance of the constructor. 6238 // This affects whether we implicitly add an exception spec and constexpr. 6239 bool First = MD == MD->getCanonicalDecl(); 6240 6241 bool HadError = false; 6242 6243 // C++11 [dcl.fct.def.default]p1: 6244 // A function that is explicitly defaulted shall 6245 // -- be a special member function (checked elsewhere), 6246 // -- have the same type (except for ref-qualifiers, and except that a 6247 // copy operation can take a non-const reference) as an implicit 6248 // declaration, and 6249 // -- not have default arguments. 6250 unsigned ExpectedParams = 1; 6251 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6252 ExpectedParams = 0; 6253 if (MD->getNumParams() != ExpectedParams) { 6254 // This also checks for default arguments: a copy or move constructor with a 6255 // default argument is classified as a default constructor, and assignment 6256 // operations and destructors can't have default arguments. 6257 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6258 << CSM << MD->getSourceRange(); 6259 HadError = true; 6260 } else if (MD->isVariadic()) { 6261 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6262 << CSM << MD->getSourceRange(); 6263 HadError = true; 6264 } 6265 6266 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6267 6268 bool CanHaveConstParam = false; 6269 if (CSM == CXXCopyConstructor) 6270 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6271 else if (CSM == CXXCopyAssignment) 6272 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6273 6274 QualType ReturnType = Context.VoidTy; 6275 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6276 // Check for return type matching. 6277 ReturnType = Type->getReturnType(); 6278 QualType ExpectedReturnType = 6279 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6280 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6281 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6282 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6283 HadError = true; 6284 } 6285 6286 // A defaulted special member cannot have cv-qualifiers. 6287 if (Type->getTypeQuals()) { 6288 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6289 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6290 HadError = true; 6291 } 6292 } 6293 6294 // Check for parameter type matching. 6295 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6296 bool HasConstParam = false; 6297 if (ExpectedParams && ArgType->isReferenceType()) { 6298 // Argument must be reference to possibly-const T. 6299 QualType ReferentType = ArgType->getPointeeType(); 6300 HasConstParam = ReferentType.isConstQualified(); 6301 6302 if (ReferentType.isVolatileQualified()) { 6303 Diag(MD->getLocation(), 6304 diag::err_defaulted_special_member_volatile_param) << CSM; 6305 HadError = true; 6306 } 6307 6308 if (HasConstParam && !CanHaveConstParam) { 6309 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6310 Diag(MD->getLocation(), 6311 diag::err_defaulted_special_member_copy_const_param) 6312 << (CSM == CXXCopyAssignment); 6313 // FIXME: Explain why this special member can't be const. 6314 } else { 6315 Diag(MD->getLocation(), 6316 diag::err_defaulted_special_member_move_const_param) 6317 << (CSM == CXXMoveAssignment); 6318 } 6319 HadError = true; 6320 } 6321 } else if (ExpectedParams) { 6322 // A copy assignment operator can take its argument by value, but a 6323 // defaulted one cannot. 6324 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6325 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6326 HadError = true; 6327 } 6328 6329 // C++11 [dcl.fct.def.default]p2: 6330 // An explicitly-defaulted function may be declared constexpr only if it 6331 // would have been implicitly declared as constexpr, 6332 // Do not apply this rule to members of class templates, since core issue 1358 6333 // makes such functions always instantiate to constexpr functions. For 6334 // functions which cannot be constexpr (for non-constructors in C++11 and for 6335 // destructors in C++1y), this is checked elsewhere. 6336 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6337 HasConstParam); 6338 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6339 : isa<CXXConstructorDecl>(MD)) && 6340 MD->isConstexpr() && !Constexpr && 6341 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6342 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6343 // FIXME: Explain why the special member can't be constexpr. 6344 HadError = true; 6345 } 6346 6347 // and may have an explicit exception-specification only if it is compatible 6348 // with the exception-specification on the implicit declaration. 6349 if (Type->hasExceptionSpec()) { 6350 // Delay the check if this is the first declaration of the special member, 6351 // since we may not have parsed some necessary in-class initializers yet. 6352 if (First) { 6353 // If the exception specification needs to be instantiated, do so now, 6354 // before we clobber it with an EST_Unevaluated specification below. 6355 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6356 InstantiateExceptionSpec(MD->getLocStart(), MD); 6357 Type = MD->getType()->getAs<FunctionProtoType>(); 6358 } 6359 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6360 } else 6361 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6362 } 6363 6364 // If a function is explicitly defaulted on its first declaration, 6365 if (First) { 6366 // -- it is implicitly considered to be constexpr if the implicit 6367 // definition would be, 6368 MD->setConstexpr(Constexpr); 6369 6370 // -- it is implicitly considered to have the same exception-specification 6371 // as if it had been implicitly declared, 6372 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6373 EPI.ExceptionSpec.Type = EST_Unevaluated; 6374 EPI.ExceptionSpec.SourceDecl = MD; 6375 MD->setType(Context.getFunctionType(ReturnType, 6376 llvm::makeArrayRef(&ArgType, 6377 ExpectedParams), 6378 EPI)); 6379 } 6380 6381 if (ShouldDeleteSpecialMember(MD, CSM)) { 6382 if (First) { 6383 SetDeclDeleted(MD, MD->getLocation()); 6384 } else { 6385 // C++11 [dcl.fct.def.default]p4: 6386 // [For a] user-provided explicitly-defaulted function [...] if such a 6387 // function is implicitly defined as deleted, the program is ill-formed. 6388 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6389 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6390 HadError = true; 6391 } 6392 } 6393 6394 if (HadError) 6395 MD->setInvalidDecl(); 6396 } 6397 6398 /// Check whether the exception specification provided for an 6399 /// explicitly-defaulted special member matches the exception specification 6400 /// that would have been generated for an implicit special member, per 6401 /// C++11 [dcl.fct.def.default]p2. 6402 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6403 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6404 // If the exception specification was explicitly specified but hadn't been 6405 // parsed when the method was defaulted, grab it now. 6406 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6407 SpecifiedType = 6408 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6409 6410 // Compute the implicit exception specification. 6411 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6412 /*IsCXXMethod=*/true); 6413 FunctionProtoType::ExtProtoInfo EPI(CC); 6414 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6415 EPI.ExceptionSpec = IES.getExceptionSpec(); 6416 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6417 Context.getFunctionType(Context.VoidTy, None, EPI)); 6418 6419 // Ensure that it matches. 6420 CheckEquivalentExceptionSpec( 6421 PDiag(diag::err_incorrect_defaulted_exception_spec) 6422 << getSpecialMember(MD), PDiag(), 6423 ImplicitType, SourceLocation(), 6424 SpecifiedType, MD->getLocation()); 6425 } 6426 6427 void Sema::CheckDelayedMemberExceptionSpecs() { 6428 decltype(DelayedExceptionSpecChecks) Checks; 6429 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6430 6431 std::swap(Checks, DelayedExceptionSpecChecks); 6432 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6433 6434 // Perform any deferred checking of exception specifications for virtual 6435 // destructors. 6436 for (auto &Check : Checks) 6437 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6438 6439 // Check that any explicitly-defaulted methods have exception specifications 6440 // compatible with their implicit exception specifications. 6441 for (auto &Spec : Specs) 6442 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6443 } 6444 6445 namespace { 6446 /// CRTP base class for visiting operations performed by a special member 6447 /// function (or inherited constructor). 6448 template<typename Derived> 6449 struct SpecialMemberVisitor { 6450 Sema &S; 6451 CXXMethodDecl *MD; 6452 Sema::CXXSpecialMember CSM; 6453 Sema::InheritedConstructorInfo *ICI; 6454 6455 // Properties of the special member, computed for convenience. 6456 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6457 6458 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6459 Sema::InheritedConstructorInfo *ICI) 6460 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6461 switch (CSM) { 6462 case Sema::CXXDefaultConstructor: 6463 case Sema::CXXCopyConstructor: 6464 case Sema::CXXMoveConstructor: 6465 IsConstructor = true; 6466 break; 6467 case Sema::CXXCopyAssignment: 6468 case Sema::CXXMoveAssignment: 6469 IsAssignment = true; 6470 break; 6471 case Sema::CXXDestructor: 6472 break; 6473 case Sema::CXXInvalid: 6474 llvm_unreachable("invalid special member kind"); 6475 } 6476 6477 if (MD->getNumParams()) { 6478 if (const ReferenceType *RT = 6479 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6480 ConstArg = RT->getPointeeType().isConstQualified(); 6481 } 6482 } 6483 6484 Derived &getDerived() { return static_cast<Derived&>(*this); } 6485 6486 /// Is this a "move" special member? 6487 bool isMove() const { 6488 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6489 } 6490 6491 /// Look up the corresponding special member in the given class. 6492 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6493 unsigned Quals, bool IsMutable) { 6494 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6495 ConstArg && !IsMutable); 6496 } 6497 6498 /// Look up the constructor for the specified base class to see if it's 6499 /// overridden due to this being an inherited constructor. 6500 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6501 if (!ICI) 6502 return {}; 6503 assert(CSM == Sema::CXXDefaultConstructor); 6504 auto *BaseCtor = 6505 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6506 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6507 return MD; 6508 return {}; 6509 } 6510 6511 /// A base or member subobject. 6512 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6513 6514 /// Get the location to use for a subobject in diagnostics. 6515 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6516 // FIXME: For an indirect virtual base, the direct base leading to 6517 // the indirect virtual base would be a more useful choice. 6518 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6519 return B->getBaseTypeLoc(); 6520 else 6521 return Subobj.get<FieldDecl*>()->getLocation(); 6522 } 6523 6524 enum BasesToVisit { 6525 /// Visit all non-virtual (direct) bases. 6526 VisitNonVirtualBases, 6527 /// Visit all direct bases, virtual or not. 6528 VisitDirectBases, 6529 /// Visit all non-virtual bases, and all virtual bases if the class 6530 /// is not abstract. 6531 VisitPotentiallyConstructedBases, 6532 /// Visit all direct or virtual bases. 6533 VisitAllBases 6534 }; 6535 6536 // Visit the bases and members of the class. 6537 bool visit(BasesToVisit Bases) { 6538 CXXRecordDecl *RD = MD->getParent(); 6539 6540 if (Bases == VisitPotentiallyConstructedBases) 6541 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6542 6543 for (auto &B : RD->bases()) 6544 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6545 getDerived().visitBase(&B)) 6546 return true; 6547 6548 if (Bases == VisitAllBases) 6549 for (auto &B : RD->vbases()) 6550 if (getDerived().visitBase(&B)) 6551 return true; 6552 6553 for (auto *F : RD->fields()) 6554 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6555 getDerived().visitField(F)) 6556 return true; 6557 6558 return false; 6559 } 6560 }; 6561 } 6562 6563 namespace { 6564 struct SpecialMemberDeletionInfo 6565 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6566 bool Diagnose; 6567 6568 SourceLocation Loc; 6569 6570 bool AllFieldsAreConst; 6571 6572 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6573 Sema::CXXSpecialMember CSM, 6574 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6575 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6576 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6577 6578 bool inUnion() const { return MD->getParent()->isUnion(); } 6579 6580 Sema::CXXSpecialMember getEffectiveCSM() { 6581 return ICI ? Sema::CXXInvalid : CSM; 6582 } 6583 6584 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6585 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6586 6587 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6588 bool shouldDeleteForField(FieldDecl *FD); 6589 bool shouldDeleteForAllConstMembers(); 6590 6591 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6592 unsigned Quals); 6593 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6594 Sema::SpecialMemberOverloadResult SMOR, 6595 bool IsDtorCallInCtor); 6596 6597 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6598 }; 6599 } 6600 6601 /// Is the given special member inaccessible when used on the given 6602 /// sub-object. 6603 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6604 CXXMethodDecl *target) { 6605 /// If we're operating on a base class, the object type is the 6606 /// type of this special member. 6607 QualType objectTy; 6608 AccessSpecifier access = target->getAccess(); 6609 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6610 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6611 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6612 6613 // If we're operating on a field, the object type is the type of the field. 6614 } else { 6615 objectTy = S.Context.getTypeDeclType(target->getParent()); 6616 } 6617 6618 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6619 } 6620 6621 /// Check whether we should delete a special member due to the implicit 6622 /// definition containing a call to a special member of a subobject. 6623 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6624 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6625 bool IsDtorCallInCtor) { 6626 CXXMethodDecl *Decl = SMOR.getMethod(); 6627 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6628 6629 int DiagKind = -1; 6630 6631 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6632 DiagKind = !Decl ? 0 : 1; 6633 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6634 DiagKind = 2; 6635 else if (!isAccessible(Subobj, Decl)) 6636 DiagKind = 3; 6637 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6638 !Decl->isTrivial()) { 6639 // A member of a union must have a trivial corresponding special member. 6640 // As a weird special case, a destructor call from a union's constructor 6641 // must be accessible and non-deleted, but need not be trivial. Such a 6642 // destructor is never actually called, but is semantically checked as 6643 // if it were. 6644 DiagKind = 4; 6645 } 6646 6647 if (DiagKind == -1) 6648 return false; 6649 6650 if (Diagnose) { 6651 if (Field) { 6652 S.Diag(Field->getLocation(), 6653 diag::note_deleted_special_member_class_subobject) 6654 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6655 << Field << DiagKind << IsDtorCallInCtor; 6656 } else { 6657 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6658 S.Diag(Base->getLocStart(), 6659 diag::note_deleted_special_member_class_subobject) 6660 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6661 << Base->getType() << DiagKind << IsDtorCallInCtor; 6662 } 6663 6664 if (DiagKind == 1) 6665 S.NoteDeletedFunction(Decl); 6666 // FIXME: Explain inaccessibility if DiagKind == 3. 6667 } 6668 6669 return true; 6670 } 6671 6672 /// Check whether we should delete a special member function due to having a 6673 /// direct or virtual base class or non-static data member of class type M. 6674 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6675 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6676 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6677 bool IsMutable = Field && Field->isMutable(); 6678 6679 // C++11 [class.ctor]p5: 6680 // -- any direct or virtual base class, or non-static data member with no 6681 // brace-or-equal-initializer, has class type M (or array thereof) and 6682 // either M has no default constructor or overload resolution as applied 6683 // to M's default constructor results in an ambiguity or in a function 6684 // that is deleted or inaccessible 6685 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6686 // -- a direct or virtual base class B that cannot be copied/moved because 6687 // overload resolution, as applied to B's corresponding special member, 6688 // results in an ambiguity or a function that is deleted or inaccessible 6689 // from the defaulted special member 6690 // C++11 [class.dtor]p5: 6691 // -- any direct or virtual base class [...] has a type with a destructor 6692 // that is deleted or inaccessible 6693 if (!(CSM == Sema::CXXDefaultConstructor && 6694 Field && Field->hasInClassInitializer()) && 6695 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6696 false)) 6697 return true; 6698 6699 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6700 // -- any direct or virtual base class or non-static data member has a 6701 // type with a destructor that is deleted or inaccessible 6702 if (IsConstructor) { 6703 Sema::SpecialMemberOverloadResult SMOR = 6704 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6705 false, false, false, false, false); 6706 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6707 return true; 6708 } 6709 6710 return false; 6711 } 6712 6713 /// Check whether we should delete a special member function due to the class 6714 /// having a particular direct or virtual base class. 6715 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6716 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6717 // If program is correct, BaseClass cannot be null, but if it is, the error 6718 // must be reported elsewhere. 6719 if (!BaseClass) 6720 return false; 6721 // If we have an inheriting constructor, check whether we're calling an 6722 // inherited constructor instead of a default constructor. 6723 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6724 if (auto *BaseCtor = SMOR.getMethod()) { 6725 // Note that we do not check access along this path; other than that, 6726 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6727 // FIXME: Check that the base has a usable destructor! Sink this into 6728 // shouldDeleteForClassSubobject. 6729 if (BaseCtor->isDeleted() && Diagnose) { 6730 S.Diag(Base->getLocStart(), 6731 diag::note_deleted_special_member_class_subobject) 6732 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6733 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6734 S.NoteDeletedFunction(BaseCtor); 6735 } 6736 return BaseCtor->isDeleted(); 6737 } 6738 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6739 } 6740 6741 /// Check whether we should delete a special member function due to the class 6742 /// having a particular non-static data member. 6743 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6744 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6745 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6746 6747 if (CSM == Sema::CXXDefaultConstructor) { 6748 // For a default constructor, all references must be initialized in-class 6749 // and, if a union, it must have a non-const member. 6750 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6751 if (Diagnose) 6752 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6753 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6754 return true; 6755 } 6756 // C++11 [class.ctor]p5: any non-variant non-static data member of 6757 // const-qualified type (or array thereof) with no 6758 // brace-or-equal-initializer does not have a user-provided default 6759 // constructor. 6760 if (!inUnion() && FieldType.isConstQualified() && 6761 !FD->hasInClassInitializer() && 6762 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6763 if (Diagnose) 6764 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6765 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6766 return true; 6767 } 6768 6769 if (inUnion() && !FieldType.isConstQualified()) 6770 AllFieldsAreConst = false; 6771 } else if (CSM == Sema::CXXCopyConstructor) { 6772 // For a copy constructor, data members must not be of rvalue reference 6773 // type. 6774 if (FieldType->isRValueReferenceType()) { 6775 if (Diagnose) 6776 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6777 << MD->getParent() << FD << FieldType; 6778 return true; 6779 } 6780 } else if (IsAssignment) { 6781 // For an assignment operator, data members must not be of reference type. 6782 if (FieldType->isReferenceType()) { 6783 if (Diagnose) 6784 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6785 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6786 return true; 6787 } 6788 if (!FieldRecord && FieldType.isConstQualified()) { 6789 // C++11 [class.copy]p23: 6790 // -- a non-static data member of const non-class type (or array thereof) 6791 if (Diagnose) 6792 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6793 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6794 return true; 6795 } 6796 } 6797 6798 if (FieldRecord) { 6799 // Some additional restrictions exist on the variant members. 6800 if (!inUnion() && FieldRecord->isUnion() && 6801 FieldRecord->isAnonymousStructOrUnion()) { 6802 bool AllVariantFieldsAreConst = true; 6803 6804 // FIXME: Handle anonymous unions declared within anonymous unions. 6805 for (auto *UI : FieldRecord->fields()) { 6806 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6807 6808 if (!UnionFieldType.isConstQualified()) 6809 AllVariantFieldsAreConst = false; 6810 6811 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6812 if (UnionFieldRecord && 6813 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6814 UnionFieldType.getCVRQualifiers())) 6815 return true; 6816 } 6817 6818 // At least one member in each anonymous union must be non-const 6819 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6820 !FieldRecord->field_empty()) { 6821 if (Diagnose) 6822 S.Diag(FieldRecord->getLocation(), 6823 diag::note_deleted_default_ctor_all_const) 6824 << !!ICI << MD->getParent() << /*anonymous union*/1; 6825 return true; 6826 } 6827 6828 // Don't check the implicit member of the anonymous union type. 6829 // This is technically non-conformant, but sanity demands it. 6830 return false; 6831 } 6832 6833 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6834 FieldType.getCVRQualifiers())) 6835 return true; 6836 } 6837 6838 return false; 6839 } 6840 6841 /// C++11 [class.ctor] p5: 6842 /// A defaulted default constructor for a class X is defined as deleted if 6843 /// X is a union and all of its variant members are of const-qualified type. 6844 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6845 // This is a silly definition, because it gives an empty union a deleted 6846 // default constructor. Don't do that. 6847 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 6848 bool AnyFields = false; 6849 for (auto *F : MD->getParent()->fields()) 6850 if ((AnyFields = !F->isUnnamedBitfield())) 6851 break; 6852 if (!AnyFields) 6853 return false; 6854 if (Diagnose) 6855 S.Diag(MD->getParent()->getLocation(), 6856 diag::note_deleted_default_ctor_all_const) 6857 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6858 return true; 6859 } 6860 return false; 6861 } 6862 6863 /// Determine whether a defaulted special member function should be defined as 6864 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6865 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6866 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6867 InheritedConstructorInfo *ICI, 6868 bool Diagnose) { 6869 if (MD->isInvalidDecl()) 6870 return false; 6871 CXXRecordDecl *RD = MD->getParent(); 6872 assert(!RD->isDependentType() && "do deletion after instantiation"); 6873 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6874 return false; 6875 6876 // C++11 [expr.lambda.prim]p19: 6877 // The closure type associated with a lambda-expression has a 6878 // deleted (8.4.3) default constructor and a deleted copy 6879 // assignment operator. 6880 if (RD->isLambda() && 6881 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6882 if (Diagnose) 6883 Diag(RD->getLocation(), diag::note_lambda_decl); 6884 return true; 6885 } 6886 6887 // For an anonymous struct or union, the copy and assignment special members 6888 // will never be used, so skip the check. For an anonymous union declared at 6889 // namespace scope, the constructor and destructor are used. 6890 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6891 RD->isAnonymousStructOrUnion()) 6892 return false; 6893 6894 // C++11 [class.copy]p7, p18: 6895 // If the class definition declares a move constructor or move assignment 6896 // operator, an implicitly declared copy constructor or copy assignment 6897 // operator is defined as deleted. 6898 if (MD->isImplicit() && 6899 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6900 CXXMethodDecl *UserDeclaredMove = nullptr; 6901 6902 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 6903 // deletion of the corresponding copy operation, not both copy operations. 6904 // MSVC 2015 has adopted the standards conforming behavior. 6905 bool DeletesOnlyMatchingCopy = 6906 getLangOpts().MSVCCompat && 6907 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 6908 6909 if (RD->hasUserDeclaredMoveConstructor() && 6910 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 6911 if (!Diagnose) return true; 6912 6913 // Find any user-declared move constructor. 6914 for (auto *I : RD->ctors()) { 6915 if (I->isMoveConstructor()) { 6916 UserDeclaredMove = I; 6917 break; 6918 } 6919 } 6920 assert(UserDeclaredMove); 6921 } else if (RD->hasUserDeclaredMoveAssignment() && 6922 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 6923 if (!Diagnose) return true; 6924 6925 // Find any user-declared move assignment operator. 6926 for (auto *I : RD->methods()) { 6927 if (I->isMoveAssignmentOperator()) { 6928 UserDeclaredMove = I; 6929 break; 6930 } 6931 } 6932 assert(UserDeclaredMove); 6933 } 6934 6935 if (UserDeclaredMove) { 6936 Diag(UserDeclaredMove->getLocation(), 6937 diag::note_deleted_copy_user_declared_move) 6938 << (CSM == CXXCopyAssignment) << RD 6939 << UserDeclaredMove->isMoveAssignmentOperator(); 6940 return true; 6941 } 6942 } 6943 6944 // Do access control from the special member function 6945 ContextRAII MethodContext(*this, MD); 6946 6947 // C++11 [class.dtor]p5: 6948 // -- for a virtual destructor, lookup of the non-array deallocation function 6949 // results in an ambiguity or in a function that is deleted or inaccessible 6950 if (CSM == CXXDestructor && MD->isVirtual()) { 6951 FunctionDecl *OperatorDelete = nullptr; 6952 DeclarationName Name = 6953 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6954 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 6955 OperatorDelete, /*Diagnose*/false)) { 6956 if (Diagnose) 6957 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 6958 return true; 6959 } 6960 } 6961 6962 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 6963 6964 // Per DR1611, do not consider virtual bases of constructors of abstract 6965 // classes, since we are not going to construct them. 6966 // Per DR1658, do not consider virtual bases of destructors of abstract 6967 // classes either. 6968 // Per DR2180, for assignment operators we only assign (and thus only 6969 // consider) direct bases. 6970 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 6971 : SMI.VisitPotentiallyConstructedBases)) 6972 return true; 6973 6974 if (SMI.shouldDeleteForAllConstMembers()) 6975 return true; 6976 6977 if (getLangOpts().CUDA) { 6978 // We should delete the special member in CUDA mode if target inference 6979 // failed. 6980 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 6981 Diagnose); 6982 } 6983 6984 return false; 6985 } 6986 6987 /// Perform lookup for a special member of the specified kind, and determine 6988 /// whether it is trivial. If the triviality can be determined without the 6989 /// lookup, skip it. This is intended for use when determining whether a 6990 /// special member of a containing object is trivial, and thus does not ever 6991 /// perform overload resolution for default constructors. 6992 /// 6993 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 6994 /// member that was most likely to be intended to be trivial, if any. 6995 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 6996 Sema::CXXSpecialMember CSM, unsigned Quals, 6997 bool ConstRHS, CXXMethodDecl **Selected) { 6998 if (Selected) 6999 *Selected = nullptr; 7000 7001 switch (CSM) { 7002 case Sema::CXXInvalid: 7003 llvm_unreachable("not a special member"); 7004 7005 case Sema::CXXDefaultConstructor: 7006 // C++11 [class.ctor]p5: 7007 // A default constructor is trivial if: 7008 // - all the [direct subobjects] have trivial default constructors 7009 // 7010 // Note, no overload resolution is performed in this case. 7011 if (RD->hasTrivialDefaultConstructor()) 7012 return true; 7013 7014 if (Selected) { 7015 // If there's a default constructor which could have been trivial, dig it 7016 // out. Otherwise, if there's any user-provided default constructor, point 7017 // to that as an example of why there's not a trivial one. 7018 CXXConstructorDecl *DefCtor = nullptr; 7019 if (RD->needsImplicitDefaultConstructor()) 7020 S.DeclareImplicitDefaultConstructor(RD); 7021 for (auto *CI : RD->ctors()) { 7022 if (!CI->isDefaultConstructor()) 7023 continue; 7024 DefCtor = CI; 7025 if (!DefCtor->isUserProvided()) 7026 break; 7027 } 7028 7029 *Selected = DefCtor; 7030 } 7031 7032 return false; 7033 7034 case Sema::CXXDestructor: 7035 // C++11 [class.dtor]p5: 7036 // A destructor is trivial if: 7037 // - all the direct [subobjects] have trivial destructors 7038 if (RD->hasTrivialDestructor()) 7039 return true; 7040 7041 if (Selected) { 7042 if (RD->needsImplicitDestructor()) 7043 S.DeclareImplicitDestructor(RD); 7044 *Selected = RD->getDestructor(); 7045 } 7046 7047 return false; 7048 7049 case Sema::CXXCopyConstructor: 7050 // C++11 [class.copy]p12: 7051 // A copy constructor is trivial if: 7052 // - the constructor selected to copy each direct [subobject] is trivial 7053 if (RD->hasTrivialCopyConstructor()) { 7054 if (Quals == Qualifiers::Const) 7055 // We must either select the trivial copy constructor or reach an 7056 // ambiguity; no need to actually perform overload resolution. 7057 return true; 7058 } else if (!Selected) { 7059 return false; 7060 } 7061 // In C++98, we are not supposed to perform overload resolution here, but we 7062 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7063 // cases like B as having a non-trivial copy constructor: 7064 // struct A { template<typename T> A(T&); }; 7065 // struct B { mutable A a; }; 7066 goto NeedOverloadResolution; 7067 7068 case Sema::CXXCopyAssignment: 7069 // C++11 [class.copy]p25: 7070 // A copy assignment operator is trivial if: 7071 // - the assignment operator selected to copy each direct [subobject] is 7072 // trivial 7073 if (RD->hasTrivialCopyAssignment()) { 7074 if (Quals == Qualifiers::Const) 7075 return true; 7076 } else if (!Selected) { 7077 return false; 7078 } 7079 // In C++98, we are not supposed to perform overload resolution here, but we 7080 // treat that as a language defect. 7081 goto NeedOverloadResolution; 7082 7083 case Sema::CXXMoveConstructor: 7084 case Sema::CXXMoveAssignment: 7085 NeedOverloadResolution: 7086 Sema::SpecialMemberOverloadResult SMOR = 7087 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7088 7089 // The standard doesn't describe how to behave if the lookup is ambiguous. 7090 // We treat it as not making the member non-trivial, just like the standard 7091 // mandates for the default constructor. This should rarely matter, because 7092 // the member will also be deleted. 7093 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7094 return true; 7095 7096 if (!SMOR.getMethod()) { 7097 assert(SMOR.getKind() == 7098 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7099 return false; 7100 } 7101 7102 // We deliberately don't check if we found a deleted special member. We're 7103 // not supposed to! 7104 if (Selected) 7105 *Selected = SMOR.getMethod(); 7106 return SMOR.getMethod()->isTrivial(); 7107 } 7108 7109 llvm_unreachable("unknown special method kind"); 7110 } 7111 7112 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7113 for (auto *CI : RD->ctors()) 7114 if (!CI->isImplicit()) 7115 return CI; 7116 7117 // Look for constructor templates. 7118 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7119 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7120 if (CXXConstructorDecl *CD = 7121 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7122 return CD; 7123 } 7124 7125 return nullptr; 7126 } 7127 7128 /// The kind of subobject we are checking for triviality. The values of this 7129 /// enumeration are used in diagnostics. 7130 enum TrivialSubobjectKind { 7131 /// The subobject is a base class. 7132 TSK_BaseClass, 7133 /// The subobject is a non-static data member. 7134 TSK_Field, 7135 /// The object is actually the complete object. 7136 TSK_CompleteObject 7137 }; 7138 7139 /// Check whether the special member selected for a given type would be trivial. 7140 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7141 QualType SubType, bool ConstRHS, 7142 Sema::CXXSpecialMember CSM, 7143 TrivialSubobjectKind Kind, 7144 bool Diagnose) { 7145 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7146 if (!SubRD) 7147 return true; 7148 7149 CXXMethodDecl *Selected; 7150 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7151 ConstRHS, Diagnose ? &Selected : nullptr)) 7152 return true; 7153 7154 if (Diagnose) { 7155 if (ConstRHS) 7156 SubType.addConst(); 7157 7158 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7159 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7160 << Kind << SubType.getUnqualifiedType(); 7161 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7162 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7163 } else if (!Selected) 7164 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7165 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7166 else if (Selected->isUserProvided()) { 7167 if (Kind == TSK_CompleteObject) 7168 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7169 << Kind << SubType.getUnqualifiedType() << CSM; 7170 else { 7171 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7172 << Kind << SubType.getUnqualifiedType() << CSM; 7173 S.Diag(Selected->getLocation(), diag::note_declared_at); 7174 } 7175 } else { 7176 if (Kind != TSK_CompleteObject) 7177 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7178 << Kind << SubType.getUnqualifiedType() << CSM; 7179 7180 // Explain why the defaulted or deleted special member isn't trivial. 7181 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 7182 } 7183 } 7184 7185 return false; 7186 } 7187 7188 /// Check whether the members of a class type allow a special member to be 7189 /// trivial. 7190 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7191 Sema::CXXSpecialMember CSM, 7192 bool ConstArg, bool Diagnose) { 7193 for (const auto *FI : RD->fields()) { 7194 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7195 continue; 7196 7197 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7198 7199 // Pretend anonymous struct or union members are members of this class. 7200 if (FI->isAnonymousStructOrUnion()) { 7201 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7202 CSM, ConstArg, Diagnose)) 7203 return false; 7204 continue; 7205 } 7206 7207 // C++11 [class.ctor]p5: 7208 // A default constructor is trivial if [...] 7209 // -- no non-static data member of its class has a 7210 // brace-or-equal-initializer 7211 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7212 if (Diagnose) 7213 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7214 return false; 7215 } 7216 7217 // Objective C ARC 4.3.5: 7218 // [...] nontrivally ownership-qualified types are [...] not trivially 7219 // default constructible, copy constructible, move constructible, copy 7220 // assignable, move assignable, or destructible [...] 7221 if (FieldType.hasNonTrivialObjCLifetime()) { 7222 if (Diagnose) 7223 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7224 << RD << FieldType.getObjCLifetime(); 7225 return false; 7226 } 7227 7228 bool ConstRHS = ConstArg && !FI->isMutable(); 7229 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7230 CSM, TSK_Field, Diagnose)) 7231 return false; 7232 } 7233 7234 return true; 7235 } 7236 7237 /// Diagnose why the specified class does not have a trivial special member of 7238 /// the given kind. 7239 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7240 QualType Ty = Context.getRecordType(RD); 7241 7242 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7243 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7244 TSK_CompleteObject, /*Diagnose*/true); 7245 } 7246 7247 /// Determine whether a defaulted or deleted special member function is trivial, 7248 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7249 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7250 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7251 bool Diagnose) { 7252 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7253 7254 CXXRecordDecl *RD = MD->getParent(); 7255 7256 bool ConstArg = false; 7257 7258 // C++11 [class.copy]p12, p25: [DR1593] 7259 // A [special member] is trivial if [...] its parameter-type-list is 7260 // equivalent to the parameter-type-list of an implicit declaration [...] 7261 switch (CSM) { 7262 case CXXDefaultConstructor: 7263 case CXXDestructor: 7264 // Trivial default constructors and destructors cannot have parameters. 7265 break; 7266 7267 case CXXCopyConstructor: 7268 case CXXCopyAssignment: { 7269 // Trivial copy operations always have const, non-volatile parameter types. 7270 ConstArg = true; 7271 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7272 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7273 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7274 if (Diagnose) 7275 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7276 << Param0->getSourceRange() << Param0->getType() 7277 << Context.getLValueReferenceType( 7278 Context.getRecordType(RD).withConst()); 7279 return false; 7280 } 7281 break; 7282 } 7283 7284 case CXXMoveConstructor: 7285 case CXXMoveAssignment: { 7286 // Trivial move operations always have non-cv-qualified parameters. 7287 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7288 const RValueReferenceType *RT = 7289 Param0->getType()->getAs<RValueReferenceType>(); 7290 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7291 if (Diagnose) 7292 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7293 << Param0->getSourceRange() << Param0->getType() 7294 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7295 return false; 7296 } 7297 break; 7298 } 7299 7300 case CXXInvalid: 7301 llvm_unreachable("not a special member"); 7302 } 7303 7304 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7305 if (Diagnose) 7306 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7307 diag::note_nontrivial_default_arg) 7308 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7309 return false; 7310 } 7311 if (MD->isVariadic()) { 7312 if (Diagnose) 7313 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7314 return false; 7315 } 7316 7317 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7318 // A copy/move [constructor or assignment operator] is trivial if 7319 // -- the [member] selected to copy/move each direct base class subobject 7320 // is trivial 7321 // 7322 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7323 // A [default constructor or destructor] is trivial if 7324 // -- all the direct base classes have trivial [default constructors or 7325 // destructors] 7326 for (const auto &BI : RD->bases()) 7327 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7328 ConstArg, CSM, TSK_BaseClass, Diagnose)) 7329 return false; 7330 7331 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7332 // A copy/move [constructor or assignment operator] for a class X is 7333 // trivial if 7334 // -- for each non-static data member of X that is of class type (or array 7335 // thereof), the constructor selected to copy/move that member is 7336 // trivial 7337 // 7338 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7339 // A [default constructor or destructor] is trivial if 7340 // -- for all of the non-static data members of its class that are of class 7341 // type (or array thereof), each such class has a trivial [default 7342 // constructor or destructor] 7343 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 7344 return false; 7345 7346 // C++11 [class.dtor]p5: 7347 // A destructor is trivial if [...] 7348 // -- the destructor is not virtual 7349 if (CSM == CXXDestructor && MD->isVirtual()) { 7350 if (Diagnose) 7351 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7352 return false; 7353 } 7354 7355 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7356 // A [special member] for class X is trivial if [...] 7357 // -- class X has no virtual functions and no virtual base classes 7358 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7359 if (!Diagnose) 7360 return false; 7361 7362 if (RD->getNumVBases()) { 7363 // Check for virtual bases. We already know that the corresponding 7364 // member in all bases is trivial, so vbases must all be direct. 7365 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7366 assert(BS.isVirtual()); 7367 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7368 return false; 7369 } 7370 7371 // Must have a virtual method. 7372 for (const auto *MI : RD->methods()) { 7373 if (MI->isVirtual()) { 7374 SourceLocation MLoc = MI->getLocStart(); 7375 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7376 return false; 7377 } 7378 } 7379 7380 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7381 } 7382 7383 // Looks like it's trivial! 7384 return true; 7385 } 7386 7387 namespace { 7388 struct FindHiddenVirtualMethod { 7389 Sema *S; 7390 CXXMethodDecl *Method; 7391 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7392 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7393 7394 private: 7395 /// Check whether any most overriden method from MD in Methods 7396 static bool CheckMostOverridenMethods( 7397 const CXXMethodDecl *MD, 7398 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7399 if (MD->size_overridden_methods() == 0) 7400 return Methods.count(MD->getCanonicalDecl()); 7401 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7402 E = MD->end_overridden_methods(); 7403 I != E; ++I) 7404 if (CheckMostOverridenMethods(*I, Methods)) 7405 return true; 7406 return false; 7407 } 7408 7409 public: 7410 /// Member lookup function that determines whether a given C++ 7411 /// method overloads virtual methods in a base class without overriding any, 7412 /// to be used with CXXRecordDecl::lookupInBases(). 7413 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7414 RecordDecl *BaseRecord = 7415 Specifier->getType()->getAs<RecordType>()->getDecl(); 7416 7417 DeclarationName Name = Method->getDeclName(); 7418 assert(Name.getNameKind() == DeclarationName::Identifier); 7419 7420 bool foundSameNameMethod = false; 7421 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7422 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7423 Path.Decls = Path.Decls.slice(1)) { 7424 NamedDecl *D = Path.Decls.front(); 7425 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7426 MD = MD->getCanonicalDecl(); 7427 foundSameNameMethod = true; 7428 // Interested only in hidden virtual methods. 7429 if (!MD->isVirtual()) 7430 continue; 7431 // If the method we are checking overrides a method from its base 7432 // don't warn about the other overloaded methods. Clang deviates from 7433 // GCC by only diagnosing overloads of inherited virtual functions that 7434 // do not override any other virtual functions in the base. GCC's 7435 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7436 // function from a base class. These cases may be better served by a 7437 // warning (not specific to virtual functions) on call sites when the 7438 // call would select a different function from the base class, were it 7439 // visible. 7440 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7441 if (!S->IsOverload(Method, MD, false)) 7442 return true; 7443 // Collect the overload only if its hidden. 7444 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7445 overloadedMethods.push_back(MD); 7446 } 7447 } 7448 7449 if (foundSameNameMethod) 7450 OverloadedMethods.append(overloadedMethods.begin(), 7451 overloadedMethods.end()); 7452 return foundSameNameMethod; 7453 } 7454 }; 7455 } // end anonymous namespace 7456 7457 /// \brief Add the most overriden methods from MD to Methods 7458 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7459 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7460 if (MD->size_overridden_methods() == 0) 7461 Methods.insert(MD->getCanonicalDecl()); 7462 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7463 E = MD->end_overridden_methods(); 7464 I != E; ++I) 7465 AddMostOverridenMethods(*I, Methods); 7466 } 7467 7468 /// \brief Check if a method overloads virtual methods in a base class without 7469 /// overriding any. 7470 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7471 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7472 if (!MD->getDeclName().isIdentifier()) 7473 return; 7474 7475 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7476 /*bool RecordPaths=*/false, 7477 /*bool DetectVirtual=*/false); 7478 FindHiddenVirtualMethod FHVM; 7479 FHVM.Method = MD; 7480 FHVM.S = this; 7481 7482 // Keep the base methods that were overriden or introduced in the subclass 7483 // by 'using' in a set. A base method not in this set is hidden. 7484 CXXRecordDecl *DC = MD->getParent(); 7485 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7486 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7487 NamedDecl *ND = *I; 7488 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7489 ND = shad->getTargetDecl(); 7490 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7491 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7492 } 7493 7494 if (DC->lookupInBases(FHVM, Paths)) 7495 OverloadedMethods = FHVM.OverloadedMethods; 7496 } 7497 7498 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7499 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7500 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7501 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7502 PartialDiagnostic PD = PDiag( 7503 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7504 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7505 Diag(overloadedMD->getLocation(), PD); 7506 } 7507 } 7508 7509 /// \brief Diagnose methods which overload virtual methods in a base class 7510 /// without overriding any. 7511 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7512 if (MD->isInvalidDecl()) 7513 return; 7514 7515 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7516 return; 7517 7518 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7519 FindHiddenVirtualMethods(MD, OverloadedMethods); 7520 if (!OverloadedMethods.empty()) { 7521 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7522 << MD << (OverloadedMethods.size() > 1); 7523 7524 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7525 } 7526 } 7527 7528 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7529 Decl *TagDecl, 7530 SourceLocation LBrac, 7531 SourceLocation RBrac, 7532 AttributeList *AttrList) { 7533 if (!TagDecl) 7534 return; 7535 7536 AdjustDeclIfTemplate(TagDecl); 7537 7538 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7539 if (l->getKind() != AttributeList::AT_Visibility) 7540 continue; 7541 l->setInvalid(); 7542 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7543 l->getName(); 7544 } 7545 7546 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7547 // strict aliasing violation! 7548 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7549 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7550 7551 CheckCompletedCXXClass(dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7552 } 7553 7554 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7555 /// special functions, such as the default constructor, copy 7556 /// constructor, or destructor, to the given C++ class (C++ 7557 /// [special]p1). This routine can only be executed just before the 7558 /// definition of the class is complete. 7559 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7560 if (ClassDecl->needsImplicitDefaultConstructor()) { 7561 ++ASTContext::NumImplicitDefaultConstructors; 7562 7563 if (ClassDecl->hasInheritedConstructor()) 7564 DeclareImplicitDefaultConstructor(ClassDecl); 7565 } 7566 7567 if (ClassDecl->needsImplicitCopyConstructor()) { 7568 ++ASTContext::NumImplicitCopyConstructors; 7569 7570 // If the properties or semantics of the copy constructor couldn't be 7571 // determined while the class was being declared, force a declaration 7572 // of it now. 7573 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7574 ClassDecl->hasInheritedConstructor()) 7575 DeclareImplicitCopyConstructor(ClassDecl); 7576 // For the MS ABI we need to know whether the copy ctor is deleted. A 7577 // prerequisite for deleting the implicit copy ctor is that the class has a 7578 // move ctor or move assignment that is either user-declared or whose 7579 // semantics are inherited from a subobject. FIXME: We should provide a more 7580 // direct way for CodeGen to ask whether the constructor was deleted. 7581 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7582 (ClassDecl->hasUserDeclaredMoveConstructor() || 7583 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7584 ClassDecl->hasUserDeclaredMoveAssignment() || 7585 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7586 DeclareImplicitCopyConstructor(ClassDecl); 7587 } 7588 7589 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7590 ++ASTContext::NumImplicitMoveConstructors; 7591 7592 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7593 ClassDecl->hasInheritedConstructor()) 7594 DeclareImplicitMoveConstructor(ClassDecl); 7595 } 7596 7597 if (ClassDecl->needsImplicitCopyAssignment()) { 7598 ++ASTContext::NumImplicitCopyAssignmentOperators; 7599 7600 // If we have a dynamic class, then the copy assignment operator may be 7601 // virtual, so we have to declare it immediately. This ensures that, e.g., 7602 // it shows up in the right place in the vtable and that we diagnose 7603 // problems with the implicit exception specification. 7604 if (ClassDecl->isDynamicClass() || 7605 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7606 ClassDecl->hasInheritedAssignment()) 7607 DeclareImplicitCopyAssignment(ClassDecl); 7608 } 7609 7610 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7611 ++ASTContext::NumImplicitMoveAssignmentOperators; 7612 7613 // Likewise for the move assignment operator. 7614 if (ClassDecl->isDynamicClass() || 7615 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7616 ClassDecl->hasInheritedAssignment()) 7617 DeclareImplicitMoveAssignment(ClassDecl); 7618 } 7619 7620 if (ClassDecl->needsImplicitDestructor()) { 7621 ++ASTContext::NumImplicitDestructors; 7622 7623 // If we have a dynamic class, then the destructor may be virtual, so we 7624 // have to declare the destructor immediately. This ensures that, e.g., it 7625 // shows up in the right place in the vtable and that we diagnose problems 7626 // with the implicit exception specification. 7627 if (ClassDecl->isDynamicClass() || 7628 ClassDecl->needsOverloadResolutionForDestructor()) 7629 DeclareImplicitDestructor(ClassDecl); 7630 } 7631 } 7632 7633 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7634 if (!D) 7635 return 0; 7636 7637 // The order of template parameters is not important here. All names 7638 // get added to the same scope. 7639 SmallVector<TemplateParameterList *, 4> ParameterLists; 7640 7641 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7642 D = TD->getTemplatedDecl(); 7643 7644 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7645 ParameterLists.push_back(PSD->getTemplateParameters()); 7646 7647 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7648 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7649 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7650 7651 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7652 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7653 ParameterLists.push_back(FTD->getTemplateParameters()); 7654 } 7655 } 7656 7657 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7658 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7659 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7660 7661 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7662 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7663 ParameterLists.push_back(CTD->getTemplateParameters()); 7664 } 7665 } 7666 7667 unsigned Count = 0; 7668 for (TemplateParameterList *Params : ParameterLists) { 7669 if (Params->size() > 0) 7670 // Ignore explicit specializations; they don't contribute to the template 7671 // depth. 7672 ++Count; 7673 for (NamedDecl *Param : *Params) { 7674 if (Param->getDeclName()) { 7675 S->AddDecl(Param); 7676 IdResolver.AddDecl(Param); 7677 } 7678 } 7679 } 7680 7681 return Count; 7682 } 7683 7684 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7685 if (!RecordD) return; 7686 AdjustDeclIfTemplate(RecordD); 7687 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7688 PushDeclContext(S, Record); 7689 } 7690 7691 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7692 if (!RecordD) return; 7693 PopDeclContext(); 7694 } 7695 7696 /// This is used to implement the constant expression evaluation part of the 7697 /// attribute enable_if extension. There is nothing in standard C++ which would 7698 /// require reentering parameters. 7699 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7700 if (!Param) 7701 return; 7702 7703 S->AddDecl(Param); 7704 if (Param->getDeclName()) 7705 IdResolver.AddDecl(Param); 7706 } 7707 7708 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7709 /// parsing a top-level (non-nested) C++ class, and we are now 7710 /// parsing those parts of the given Method declaration that could 7711 /// not be parsed earlier (C++ [class.mem]p2), such as default 7712 /// arguments. This action should enter the scope of the given 7713 /// Method declaration as if we had just parsed the qualified method 7714 /// name. However, it should not bring the parameters into scope; 7715 /// that will be performed by ActOnDelayedCXXMethodParameter. 7716 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7717 } 7718 7719 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7720 /// C++ method declaration. We're (re-)introducing the given 7721 /// function parameter into scope for use in parsing later parts of 7722 /// the method declaration. For example, we could see an 7723 /// ActOnParamDefaultArgument event for this parameter. 7724 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7725 if (!ParamD) 7726 return; 7727 7728 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7729 7730 // If this parameter has an unparsed default argument, clear it out 7731 // to make way for the parsed default argument. 7732 if (Param->hasUnparsedDefaultArg()) 7733 Param->setDefaultArg(nullptr); 7734 7735 S->AddDecl(Param); 7736 if (Param->getDeclName()) 7737 IdResolver.AddDecl(Param); 7738 } 7739 7740 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7741 /// processing the delayed method declaration for Method. The method 7742 /// declaration is now considered finished. There may be a separate 7743 /// ActOnStartOfFunctionDef action later (not necessarily 7744 /// immediately!) for this method, if it was also defined inside the 7745 /// class body. 7746 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7747 if (!MethodD) 7748 return; 7749 7750 AdjustDeclIfTemplate(MethodD); 7751 7752 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7753 7754 // Now that we have our default arguments, check the constructor 7755 // again. It could produce additional diagnostics or affect whether 7756 // the class has implicitly-declared destructors, among other 7757 // things. 7758 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7759 CheckConstructor(Constructor); 7760 7761 // Check the default arguments, which we may have added. 7762 if (!Method->isInvalidDecl()) 7763 CheckCXXDefaultArguments(Method); 7764 } 7765 7766 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7767 /// the well-formedness of the constructor declarator @p D with type @p 7768 /// R. If there are any errors in the declarator, this routine will 7769 /// emit diagnostics and set the invalid bit to true. In any case, the type 7770 /// will be updated to reflect a well-formed type for the constructor and 7771 /// returned. 7772 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7773 StorageClass &SC) { 7774 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7775 7776 // C++ [class.ctor]p3: 7777 // A constructor shall not be virtual (10.3) or static (9.4). A 7778 // constructor can be invoked for a const, volatile or const 7779 // volatile object. A constructor shall not be declared const, 7780 // volatile, or const volatile (9.3.2). 7781 if (isVirtual) { 7782 if (!D.isInvalidType()) 7783 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7784 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7785 << SourceRange(D.getIdentifierLoc()); 7786 D.setInvalidType(); 7787 } 7788 if (SC == SC_Static) { 7789 if (!D.isInvalidType()) 7790 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7791 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7792 << SourceRange(D.getIdentifierLoc()); 7793 D.setInvalidType(); 7794 SC = SC_None; 7795 } 7796 7797 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7798 diagnoseIgnoredQualifiers( 7799 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7800 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7801 D.getDeclSpec().getRestrictSpecLoc(), 7802 D.getDeclSpec().getAtomicSpecLoc()); 7803 D.setInvalidType(); 7804 } 7805 7806 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7807 if (FTI.TypeQuals != 0) { 7808 if (FTI.TypeQuals & Qualifiers::Const) 7809 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7810 << "const" << SourceRange(D.getIdentifierLoc()); 7811 if (FTI.TypeQuals & Qualifiers::Volatile) 7812 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7813 << "volatile" << SourceRange(D.getIdentifierLoc()); 7814 if (FTI.TypeQuals & Qualifiers::Restrict) 7815 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7816 << "restrict" << SourceRange(D.getIdentifierLoc()); 7817 D.setInvalidType(); 7818 } 7819 7820 // C++0x [class.ctor]p4: 7821 // A constructor shall not be declared with a ref-qualifier. 7822 if (FTI.hasRefQualifier()) { 7823 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7824 << FTI.RefQualifierIsLValueRef 7825 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7826 D.setInvalidType(); 7827 } 7828 7829 // Rebuild the function type "R" without any type qualifiers (in 7830 // case any of the errors above fired) and with "void" as the 7831 // return type, since constructors don't have return types. 7832 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7833 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7834 return R; 7835 7836 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7837 EPI.TypeQuals = 0; 7838 EPI.RefQualifier = RQ_None; 7839 7840 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7841 } 7842 7843 /// CheckConstructor - Checks a fully-formed constructor for 7844 /// well-formedness, issuing any diagnostics required. Returns true if 7845 /// the constructor declarator is invalid. 7846 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7847 CXXRecordDecl *ClassDecl 7848 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7849 if (!ClassDecl) 7850 return Constructor->setInvalidDecl(); 7851 7852 // C++ [class.copy]p3: 7853 // A declaration of a constructor for a class X is ill-formed if 7854 // its first parameter is of type (optionally cv-qualified) X and 7855 // either there are no other parameters or else all other 7856 // parameters have default arguments. 7857 if (!Constructor->isInvalidDecl() && 7858 ((Constructor->getNumParams() == 1) || 7859 (Constructor->getNumParams() > 1 && 7860 Constructor->getParamDecl(1)->hasDefaultArg())) && 7861 Constructor->getTemplateSpecializationKind() 7862 != TSK_ImplicitInstantiation) { 7863 QualType ParamType = Constructor->getParamDecl(0)->getType(); 7864 QualType ClassTy = Context.getTagDeclType(ClassDecl); 7865 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 7866 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 7867 const char *ConstRef 7868 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 7869 : " const &"; 7870 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 7871 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 7872 7873 // FIXME: Rather that making the constructor invalid, we should endeavor 7874 // to fix the type. 7875 Constructor->setInvalidDecl(); 7876 } 7877 } 7878 } 7879 7880 /// CheckDestructor - Checks a fully-formed destructor definition for 7881 /// well-formedness, issuing any diagnostics required. Returns true 7882 /// on error. 7883 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 7884 CXXRecordDecl *RD = Destructor->getParent(); 7885 7886 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 7887 SourceLocation Loc; 7888 7889 if (!Destructor->isImplicit()) 7890 Loc = Destructor->getLocation(); 7891 else 7892 Loc = RD->getLocation(); 7893 7894 // If we have a virtual destructor, look up the deallocation function 7895 if (FunctionDecl *OperatorDelete = 7896 FindDeallocationFunctionForDestructor(Loc, RD)) { 7897 MarkFunctionReferenced(Loc, OperatorDelete); 7898 Destructor->setOperatorDelete(OperatorDelete); 7899 } 7900 } 7901 7902 return false; 7903 } 7904 7905 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 7906 /// the well-formednes of the destructor declarator @p D with type @p 7907 /// R. If there are any errors in the declarator, this routine will 7908 /// emit diagnostics and set the declarator to invalid. Even if this happens, 7909 /// will be updated to reflect a well-formed type for the destructor and 7910 /// returned. 7911 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 7912 StorageClass& SC) { 7913 // C++ [class.dtor]p1: 7914 // [...] A typedef-name that names a class is a class-name 7915 // (7.1.3); however, a typedef-name that names a class shall not 7916 // be used as the identifier in the declarator for a destructor 7917 // declaration. 7918 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 7919 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 7920 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7921 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 7922 else if (const TemplateSpecializationType *TST = 7923 DeclaratorType->getAs<TemplateSpecializationType>()) 7924 if (TST->isTypeAlias()) 7925 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7926 << DeclaratorType << 1; 7927 7928 // C++ [class.dtor]p2: 7929 // A destructor is used to destroy objects of its class type. A 7930 // destructor takes no parameters, and no return type can be 7931 // specified for it (not even void). The address of a destructor 7932 // shall not be taken. A destructor shall not be static. A 7933 // destructor can be invoked for a const, volatile or const 7934 // volatile object. A destructor shall not be declared const, 7935 // volatile or const volatile (9.3.2). 7936 if (SC == SC_Static) { 7937 if (!D.isInvalidType()) 7938 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 7939 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7940 << SourceRange(D.getIdentifierLoc()) 7941 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7942 7943 SC = SC_None; 7944 } 7945 if (!D.isInvalidType()) { 7946 // Destructors don't have return types, but the parser will 7947 // happily parse something like: 7948 // 7949 // class X { 7950 // float ~X(); 7951 // }; 7952 // 7953 // The return type will be eliminated later. 7954 if (D.getDeclSpec().hasTypeSpecifier()) 7955 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 7956 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7957 << SourceRange(D.getIdentifierLoc()); 7958 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7959 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 7960 SourceLocation(), 7961 D.getDeclSpec().getConstSpecLoc(), 7962 D.getDeclSpec().getVolatileSpecLoc(), 7963 D.getDeclSpec().getRestrictSpecLoc(), 7964 D.getDeclSpec().getAtomicSpecLoc()); 7965 D.setInvalidType(); 7966 } 7967 } 7968 7969 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7970 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 7971 if (FTI.TypeQuals & Qualifiers::Const) 7972 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7973 << "const" << SourceRange(D.getIdentifierLoc()); 7974 if (FTI.TypeQuals & Qualifiers::Volatile) 7975 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7976 << "volatile" << SourceRange(D.getIdentifierLoc()); 7977 if (FTI.TypeQuals & Qualifiers::Restrict) 7978 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7979 << "restrict" << SourceRange(D.getIdentifierLoc()); 7980 D.setInvalidType(); 7981 } 7982 7983 // C++0x [class.dtor]p2: 7984 // A destructor shall not be declared with a ref-qualifier. 7985 if (FTI.hasRefQualifier()) { 7986 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 7987 << FTI.RefQualifierIsLValueRef 7988 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7989 D.setInvalidType(); 7990 } 7991 7992 // Make sure we don't have any parameters. 7993 if (FTIHasNonVoidParameters(FTI)) { 7994 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 7995 7996 // Delete the parameters. 7997 FTI.freeParams(); 7998 D.setInvalidType(); 7999 } 8000 8001 // Make sure the destructor isn't variadic. 8002 if (FTI.isVariadic) { 8003 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8004 D.setInvalidType(); 8005 } 8006 8007 // Rebuild the function type "R" without any type qualifiers or 8008 // parameters (in case any of the errors above fired) and with 8009 // "void" as the return type, since destructors don't have return 8010 // types. 8011 if (!D.isInvalidType()) 8012 return R; 8013 8014 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8015 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8016 EPI.Variadic = false; 8017 EPI.TypeQuals = 0; 8018 EPI.RefQualifier = RQ_None; 8019 return Context.getFunctionType(Context.VoidTy, None, EPI); 8020 } 8021 8022 static void extendLeft(SourceRange &R, SourceRange Before) { 8023 if (Before.isInvalid()) 8024 return; 8025 R.setBegin(Before.getBegin()); 8026 if (R.getEnd().isInvalid()) 8027 R.setEnd(Before.getEnd()); 8028 } 8029 8030 static void extendRight(SourceRange &R, SourceRange After) { 8031 if (After.isInvalid()) 8032 return; 8033 if (R.getBegin().isInvalid()) 8034 R.setBegin(After.getBegin()); 8035 R.setEnd(After.getEnd()); 8036 } 8037 8038 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8039 /// well-formednes of the conversion function declarator @p D with 8040 /// type @p R. If there are any errors in the declarator, this routine 8041 /// will emit diagnostics and return true. Otherwise, it will return 8042 /// false. Either way, the type @p R will be updated to reflect a 8043 /// well-formed type for the conversion operator. 8044 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8045 StorageClass& SC) { 8046 // C++ [class.conv.fct]p1: 8047 // Neither parameter types nor return type can be specified. The 8048 // type of a conversion function (8.3.5) is "function taking no 8049 // parameter returning conversion-type-id." 8050 if (SC == SC_Static) { 8051 if (!D.isInvalidType()) 8052 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8053 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8054 << D.getName().getSourceRange(); 8055 D.setInvalidType(); 8056 SC = SC_None; 8057 } 8058 8059 TypeSourceInfo *ConvTSI = nullptr; 8060 QualType ConvType = 8061 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8062 8063 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 8064 // Conversion functions don't have return types, but the parser will 8065 // happily parse something like: 8066 // 8067 // class X { 8068 // float operator bool(); 8069 // }; 8070 // 8071 // The return type will be changed later anyway. 8072 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8073 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8074 << SourceRange(D.getIdentifierLoc()); 8075 D.setInvalidType(); 8076 } 8077 8078 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8079 8080 // Make sure we don't have any parameters. 8081 if (Proto->getNumParams() > 0) { 8082 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8083 8084 // Delete the parameters. 8085 D.getFunctionTypeInfo().freeParams(); 8086 D.setInvalidType(); 8087 } else if (Proto->isVariadic()) { 8088 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8089 D.setInvalidType(); 8090 } 8091 8092 // Diagnose "&operator bool()" and other such nonsense. This 8093 // is actually a gcc extension which we don't support. 8094 if (Proto->getReturnType() != ConvType) { 8095 bool NeedsTypedef = false; 8096 SourceRange Before, After; 8097 8098 // Walk the chunks and extract information on them for our diagnostic. 8099 bool PastFunctionChunk = false; 8100 for (auto &Chunk : D.type_objects()) { 8101 switch (Chunk.Kind) { 8102 case DeclaratorChunk::Function: 8103 if (!PastFunctionChunk) { 8104 if (Chunk.Fun.HasTrailingReturnType) { 8105 TypeSourceInfo *TRT = nullptr; 8106 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8107 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8108 } 8109 PastFunctionChunk = true; 8110 break; 8111 } 8112 // Fall through. 8113 case DeclaratorChunk::Array: 8114 NeedsTypedef = true; 8115 extendRight(After, Chunk.getSourceRange()); 8116 break; 8117 8118 case DeclaratorChunk::Pointer: 8119 case DeclaratorChunk::BlockPointer: 8120 case DeclaratorChunk::Reference: 8121 case DeclaratorChunk::MemberPointer: 8122 case DeclaratorChunk::Pipe: 8123 extendLeft(Before, Chunk.getSourceRange()); 8124 break; 8125 8126 case DeclaratorChunk::Paren: 8127 extendLeft(Before, Chunk.Loc); 8128 extendRight(After, Chunk.EndLoc); 8129 break; 8130 } 8131 } 8132 8133 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8134 After.isValid() ? After.getBegin() : 8135 D.getIdentifierLoc(); 8136 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8137 DB << Before << After; 8138 8139 if (!NeedsTypedef) { 8140 DB << /*don't need a typedef*/0; 8141 8142 // If we can provide a correct fix-it hint, do so. 8143 if (After.isInvalid() && ConvTSI) { 8144 SourceLocation InsertLoc = 8145 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8146 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8147 << FixItHint::CreateInsertionFromRange( 8148 InsertLoc, CharSourceRange::getTokenRange(Before)) 8149 << FixItHint::CreateRemoval(Before); 8150 } 8151 } else if (!Proto->getReturnType()->isDependentType()) { 8152 DB << /*typedef*/1 << Proto->getReturnType(); 8153 } else if (getLangOpts().CPlusPlus11) { 8154 DB << /*alias template*/2 << Proto->getReturnType(); 8155 } else { 8156 DB << /*might not be fixable*/3; 8157 } 8158 8159 // Recover by incorporating the other type chunks into the result type. 8160 // Note, this does *not* change the name of the function. This is compatible 8161 // with the GCC extension: 8162 // struct S { &operator int(); } s; 8163 // int &r = s.operator int(); // ok in GCC 8164 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8165 ConvType = Proto->getReturnType(); 8166 } 8167 8168 // C++ [class.conv.fct]p4: 8169 // The conversion-type-id shall not represent a function type nor 8170 // an array type. 8171 if (ConvType->isArrayType()) { 8172 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8173 ConvType = Context.getPointerType(ConvType); 8174 D.setInvalidType(); 8175 } else if (ConvType->isFunctionType()) { 8176 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8177 ConvType = Context.getPointerType(ConvType); 8178 D.setInvalidType(); 8179 } 8180 8181 // Rebuild the function type "R" without any parameters (in case any 8182 // of the errors above fired) and with the conversion type as the 8183 // return type. 8184 if (D.isInvalidType()) 8185 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8186 8187 // C++0x explicit conversion operators. 8188 if (D.getDeclSpec().isExplicitSpecified()) 8189 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8190 getLangOpts().CPlusPlus11 ? 8191 diag::warn_cxx98_compat_explicit_conversion_functions : 8192 diag::ext_explicit_conversion_functions) 8193 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 8194 } 8195 8196 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8197 /// the declaration of the given C++ conversion function. This routine 8198 /// is responsible for recording the conversion function in the C++ 8199 /// class, if possible. 8200 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8201 assert(Conversion && "Expected to receive a conversion function declaration"); 8202 8203 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8204 8205 // Make sure we aren't redeclaring the conversion function. 8206 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8207 8208 // C++ [class.conv.fct]p1: 8209 // [...] A conversion function is never used to convert a 8210 // (possibly cv-qualified) object to the (possibly cv-qualified) 8211 // same object type (or a reference to it), to a (possibly 8212 // cv-qualified) base class of that type (or a reference to it), 8213 // or to (possibly cv-qualified) void. 8214 // FIXME: Suppress this warning if the conversion function ends up being a 8215 // virtual function that overrides a virtual function in a base class. 8216 QualType ClassType 8217 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8218 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8219 ConvType = ConvTypeRef->getPointeeType(); 8220 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8221 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8222 /* Suppress diagnostics for instantiations. */; 8223 else if (ConvType->isRecordType()) { 8224 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8225 if (ConvType == ClassType) 8226 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8227 << ClassType; 8228 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8229 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8230 << ClassType << ConvType; 8231 } else if (ConvType->isVoidType()) { 8232 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8233 << ClassType << ConvType; 8234 } 8235 8236 if (FunctionTemplateDecl *ConversionTemplate 8237 = Conversion->getDescribedFunctionTemplate()) 8238 return ConversionTemplate; 8239 8240 return Conversion; 8241 } 8242 8243 namespace { 8244 /// Utility class to accumulate and print a diagnostic listing the invalid 8245 /// specifier(s) on a declaration. 8246 struct BadSpecifierDiagnoser { 8247 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8248 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8249 ~BadSpecifierDiagnoser() { 8250 Diagnostic << Specifiers; 8251 } 8252 8253 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8254 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8255 } 8256 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8257 return check(SpecLoc, 8258 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8259 } 8260 void check(SourceLocation SpecLoc, const char *Spec) { 8261 if (SpecLoc.isInvalid()) return; 8262 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8263 if (!Specifiers.empty()) Specifiers += " "; 8264 Specifiers += Spec; 8265 } 8266 8267 Sema &S; 8268 Sema::SemaDiagnosticBuilder Diagnostic; 8269 std::string Specifiers; 8270 }; 8271 } 8272 8273 /// Check the validity of a declarator that we parsed for a deduction-guide. 8274 /// These aren't actually declarators in the grammar, so we need to check that 8275 /// the user didn't specify any pieces that are not part of the deduction-guide 8276 /// grammar. 8277 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8278 StorageClass &SC) { 8279 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8280 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8281 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8282 8283 // C++ [temp.deduct.guide]p3: 8284 // A deduction-gide shall be declared in the same scope as the 8285 // corresponding class template. 8286 if (!CurContext->getRedeclContext()->Equals( 8287 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8288 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8289 << GuidedTemplateDecl; 8290 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8291 } 8292 8293 auto &DS = D.getMutableDeclSpec(); 8294 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8295 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8296 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8297 DS.isNoreturnSpecified() || DS.isConstexprSpecified() || 8298 DS.isConceptSpecified()) { 8299 BadSpecifierDiagnoser Diagnoser( 8300 *this, D.getIdentifierLoc(), 8301 diag::err_deduction_guide_invalid_specifier); 8302 8303 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8304 DS.ClearStorageClassSpecs(); 8305 SC = SC_None; 8306 8307 // 'explicit' is permitted. 8308 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8309 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8310 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8311 Diagnoser.check(DS.getConceptSpecLoc(), "concept"); 8312 DS.ClearConstexprSpec(); 8313 DS.ClearConceptSpec(); 8314 8315 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8316 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8317 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8318 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8319 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8320 DS.ClearTypeQualifiers(); 8321 8322 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8323 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8324 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8325 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8326 DS.ClearTypeSpecType(); 8327 } 8328 8329 if (D.isInvalidType()) 8330 return; 8331 8332 // Check the declarator is simple enough. 8333 bool FoundFunction = false; 8334 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8335 if (Chunk.Kind == DeclaratorChunk::Paren) 8336 continue; 8337 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8338 Diag(D.getDeclSpec().getLocStart(), 8339 diag::err_deduction_guide_with_complex_decl) 8340 << D.getSourceRange(); 8341 break; 8342 } 8343 if (!Chunk.Fun.hasTrailingReturnType()) { 8344 Diag(D.getName().getLocStart(), 8345 diag::err_deduction_guide_no_trailing_return_type); 8346 break; 8347 } 8348 8349 // Check that the return type is written as a specialization of 8350 // the template specified as the deduction-guide's name. 8351 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8352 TypeSourceInfo *TSI = nullptr; 8353 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8354 assert(TSI && "deduction guide has valid type but invalid return type?"); 8355 bool AcceptableReturnType = false; 8356 bool MightInstantiateToSpecialization = false; 8357 if (auto RetTST = 8358 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8359 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8360 bool TemplateMatches = 8361 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8362 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8363 AcceptableReturnType = true; 8364 else { 8365 // This could still instantiate to the right type, unless we know it 8366 // names the wrong class template. 8367 auto *TD = SpecifiedName.getAsTemplateDecl(); 8368 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8369 !TemplateMatches); 8370 } 8371 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8372 MightInstantiateToSpecialization = true; 8373 } 8374 8375 if (!AcceptableReturnType) { 8376 Diag(TSI->getTypeLoc().getLocStart(), 8377 diag::err_deduction_guide_bad_trailing_return_type) 8378 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8379 << TSI->getTypeLoc().getSourceRange(); 8380 } 8381 8382 // Keep going to check that we don't have any inner declarator pieces (we 8383 // could still have a function returning a pointer to a function). 8384 FoundFunction = true; 8385 } 8386 8387 if (D.isFunctionDefinition()) 8388 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8389 } 8390 8391 //===----------------------------------------------------------------------===// 8392 // Namespace Handling 8393 //===----------------------------------------------------------------------===// 8394 8395 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8396 /// reopened. 8397 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8398 SourceLocation Loc, 8399 IdentifierInfo *II, bool *IsInline, 8400 NamespaceDecl *PrevNS) { 8401 assert(*IsInline != PrevNS->isInline()); 8402 8403 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8404 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8405 // inline namespaces, with the intention of bringing names into namespace std. 8406 // 8407 // We support this just well enough to get that case working; this is not 8408 // sufficient to support reopening namespaces as inline in general. 8409 if (*IsInline && II && II->getName().startswith("__atomic") && 8410 S.getSourceManager().isInSystemHeader(Loc)) { 8411 // Mark all prior declarations of the namespace as inline. 8412 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8413 NS = NS->getPreviousDecl()) 8414 NS->setInline(*IsInline); 8415 // Patch up the lookup table for the containing namespace. This isn't really 8416 // correct, but it's good enough for this particular case. 8417 for (auto *I : PrevNS->decls()) 8418 if (auto *ND = dyn_cast<NamedDecl>(I)) 8419 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8420 return; 8421 } 8422 8423 if (PrevNS->isInline()) 8424 // The user probably just forgot the 'inline', so suggest that it 8425 // be added back. 8426 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8427 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8428 else 8429 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8430 8431 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8432 *IsInline = PrevNS->isInline(); 8433 } 8434 8435 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8436 /// definition. 8437 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8438 SourceLocation InlineLoc, 8439 SourceLocation NamespaceLoc, 8440 SourceLocation IdentLoc, 8441 IdentifierInfo *II, 8442 SourceLocation LBrace, 8443 AttributeList *AttrList, 8444 UsingDirectiveDecl *&UD) { 8445 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8446 // For anonymous namespace, take the location of the left brace. 8447 SourceLocation Loc = II ? IdentLoc : LBrace; 8448 bool IsInline = InlineLoc.isValid(); 8449 bool IsInvalid = false; 8450 bool IsStd = false; 8451 bool AddToKnown = false; 8452 Scope *DeclRegionScope = NamespcScope->getParent(); 8453 8454 NamespaceDecl *PrevNS = nullptr; 8455 if (II) { 8456 // C++ [namespace.def]p2: 8457 // The identifier in an original-namespace-definition shall not 8458 // have been previously defined in the declarative region in 8459 // which the original-namespace-definition appears. The 8460 // identifier in an original-namespace-definition is the name of 8461 // the namespace. Subsequently in that declarative region, it is 8462 // treated as an original-namespace-name. 8463 // 8464 // Since namespace names are unique in their scope, and we don't 8465 // look through using directives, just look for any ordinary names 8466 // as if by qualified name lookup. 8467 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration); 8468 LookupQualifiedName(R, CurContext->getRedeclContext()); 8469 NamedDecl *PrevDecl = 8470 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8471 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8472 8473 if (PrevNS) { 8474 // This is an extended namespace definition. 8475 if (IsInline != PrevNS->isInline()) 8476 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8477 &IsInline, PrevNS); 8478 } else if (PrevDecl) { 8479 // This is an invalid name redefinition. 8480 Diag(Loc, diag::err_redefinition_different_kind) 8481 << II; 8482 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8483 IsInvalid = true; 8484 // Continue on to push Namespc as current DeclContext and return it. 8485 } else if (II->isStr("std") && 8486 CurContext->getRedeclContext()->isTranslationUnit()) { 8487 // This is the first "real" definition of the namespace "std", so update 8488 // our cache of the "std" namespace to point at this definition. 8489 PrevNS = getStdNamespace(); 8490 IsStd = true; 8491 AddToKnown = !IsInline; 8492 } else { 8493 // We've seen this namespace for the first time. 8494 AddToKnown = !IsInline; 8495 } 8496 } else { 8497 // Anonymous namespaces. 8498 8499 // Determine whether the parent already has an anonymous namespace. 8500 DeclContext *Parent = CurContext->getRedeclContext(); 8501 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8502 PrevNS = TU->getAnonymousNamespace(); 8503 } else { 8504 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8505 PrevNS = ND->getAnonymousNamespace(); 8506 } 8507 8508 if (PrevNS && IsInline != PrevNS->isInline()) 8509 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8510 &IsInline, PrevNS); 8511 } 8512 8513 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8514 StartLoc, Loc, II, PrevNS); 8515 if (IsInvalid) 8516 Namespc->setInvalidDecl(); 8517 8518 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8519 AddPragmaAttributes(DeclRegionScope, Namespc); 8520 8521 // FIXME: Should we be merging attributes? 8522 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8523 PushNamespaceVisibilityAttr(Attr, Loc); 8524 8525 if (IsStd) 8526 StdNamespace = Namespc; 8527 if (AddToKnown) 8528 KnownNamespaces[Namespc] = false; 8529 8530 if (II) { 8531 PushOnScopeChains(Namespc, DeclRegionScope); 8532 } else { 8533 // Link the anonymous namespace into its parent. 8534 DeclContext *Parent = CurContext->getRedeclContext(); 8535 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8536 TU->setAnonymousNamespace(Namespc); 8537 } else { 8538 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8539 } 8540 8541 CurContext->addDecl(Namespc); 8542 8543 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8544 // behaves as if it were replaced by 8545 // namespace unique { /* empty body */ } 8546 // using namespace unique; 8547 // namespace unique { namespace-body } 8548 // where all occurrences of 'unique' in a translation unit are 8549 // replaced by the same identifier and this identifier differs 8550 // from all other identifiers in the entire program. 8551 8552 // We just create the namespace with an empty name and then add an 8553 // implicit using declaration, just like the standard suggests. 8554 // 8555 // CodeGen enforces the "universally unique" aspect by giving all 8556 // declarations semantically contained within an anonymous 8557 // namespace internal linkage. 8558 8559 if (!PrevNS) { 8560 UD = UsingDirectiveDecl::Create(Context, Parent, 8561 /* 'using' */ LBrace, 8562 /* 'namespace' */ SourceLocation(), 8563 /* qualifier */ NestedNameSpecifierLoc(), 8564 /* identifier */ SourceLocation(), 8565 Namespc, 8566 /* Ancestor */ Parent); 8567 UD->setImplicit(); 8568 Parent->addDecl(UD); 8569 } 8570 } 8571 8572 ActOnDocumentableDecl(Namespc); 8573 8574 // Although we could have an invalid decl (i.e. the namespace name is a 8575 // redefinition), push it as current DeclContext and try to continue parsing. 8576 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8577 // for the namespace has the declarations that showed up in that particular 8578 // namespace definition. 8579 PushDeclContext(NamespcScope, Namespc); 8580 return Namespc; 8581 } 8582 8583 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8584 /// is a namespace alias, returns the namespace it points to. 8585 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8586 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8587 return AD->getNamespace(); 8588 return dyn_cast_or_null<NamespaceDecl>(D); 8589 } 8590 8591 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8592 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8593 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8594 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8595 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8596 Namespc->setRBraceLoc(RBrace); 8597 PopDeclContext(); 8598 if (Namespc->hasAttr<VisibilityAttr>()) 8599 PopPragmaVisibility(true, RBrace); 8600 } 8601 8602 CXXRecordDecl *Sema::getStdBadAlloc() const { 8603 return cast_or_null<CXXRecordDecl>( 8604 StdBadAlloc.get(Context.getExternalSource())); 8605 } 8606 8607 EnumDecl *Sema::getStdAlignValT() const { 8608 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8609 } 8610 8611 NamespaceDecl *Sema::getStdNamespace() const { 8612 return cast_or_null<NamespaceDecl>( 8613 StdNamespace.get(Context.getExternalSource())); 8614 } 8615 8616 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8617 if (!StdExperimentalNamespaceCache) { 8618 if (auto Std = getStdNamespace()) { 8619 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8620 SourceLocation(), LookupNamespaceName); 8621 if (!LookupQualifiedName(Result, Std) || 8622 !(StdExperimentalNamespaceCache = 8623 Result.getAsSingle<NamespaceDecl>())) 8624 Result.suppressDiagnostics(); 8625 } 8626 } 8627 return StdExperimentalNamespaceCache; 8628 } 8629 8630 /// \brief Retrieve the special "std" namespace, which may require us to 8631 /// implicitly define the namespace. 8632 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8633 if (!StdNamespace) { 8634 // The "std" namespace has not yet been defined, so build one implicitly. 8635 StdNamespace = NamespaceDecl::Create(Context, 8636 Context.getTranslationUnitDecl(), 8637 /*Inline=*/false, 8638 SourceLocation(), SourceLocation(), 8639 &PP.getIdentifierTable().get("std"), 8640 /*PrevDecl=*/nullptr); 8641 getStdNamespace()->setImplicit(true); 8642 } 8643 8644 return getStdNamespace(); 8645 } 8646 8647 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8648 assert(getLangOpts().CPlusPlus && 8649 "Looking for std::initializer_list outside of C++."); 8650 8651 // We're looking for implicit instantiations of 8652 // template <typename E> class std::initializer_list. 8653 8654 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8655 return false; 8656 8657 ClassTemplateDecl *Template = nullptr; 8658 const TemplateArgument *Arguments = nullptr; 8659 8660 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8661 8662 ClassTemplateSpecializationDecl *Specialization = 8663 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8664 if (!Specialization) 8665 return false; 8666 8667 Template = Specialization->getSpecializedTemplate(); 8668 Arguments = Specialization->getTemplateArgs().data(); 8669 } else if (const TemplateSpecializationType *TST = 8670 Ty->getAs<TemplateSpecializationType>()) { 8671 Template = dyn_cast_or_null<ClassTemplateDecl>( 8672 TST->getTemplateName().getAsTemplateDecl()); 8673 Arguments = TST->getArgs(); 8674 } 8675 if (!Template) 8676 return false; 8677 8678 if (!StdInitializerList) { 8679 // Haven't recognized std::initializer_list yet, maybe this is it. 8680 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8681 if (TemplateClass->getIdentifier() != 8682 &PP.getIdentifierTable().get("initializer_list") || 8683 !getStdNamespace()->InEnclosingNamespaceSetOf( 8684 TemplateClass->getDeclContext())) 8685 return false; 8686 // This is a template called std::initializer_list, but is it the right 8687 // template? 8688 TemplateParameterList *Params = Template->getTemplateParameters(); 8689 if (Params->getMinRequiredArguments() != 1) 8690 return false; 8691 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8692 return false; 8693 8694 // It's the right template. 8695 StdInitializerList = Template; 8696 } 8697 8698 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8699 return false; 8700 8701 // This is an instance of std::initializer_list. Find the argument type. 8702 if (Element) 8703 *Element = Arguments[0].getAsType(); 8704 return true; 8705 } 8706 8707 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8708 NamespaceDecl *Std = S.getStdNamespace(); 8709 if (!Std) { 8710 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8711 return nullptr; 8712 } 8713 8714 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8715 Loc, Sema::LookupOrdinaryName); 8716 if (!S.LookupQualifiedName(Result, Std)) { 8717 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8718 return nullptr; 8719 } 8720 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8721 if (!Template) { 8722 Result.suppressDiagnostics(); 8723 // We found something weird. Complain about the first thing we found. 8724 NamedDecl *Found = *Result.begin(); 8725 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8726 return nullptr; 8727 } 8728 8729 // We found some template called std::initializer_list. Now verify that it's 8730 // correct. 8731 TemplateParameterList *Params = Template->getTemplateParameters(); 8732 if (Params->getMinRequiredArguments() != 1 || 8733 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8734 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8735 return nullptr; 8736 } 8737 8738 return Template; 8739 } 8740 8741 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8742 if (!StdInitializerList) { 8743 StdInitializerList = LookupStdInitializerList(*this, Loc); 8744 if (!StdInitializerList) 8745 return QualType(); 8746 } 8747 8748 TemplateArgumentListInfo Args(Loc, Loc); 8749 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8750 Context.getTrivialTypeSourceInfo(Element, 8751 Loc))); 8752 return Context.getCanonicalType( 8753 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8754 } 8755 8756 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 8757 // C++ [dcl.init.list]p2: 8758 // A constructor is an initializer-list constructor if its first parameter 8759 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8760 // std::initializer_list<E> for some type E, and either there are no other 8761 // parameters or else all other parameters have default arguments. 8762 if (Ctor->getNumParams() < 1 || 8763 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8764 return false; 8765 8766 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8767 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8768 ArgType = RT->getPointeeType().getUnqualifiedType(); 8769 8770 return isStdInitializerList(ArgType, nullptr); 8771 } 8772 8773 /// \brief Determine whether a using statement is in a context where it will be 8774 /// apply in all contexts. 8775 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8776 switch (CurContext->getDeclKind()) { 8777 case Decl::TranslationUnit: 8778 return true; 8779 case Decl::LinkageSpec: 8780 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8781 default: 8782 return false; 8783 } 8784 } 8785 8786 namespace { 8787 8788 // Callback to only accept typo corrections that are namespaces. 8789 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8790 public: 8791 bool ValidateCandidate(const TypoCorrection &candidate) override { 8792 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8793 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8794 return false; 8795 } 8796 }; 8797 8798 } 8799 8800 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8801 CXXScopeSpec &SS, 8802 SourceLocation IdentLoc, 8803 IdentifierInfo *Ident) { 8804 R.clear(); 8805 if (TypoCorrection Corrected = 8806 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8807 llvm::make_unique<NamespaceValidatorCCC>(), 8808 Sema::CTK_ErrorRecovery)) { 8809 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8810 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8811 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8812 Ident->getName().equals(CorrectedStr); 8813 S.diagnoseTypo(Corrected, 8814 S.PDiag(diag::err_using_directive_member_suggest) 8815 << Ident << DC << DroppedSpecifier << SS.getRange(), 8816 S.PDiag(diag::note_namespace_defined_here)); 8817 } else { 8818 S.diagnoseTypo(Corrected, 8819 S.PDiag(diag::err_using_directive_suggest) << Ident, 8820 S.PDiag(diag::note_namespace_defined_here)); 8821 } 8822 R.addDecl(Corrected.getFoundDecl()); 8823 return true; 8824 } 8825 return false; 8826 } 8827 8828 Decl *Sema::ActOnUsingDirective(Scope *S, 8829 SourceLocation UsingLoc, 8830 SourceLocation NamespcLoc, 8831 CXXScopeSpec &SS, 8832 SourceLocation IdentLoc, 8833 IdentifierInfo *NamespcName, 8834 AttributeList *AttrList) { 8835 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8836 assert(NamespcName && "Invalid NamespcName."); 8837 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 8838 8839 // This can only happen along a recovery path. 8840 while (S->isTemplateParamScope()) 8841 S = S->getParent(); 8842 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8843 8844 UsingDirectiveDecl *UDir = nullptr; 8845 NestedNameSpecifier *Qualifier = nullptr; 8846 if (SS.isSet()) 8847 Qualifier = SS.getScopeRep(); 8848 8849 // Lookup namespace name. 8850 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 8851 LookupParsedName(R, S, &SS); 8852 if (R.isAmbiguous()) 8853 return nullptr; 8854 8855 if (R.empty()) { 8856 R.clear(); 8857 // Allow "using namespace std;" or "using namespace ::std;" even if 8858 // "std" hasn't been defined yet, for GCC compatibility. 8859 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 8860 NamespcName->isStr("std")) { 8861 Diag(IdentLoc, diag::ext_using_undefined_std); 8862 R.addDecl(getOrCreateStdNamespace()); 8863 R.resolveKind(); 8864 } 8865 // Otherwise, attempt typo correction. 8866 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 8867 } 8868 8869 if (!R.empty()) { 8870 NamedDecl *Named = R.getRepresentativeDecl(); 8871 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 8872 assert(NS && "expected namespace decl"); 8873 8874 // The use of a nested name specifier may trigger deprecation warnings. 8875 DiagnoseUseOfDecl(Named, IdentLoc); 8876 8877 // C++ [namespace.udir]p1: 8878 // A using-directive specifies that the names in the nominated 8879 // namespace can be used in the scope in which the 8880 // using-directive appears after the using-directive. During 8881 // unqualified name lookup (3.4.1), the names appear as if they 8882 // were declared in the nearest enclosing namespace which 8883 // contains both the using-directive and the nominated 8884 // namespace. [Note: in this context, "contains" means "contains 8885 // directly or indirectly". ] 8886 8887 // Find enclosing context containing both using-directive and 8888 // nominated namespace. 8889 DeclContext *CommonAncestor = cast<DeclContext>(NS); 8890 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 8891 CommonAncestor = CommonAncestor->getParent(); 8892 8893 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 8894 SS.getWithLocInContext(Context), 8895 IdentLoc, Named, CommonAncestor); 8896 8897 if (IsUsingDirectiveInToplevelContext(CurContext) && 8898 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 8899 Diag(IdentLoc, diag::warn_using_directive_in_header); 8900 } 8901 8902 PushUsingDirective(S, UDir); 8903 } else { 8904 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8905 } 8906 8907 if (UDir) 8908 ProcessDeclAttributeList(S, UDir, AttrList); 8909 8910 return UDir; 8911 } 8912 8913 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 8914 // If the scope has an associated entity and the using directive is at 8915 // namespace or translation unit scope, add the UsingDirectiveDecl into 8916 // its lookup structure so qualified name lookup can find it. 8917 DeclContext *Ctx = S->getEntity(); 8918 if (Ctx && !Ctx->isFunctionOrMethod()) 8919 Ctx->addDecl(UDir); 8920 else 8921 // Otherwise, it is at block scope. The using-directives will affect lookup 8922 // only to the end of the scope. 8923 S->PushUsingDirective(UDir); 8924 } 8925 8926 8927 Decl *Sema::ActOnUsingDeclaration(Scope *S, 8928 AccessSpecifier AS, 8929 SourceLocation UsingLoc, 8930 SourceLocation TypenameLoc, 8931 CXXScopeSpec &SS, 8932 UnqualifiedId &Name, 8933 SourceLocation EllipsisLoc, 8934 AttributeList *AttrList) { 8935 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8936 8937 if (SS.isEmpty()) { 8938 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 8939 return nullptr; 8940 } 8941 8942 switch (Name.getKind()) { 8943 case UnqualifiedId::IK_ImplicitSelfParam: 8944 case UnqualifiedId::IK_Identifier: 8945 case UnqualifiedId::IK_OperatorFunctionId: 8946 case UnqualifiedId::IK_LiteralOperatorId: 8947 case UnqualifiedId::IK_ConversionFunctionId: 8948 break; 8949 8950 case UnqualifiedId::IK_ConstructorName: 8951 case UnqualifiedId::IK_ConstructorTemplateId: 8952 // C++11 inheriting constructors. 8953 Diag(Name.getLocStart(), 8954 getLangOpts().CPlusPlus11 ? 8955 diag::warn_cxx98_compat_using_decl_constructor : 8956 diag::err_using_decl_constructor) 8957 << SS.getRange(); 8958 8959 if (getLangOpts().CPlusPlus11) break; 8960 8961 return nullptr; 8962 8963 case UnqualifiedId::IK_DestructorName: 8964 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 8965 << SS.getRange(); 8966 return nullptr; 8967 8968 case UnqualifiedId::IK_TemplateId: 8969 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 8970 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 8971 return nullptr; 8972 8973 case UnqualifiedId::IK_DeductionGuideName: 8974 llvm_unreachable("cannot parse qualified deduction guide name"); 8975 } 8976 8977 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 8978 DeclarationName TargetName = TargetNameInfo.getName(); 8979 if (!TargetName) 8980 return nullptr; 8981 8982 // Warn about access declarations. 8983 if (UsingLoc.isInvalid()) { 8984 Diag(Name.getLocStart(), 8985 getLangOpts().CPlusPlus11 ? diag::err_access_decl 8986 : diag::warn_access_decl_deprecated) 8987 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 8988 } 8989 8990 if (EllipsisLoc.isInvalid()) { 8991 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 8992 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 8993 return nullptr; 8994 } else { 8995 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 8996 !TargetNameInfo.containsUnexpandedParameterPack()) { 8997 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 8998 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 8999 EllipsisLoc = SourceLocation(); 9000 } 9001 } 9002 9003 NamedDecl *UD = 9004 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9005 SS, TargetNameInfo, EllipsisLoc, AttrList, 9006 /*IsInstantiation*/false); 9007 if (UD) 9008 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9009 9010 return UD; 9011 } 9012 9013 /// \brief Determine whether a using declaration considers the given 9014 /// declarations as "equivalent", e.g., if they are redeclarations of 9015 /// the same entity or are both typedefs of the same type. 9016 static bool 9017 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9018 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9019 return true; 9020 9021 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9022 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9023 return Context.hasSameType(TD1->getUnderlyingType(), 9024 TD2->getUnderlyingType()); 9025 9026 return false; 9027 } 9028 9029 9030 /// Determines whether to create a using shadow decl for a particular 9031 /// decl, given the set of decls existing prior to this using lookup. 9032 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9033 const LookupResult &Previous, 9034 UsingShadowDecl *&PrevShadow) { 9035 // Diagnose finding a decl which is not from a base class of the 9036 // current class. We do this now because there are cases where this 9037 // function will silently decide not to build a shadow decl, which 9038 // will pre-empt further diagnostics. 9039 // 9040 // We don't need to do this in C++11 because we do the check once on 9041 // the qualifier. 9042 // 9043 // FIXME: diagnose the following if we care enough: 9044 // struct A { int foo; }; 9045 // struct B : A { using A::foo; }; 9046 // template <class T> struct C : A {}; 9047 // template <class T> struct D : C<T> { using B::foo; } // <--- 9048 // This is invalid (during instantiation) in C++03 because B::foo 9049 // resolves to the using decl in B, which is not a base class of D<T>. 9050 // We can't diagnose it immediately because C<T> is an unknown 9051 // specialization. The UsingShadowDecl in D<T> then points directly 9052 // to A::foo, which will look well-formed when we instantiate. 9053 // The right solution is to not collapse the shadow-decl chain. 9054 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9055 DeclContext *OrigDC = Orig->getDeclContext(); 9056 9057 // Handle enums and anonymous structs. 9058 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9059 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9060 while (OrigRec->isAnonymousStructOrUnion()) 9061 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9062 9063 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9064 if (OrigDC == CurContext) { 9065 Diag(Using->getLocation(), 9066 diag::err_using_decl_nested_name_specifier_is_current_class) 9067 << Using->getQualifierLoc().getSourceRange(); 9068 Diag(Orig->getLocation(), diag::note_using_decl_target); 9069 Using->setInvalidDecl(); 9070 return true; 9071 } 9072 9073 Diag(Using->getQualifierLoc().getBeginLoc(), 9074 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9075 << Using->getQualifier() 9076 << cast<CXXRecordDecl>(CurContext) 9077 << Using->getQualifierLoc().getSourceRange(); 9078 Diag(Orig->getLocation(), diag::note_using_decl_target); 9079 Using->setInvalidDecl(); 9080 return true; 9081 } 9082 } 9083 9084 if (Previous.empty()) return false; 9085 9086 NamedDecl *Target = Orig; 9087 if (isa<UsingShadowDecl>(Target)) 9088 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9089 9090 // If the target happens to be one of the previous declarations, we 9091 // don't have a conflict. 9092 // 9093 // FIXME: but we might be increasing its access, in which case we 9094 // should redeclare it. 9095 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9096 bool FoundEquivalentDecl = false; 9097 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9098 I != E; ++I) { 9099 NamedDecl *D = (*I)->getUnderlyingDecl(); 9100 // We can have UsingDecls in our Previous results because we use the same 9101 // LookupResult for checking whether the UsingDecl itself is a valid 9102 // redeclaration. 9103 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9104 continue; 9105 9106 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9107 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9108 PrevShadow = Shadow; 9109 FoundEquivalentDecl = true; 9110 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9111 // We don't conflict with an existing using shadow decl of an equivalent 9112 // declaration, but we're not a redeclaration of it. 9113 FoundEquivalentDecl = true; 9114 } 9115 9116 if (isVisible(D)) 9117 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9118 } 9119 9120 if (FoundEquivalentDecl) 9121 return false; 9122 9123 if (FunctionDecl *FD = Target->getAsFunction()) { 9124 NamedDecl *OldDecl = nullptr; 9125 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9126 /*IsForUsingDecl*/ true)) { 9127 case Ovl_Overload: 9128 return false; 9129 9130 case Ovl_NonFunction: 9131 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9132 break; 9133 9134 // We found a decl with the exact signature. 9135 case Ovl_Match: 9136 // If we're in a record, we want to hide the target, so we 9137 // return true (without a diagnostic) to tell the caller not to 9138 // build a shadow decl. 9139 if (CurContext->isRecord()) 9140 return true; 9141 9142 // If we're not in a record, this is an error. 9143 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9144 break; 9145 } 9146 9147 Diag(Target->getLocation(), diag::note_using_decl_target); 9148 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9149 Using->setInvalidDecl(); 9150 return true; 9151 } 9152 9153 // Target is not a function. 9154 9155 if (isa<TagDecl>(Target)) { 9156 // No conflict between a tag and a non-tag. 9157 if (!Tag) return false; 9158 9159 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9160 Diag(Target->getLocation(), diag::note_using_decl_target); 9161 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9162 Using->setInvalidDecl(); 9163 return true; 9164 } 9165 9166 // No conflict between a tag and a non-tag. 9167 if (!NonTag) return false; 9168 9169 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9170 Diag(Target->getLocation(), diag::note_using_decl_target); 9171 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9172 Using->setInvalidDecl(); 9173 return true; 9174 } 9175 9176 /// Determine whether a direct base class is a virtual base class. 9177 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9178 if (!Derived->getNumVBases()) 9179 return false; 9180 for (auto &B : Derived->bases()) 9181 if (B.getType()->getAsCXXRecordDecl() == Base) 9182 return B.isVirtual(); 9183 llvm_unreachable("not a direct base class"); 9184 } 9185 9186 /// Builds a shadow declaration corresponding to a 'using' declaration. 9187 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9188 UsingDecl *UD, 9189 NamedDecl *Orig, 9190 UsingShadowDecl *PrevDecl) { 9191 // If we resolved to another shadow declaration, just coalesce them. 9192 NamedDecl *Target = Orig; 9193 if (isa<UsingShadowDecl>(Target)) { 9194 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9195 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9196 } 9197 9198 NamedDecl *NonTemplateTarget = Target; 9199 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9200 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9201 9202 UsingShadowDecl *Shadow; 9203 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9204 bool IsVirtualBase = 9205 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9206 UD->getQualifier()->getAsRecordDecl()); 9207 Shadow = ConstructorUsingShadowDecl::Create( 9208 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9209 } else { 9210 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9211 Target); 9212 } 9213 UD->addShadowDecl(Shadow); 9214 9215 Shadow->setAccess(UD->getAccess()); 9216 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9217 Shadow->setInvalidDecl(); 9218 9219 Shadow->setPreviousDecl(PrevDecl); 9220 9221 if (S) 9222 PushOnScopeChains(Shadow, S); 9223 else 9224 CurContext->addDecl(Shadow); 9225 9226 9227 return Shadow; 9228 } 9229 9230 /// Hides a using shadow declaration. This is required by the current 9231 /// using-decl implementation when a resolvable using declaration in a 9232 /// class is followed by a declaration which would hide or override 9233 /// one or more of the using decl's targets; for example: 9234 /// 9235 /// struct Base { void foo(int); }; 9236 /// struct Derived : Base { 9237 /// using Base::foo; 9238 /// void foo(int); 9239 /// }; 9240 /// 9241 /// The governing language is C++03 [namespace.udecl]p12: 9242 /// 9243 /// When a using-declaration brings names from a base class into a 9244 /// derived class scope, member functions in the derived class 9245 /// override and/or hide member functions with the same name and 9246 /// parameter types in a base class (rather than conflicting). 9247 /// 9248 /// There are two ways to implement this: 9249 /// (1) optimistically create shadow decls when they're not hidden 9250 /// by existing declarations, or 9251 /// (2) don't create any shadow decls (or at least don't make them 9252 /// visible) until we've fully parsed/instantiated the class. 9253 /// The problem with (1) is that we might have to retroactively remove 9254 /// a shadow decl, which requires several O(n) operations because the 9255 /// decl structures are (very reasonably) not designed for removal. 9256 /// (2) avoids this but is very fiddly and phase-dependent. 9257 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9258 if (Shadow->getDeclName().getNameKind() == 9259 DeclarationName::CXXConversionFunctionName) 9260 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9261 9262 // Remove it from the DeclContext... 9263 Shadow->getDeclContext()->removeDecl(Shadow); 9264 9265 // ...and the scope, if applicable... 9266 if (S) { 9267 S->RemoveDecl(Shadow); 9268 IdResolver.RemoveDecl(Shadow); 9269 } 9270 9271 // ...and the using decl. 9272 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9273 9274 // TODO: complain somehow if Shadow was used. It shouldn't 9275 // be possible for this to happen, because...? 9276 } 9277 9278 /// Find the base specifier for a base class with the given type. 9279 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9280 QualType DesiredBase, 9281 bool &AnyDependentBases) { 9282 // Check whether the named type is a direct base class. 9283 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9284 for (auto &Base : Derived->bases()) { 9285 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9286 if (CanonicalDesiredBase == BaseType) 9287 return &Base; 9288 if (BaseType->isDependentType()) 9289 AnyDependentBases = true; 9290 } 9291 return nullptr; 9292 } 9293 9294 namespace { 9295 class UsingValidatorCCC : public CorrectionCandidateCallback { 9296 public: 9297 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9298 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9299 : HasTypenameKeyword(HasTypenameKeyword), 9300 IsInstantiation(IsInstantiation), OldNNS(NNS), 9301 RequireMemberOf(RequireMemberOf) {} 9302 9303 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9304 NamedDecl *ND = Candidate.getCorrectionDecl(); 9305 9306 // Keywords are not valid here. 9307 if (!ND || isa<NamespaceDecl>(ND)) 9308 return false; 9309 9310 // Completely unqualified names are invalid for a 'using' declaration. 9311 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9312 return false; 9313 9314 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9315 // reject. 9316 9317 if (RequireMemberOf) { 9318 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9319 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9320 // No-one ever wants a using-declaration to name an injected-class-name 9321 // of a base class, unless they're declaring an inheriting constructor. 9322 ASTContext &Ctx = ND->getASTContext(); 9323 if (!Ctx.getLangOpts().CPlusPlus11) 9324 return false; 9325 QualType FoundType = Ctx.getRecordType(FoundRecord); 9326 9327 // Check that the injected-class-name is named as a member of its own 9328 // type; we don't want to suggest 'using Derived::Base;', since that 9329 // means something else. 9330 NestedNameSpecifier *Specifier = 9331 Candidate.WillReplaceSpecifier() 9332 ? Candidate.getCorrectionSpecifier() 9333 : OldNNS; 9334 if (!Specifier->getAsType() || 9335 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9336 return false; 9337 9338 // Check that this inheriting constructor declaration actually names a 9339 // direct base class of the current class. 9340 bool AnyDependentBases = false; 9341 if (!findDirectBaseWithType(RequireMemberOf, 9342 Ctx.getRecordType(FoundRecord), 9343 AnyDependentBases) && 9344 !AnyDependentBases) 9345 return false; 9346 } else { 9347 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9348 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9349 return false; 9350 9351 // FIXME: Check that the base class member is accessible? 9352 } 9353 } else { 9354 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9355 if (FoundRecord && FoundRecord->isInjectedClassName()) 9356 return false; 9357 } 9358 9359 if (isa<TypeDecl>(ND)) 9360 return HasTypenameKeyword || !IsInstantiation; 9361 9362 return !HasTypenameKeyword; 9363 } 9364 9365 private: 9366 bool HasTypenameKeyword; 9367 bool IsInstantiation; 9368 NestedNameSpecifier *OldNNS; 9369 CXXRecordDecl *RequireMemberOf; 9370 }; 9371 } // end anonymous namespace 9372 9373 /// Builds a using declaration. 9374 /// 9375 /// \param IsInstantiation - Whether this call arises from an 9376 /// instantiation of an unresolved using declaration. We treat 9377 /// the lookup differently for these declarations. 9378 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9379 SourceLocation UsingLoc, 9380 bool HasTypenameKeyword, 9381 SourceLocation TypenameLoc, 9382 CXXScopeSpec &SS, 9383 DeclarationNameInfo NameInfo, 9384 SourceLocation EllipsisLoc, 9385 AttributeList *AttrList, 9386 bool IsInstantiation) { 9387 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9388 SourceLocation IdentLoc = NameInfo.getLoc(); 9389 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9390 9391 // FIXME: We ignore attributes for now. 9392 9393 // For an inheriting constructor declaration, the name of the using 9394 // declaration is the name of a constructor in this class, not in the 9395 // base class. 9396 DeclarationNameInfo UsingName = NameInfo; 9397 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9398 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9399 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9400 Context.getCanonicalType(Context.getRecordType(RD)))); 9401 9402 // Do the redeclaration lookup in the current scope. 9403 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9404 ForRedeclaration); 9405 Previous.setHideTags(false); 9406 if (S) { 9407 LookupName(Previous, S); 9408 9409 // It is really dumb that we have to do this. 9410 LookupResult::Filter F = Previous.makeFilter(); 9411 while (F.hasNext()) { 9412 NamedDecl *D = F.next(); 9413 if (!isDeclInScope(D, CurContext, S)) 9414 F.erase(); 9415 // If we found a local extern declaration that's not ordinarily visible, 9416 // and this declaration is being added to a non-block scope, ignore it. 9417 // We're only checking for scope conflicts here, not also for violations 9418 // of the linkage rules. 9419 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9420 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9421 F.erase(); 9422 } 9423 F.done(); 9424 } else { 9425 assert(IsInstantiation && "no scope in non-instantiation"); 9426 if (CurContext->isRecord()) 9427 LookupQualifiedName(Previous, CurContext); 9428 else { 9429 // No redeclaration check is needed here; in non-member contexts we 9430 // diagnosed all possible conflicts with other using-declarations when 9431 // building the template: 9432 // 9433 // For a dependent non-type using declaration, the only valid case is 9434 // if we instantiate to a single enumerator. We check for conflicts 9435 // between shadow declarations we introduce, and we check in the template 9436 // definition for conflicts between a non-type using declaration and any 9437 // other declaration, which together covers all cases. 9438 // 9439 // A dependent typename using declaration will never successfully 9440 // instantiate, since it will always name a class member, so we reject 9441 // that in the template definition. 9442 } 9443 } 9444 9445 // Check for invalid redeclarations. 9446 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9447 SS, IdentLoc, Previous)) 9448 return nullptr; 9449 9450 // Check for bad qualifiers. 9451 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9452 IdentLoc)) 9453 return nullptr; 9454 9455 DeclContext *LookupContext = computeDeclContext(SS); 9456 NamedDecl *D; 9457 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9458 if (!LookupContext || EllipsisLoc.isValid()) { 9459 if (HasTypenameKeyword) { 9460 // FIXME: not all declaration name kinds are legal here 9461 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9462 UsingLoc, TypenameLoc, 9463 QualifierLoc, 9464 IdentLoc, NameInfo.getName(), 9465 EllipsisLoc); 9466 } else { 9467 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9468 QualifierLoc, NameInfo, EllipsisLoc); 9469 } 9470 D->setAccess(AS); 9471 CurContext->addDecl(D); 9472 return D; 9473 } 9474 9475 auto Build = [&](bool Invalid) { 9476 UsingDecl *UD = 9477 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9478 UsingName, HasTypenameKeyword); 9479 UD->setAccess(AS); 9480 CurContext->addDecl(UD); 9481 UD->setInvalidDecl(Invalid); 9482 return UD; 9483 }; 9484 auto BuildInvalid = [&]{ return Build(true); }; 9485 auto BuildValid = [&]{ return Build(false); }; 9486 9487 if (RequireCompleteDeclContext(SS, LookupContext)) 9488 return BuildInvalid(); 9489 9490 // Look up the target name. 9491 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9492 9493 // Unlike most lookups, we don't always want to hide tag 9494 // declarations: tag names are visible through the using declaration 9495 // even if hidden by ordinary names, *except* in a dependent context 9496 // where it's important for the sanity of two-phase lookup. 9497 if (!IsInstantiation) 9498 R.setHideTags(false); 9499 9500 // For the purposes of this lookup, we have a base object type 9501 // equal to that of the current context. 9502 if (CurContext->isRecord()) { 9503 R.setBaseObjectType( 9504 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9505 } 9506 9507 LookupQualifiedName(R, LookupContext); 9508 9509 // Try to correct typos if possible. If constructor name lookup finds no 9510 // results, that means the named class has no explicit constructors, and we 9511 // suppressed declaring implicit ones (probably because it's dependent or 9512 // invalid). 9513 if (R.empty() && 9514 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9515 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9516 // it will believe that glibc provides a ::gets in cases where it does not, 9517 // and will try to pull it into namespace std with a using-declaration. 9518 // Just ignore the using-declaration in that case. 9519 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9520 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9521 CurContext->isStdNamespace() && 9522 isa<TranslationUnitDecl>(LookupContext) && 9523 getSourceManager().isInSystemHeader(UsingLoc)) 9524 return nullptr; 9525 if (TypoCorrection Corrected = CorrectTypo( 9526 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9527 llvm::make_unique<UsingValidatorCCC>( 9528 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9529 dyn_cast<CXXRecordDecl>(CurContext)), 9530 CTK_ErrorRecovery)) { 9531 // We reject candidates where DroppedSpecifier == true, hence the 9532 // literal '0' below. 9533 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9534 << NameInfo.getName() << LookupContext << 0 9535 << SS.getRange()); 9536 9537 // If we picked a correction with no attached Decl we can't do anything 9538 // useful with it, bail out. 9539 NamedDecl *ND = Corrected.getCorrectionDecl(); 9540 if (!ND) 9541 return BuildInvalid(); 9542 9543 // If we corrected to an inheriting constructor, handle it as one. 9544 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9545 if (RD && RD->isInjectedClassName()) { 9546 // The parent of the injected class name is the class itself. 9547 RD = cast<CXXRecordDecl>(RD->getParent()); 9548 9549 // Fix up the information we'll use to build the using declaration. 9550 if (Corrected.WillReplaceSpecifier()) { 9551 NestedNameSpecifierLocBuilder Builder; 9552 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9553 QualifierLoc.getSourceRange()); 9554 QualifierLoc = Builder.getWithLocInContext(Context); 9555 } 9556 9557 // In this case, the name we introduce is the name of a derived class 9558 // constructor. 9559 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9560 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9561 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9562 UsingName.setNamedTypeInfo(nullptr); 9563 for (auto *Ctor : LookupConstructors(RD)) 9564 R.addDecl(Ctor); 9565 R.resolveKind(); 9566 } else { 9567 // FIXME: Pick up all the declarations if we found an overloaded 9568 // function. 9569 UsingName.setName(ND->getDeclName()); 9570 R.addDecl(ND); 9571 } 9572 } else { 9573 Diag(IdentLoc, diag::err_no_member) 9574 << NameInfo.getName() << LookupContext << SS.getRange(); 9575 return BuildInvalid(); 9576 } 9577 } 9578 9579 if (R.isAmbiguous()) 9580 return BuildInvalid(); 9581 9582 if (HasTypenameKeyword) { 9583 // If we asked for a typename and got a non-type decl, error out. 9584 if (!R.getAsSingle<TypeDecl>()) { 9585 Diag(IdentLoc, diag::err_using_typename_non_type); 9586 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9587 Diag((*I)->getUnderlyingDecl()->getLocation(), 9588 diag::note_using_decl_target); 9589 return BuildInvalid(); 9590 } 9591 } else { 9592 // If we asked for a non-typename and we got a type, error out, 9593 // but only if this is an instantiation of an unresolved using 9594 // decl. Otherwise just silently find the type name. 9595 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9596 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9597 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9598 return BuildInvalid(); 9599 } 9600 } 9601 9602 // C++14 [namespace.udecl]p6: 9603 // A using-declaration shall not name a namespace. 9604 if (R.getAsSingle<NamespaceDecl>()) { 9605 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9606 << SS.getRange(); 9607 return BuildInvalid(); 9608 } 9609 9610 // C++14 [namespace.udecl]p7: 9611 // A using-declaration shall not name a scoped enumerator. 9612 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9613 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9614 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9615 << SS.getRange(); 9616 return BuildInvalid(); 9617 } 9618 } 9619 9620 UsingDecl *UD = BuildValid(); 9621 9622 // Some additional rules apply to inheriting constructors. 9623 if (UsingName.getName().getNameKind() == 9624 DeclarationName::CXXConstructorName) { 9625 // Suppress access diagnostics; the access check is instead performed at the 9626 // point of use for an inheriting constructor. 9627 R.suppressDiagnostics(); 9628 if (CheckInheritingConstructorUsingDecl(UD)) 9629 return UD; 9630 } 9631 9632 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9633 UsingShadowDecl *PrevDecl = nullptr; 9634 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9635 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9636 } 9637 9638 return UD; 9639 } 9640 9641 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 9642 ArrayRef<NamedDecl *> Expansions) { 9643 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 9644 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 9645 isa<UsingPackDecl>(InstantiatedFrom)); 9646 9647 auto *UPD = 9648 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 9649 UPD->setAccess(InstantiatedFrom->getAccess()); 9650 CurContext->addDecl(UPD); 9651 return UPD; 9652 } 9653 9654 /// Additional checks for a using declaration referring to a constructor name. 9655 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9656 assert(!UD->hasTypename() && "expecting a constructor name"); 9657 9658 const Type *SourceType = UD->getQualifier()->getAsType(); 9659 assert(SourceType && 9660 "Using decl naming constructor doesn't have type in scope spec."); 9661 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9662 9663 // Check whether the named type is a direct base class. 9664 bool AnyDependentBases = false; 9665 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9666 AnyDependentBases); 9667 if (!Base && !AnyDependentBases) { 9668 Diag(UD->getUsingLoc(), 9669 diag::err_using_decl_constructor_not_in_direct_base) 9670 << UD->getNameInfo().getSourceRange() 9671 << QualType(SourceType, 0) << TargetClass; 9672 UD->setInvalidDecl(); 9673 return true; 9674 } 9675 9676 if (Base) 9677 Base->setInheritConstructors(); 9678 9679 return false; 9680 } 9681 9682 /// Checks that the given using declaration is not an invalid 9683 /// redeclaration. Note that this is checking only for the using decl 9684 /// itself, not for any ill-formedness among the UsingShadowDecls. 9685 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9686 bool HasTypenameKeyword, 9687 const CXXScopeSpec &SS, 9688 SourceLocation NameLoc, 9689 const LookupResult &Prev) { 9690 NestedNameSpecifier *Qual = SS.getScopeRep(); 9691 9692 // C++03 [namespace.udecl]p8: 9693 // C++0x [namespace.udecl]p10: 9694 // A using-declaration is a declaration and can therefore be used 9695 // repeatedly where (and only where) multiple declarations are 9696 // allowed. 9697 // 9698 // That's in non-member contexts. 9699 if (!CurContext->getRedeclContext()->isRecord()) { 9700 // A dependent qualifier outside a class can only ever resolve to an 9701 // enumeration type. Therefore it conflicts with any other non-type 9702 // declaration in the same scope. 9703 // FIXME: How should we check for dependent type-type conflicts at block 9704 // scope? 9705 if (Qual->isDependent() && !HasTypenameKeyword) { 9706 for (auto *D : Prev) { 9707 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 9708 bool OldCouldBeEnumerator = 9709 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 9710 Diag(NameLoc, 9711 OldCouldBeEnumerator ? diag::err_redefinition 9712 : diag::err_redefinition_different_kind) 9713 << Prev.getLookupName(); 9714 Diag(D->getLocation(), diag::note_previous_definition); 9715 return true; 9716 } 9717 } 9718 } 9719 return false; 9720 } 9721 9722 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9723 NamedDecl *D = *I; 9724 9725 bool DTypename; 9726 NestedNameSpecifier *DQual; 9727 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9728 DTypename = UD->hasTypename(); 9729 DQual = UD->getQualifier(); 9730 } else if (UnresolvedUsingValueDecl *UD 9731 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9732 DTypename = false; 9733 DQual = UD->getQualifier(); 9734 } else if (UnresolvedUsingTypenameDecl *UD 9735 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9736 DTypename = true; 9737 DQual = UD->getQualifier(); 9738 } else continue; 9739 9740 // using decls differ if one says 'typename' and the other doesn't. 9741 // FIXME: non-dependent using decls? 9742 if (HasTypenameKeyword != DTypename) continue; 9743 9744 // using decls differ if they name different scopes (but note that 9745 // template instantiation can cause this check to trigger when it 9746 // didn't before instantiation). 9747 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9748 Context.getCanonicalNestedNameSpecifier(DQual)) 9749 continue; 9750 9751 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9752 Diag(D->getLocation(), diag::note_using_decl) << 1; 9753 return true; 9754 } 9755 9756 return false; 9757 } 9758 9759 9760 /// Checks that the given nested-name qualifier used in a using decl 9761 /// in the current context is appropriately related to the current 9762 /// scope. If an error is found, diagnoses it and returns true. 9763 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9764 bool HasTypename, 9765 const CXXScopeSpec &SS, 9766 const DeclarationNameInfo &NameInfo, 9767 SourceLocation NameLoc) { 9768 DeclContext *NamedContext = computeDeclContext(SS); 9769 9770 if (!CurContext->isRecord()) { 9771 // C++03 [namespace.udecl]p3: 9772 // C++0x [namespace.udecl]p8: 9773 // A using-declaration for a class member shall be a member-declaration. 9774 9775 // If we weren't able to compute a valid scope, it might validly be a 9776 // dependent class scope or a dependent enumeration unscoped scope. If 9777 // we have a 'typename' keyword, the scope must resolve to a class type. 9778 if ((HasTypename && !NamedContext) || 9779 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 9780 auto *RD = NamedContext 9781 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9782 : nullptr; 9783 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9784 RD = nullptr; 9785 9786 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9787 << SS.getRange(); 9788 9789 // If we have a complete, non-dependent source type, try to suggest a 9790 // way to get the same effect. 9791 if (!RD) 9792 return true; 9793 9794 // Find what this using-declaration was referring to. 9795 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9796 R.setHideTags(false); 9797 R.suppressDiagnostics(); 9798 LookupQualifiedName(R, RD); 9799 9800 if (R.getAsSingle<TypeDecl>()) { 9801 if (getLangOpts().CPlusPlus11) { 9802 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9803 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9804 << 0 // alias declaration 9805 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9806 NameInfo.getName().getAsString() + 9807 " = "); 9808 } else { 9809 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9810 SourceLocation InsertLoc = 9811 getLocForEndOfToken(NameInfo.getLocEnd()); 9812 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9813 << 1 // typedef declaration 9814 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9815 << FixItHint::CreateInsertion( 9816 InsertLoc, " " + NameInfo.getName().getAsString()); 9817 } 9818 } else if (R.getAsSingle<VarDecl>()) { 9819 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9820 // repeating the type of the static data member here. 9821 FixItHint FixIt; 9822 if (getLangOpts().CPlusPlus11) { 9823 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9824 FixIt = FixItHint::CreateReplacement( 9825 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9826 } 9827 9828 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9829 << 2 // reference declaration 9830 << FixIt; 9831 } else if (R.getAsSingle<EnumConstantDecl>()) { 9832 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9833 // repeating the type of the enumeration here, and we can't do so if 9834 // the type is anonymous. 9835 FixItHint FixIt; 9836 if (getLangOpts().CPlusPlus11) { 9837 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9838 FixIt = FixItHint::CreateReplacement( 9839 UsingLoc, 9840 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 9841 } 9842 9843 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9844 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 9845 << FixIt; 9846 } 9847 return true; 9848 } 9849 9850 // Otherwise, this might be valid. 9851 return false; 9852 } 9853 9854 // The current scope is a record. 9855 9856 // If the named context is dependent, we can't decide much. 9857 if (!NamedContext) { 9858 // FIXME: in C++0x, we can diagnose if we can prove that the 9859 // nested-name-specifier does not refer to a base class, which is 9860 // still possible in some cases. 9861 9862 // Otherwise we have to conservatively report that things might be 9863 // okay. 9864 return false; 9865 } 9866 9867 if (!NamedContext->isRecord()) { 9868 // Ideally this would point at the last name in the specifier, 9869 // but we don't have that level of source info. 9870 Diag(SS.getRange().getBegin(), 9871 diag::err_using_decl_nested_name_specifier_is_not_class) 9872 << SS.getScopeRep() << SS.getRange(); 9873 return true; 9874 } 9875 9876 if (!NamedContext->isDependentContext() && 9877 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 9878 return true; 9879 9880 if (getLangOpts().CPlusPlus11) { 9881 // C++11 [namespace.udecl]p3: 9882 // In a using-declaration used as a member-declaration, the 9883 // nested-name-specifier shall name a base class of the class 9884 // being defined. 9885 9886 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 9887 cast<CXXRecordDecl>(NamedContext))) { 9888 if (CurContext == NamedContext) { 9889 Diag(NameLoc, 9890 diag::err_using_decl_nested_name_specifier_is_current_class) 9891 << SS.getRange(); 9892 return true; 9893 } 9894 9895 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 9896 Diag(SS.getRange().getBegin(), 9897 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9898 << SS.getScopeRep() 9899 << cast<CXXRecordDecl>(CurContext) 9900 << SS.getRange(); 9901 } 9902 return true; 9903 } 9904 9905 return false; 9906 } 9907 9908 // C++03 [namespace.udecl]p4: 9909 // A using-declaration used as a member-declaration shall refer 9910 // to a member of a base class of the class being defined [etc.]. 9911 9912 // Salient point: SS doesn't have to name a base class as long as 9913 // lookup only finds members from base classes. Therefore we can 9914 // diagnose here only if we can prove that that can't happen, 9915 // i.e. if the class hierarchies provably don't intersect. 9916 9917 // TODO: it would be nice if "definitely valid" results were cached 9918 // in the UsingDecl and UsingShadowDecl so that these checks didn't 9919 // need to be repeated. 9920 9921 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 9922 auto Collect = [&Bases](const CXXRecordDecl *Base) { 9923 Bases.insert(Base); 9924 return true; 9925 }; 9926 9927 // Collect all bases. Return false if we find a dependent base. 9928 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 9929 return false; 9930 9931 // Returns true if the base is dependent or is one of the accumulated base 9932 // classes. 9933 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 9934 return !Bases.count(Base); 9935 }; 9936 9937 // Return false if the class has a dependent base or if it or one 9938 // of its bases is present in the base set of the current context. 9939 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 9940 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 9941 return false; 9942 9943 Diag(SS.getRange().getBegin(), 9944 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9945 << SS.getScopeRep() 9946 << cast<CXXRecordDecl>(CurContext) 9947 << SS.getRange(); 9948 9949 return true; 9950 } 9951 9952 Decl *Sema::ActOnAliasDeclaration(Scope *S, 9953 AccessSpecifier AS, 9954 MultiTemplateParamsArg TemplateParamLists, 9955 SourceLocation UsingLoc, 9956 UnqualifiedId &Name, 9957 AttributeList *AttrList, 9958 TypeResult Type, 9959 Decl *DeclFromDeclSpec) { 9960 // Skip up to the relevant declaration scope. 9961 while (S->isTemplateParamScope()) 9962 S = S->getParent(); 9963 assert((S->getFlags() & Scope::DeclScope) && 9964 "got alias-declaration outside of declaration scope"); 9965 9966 if (Type.isInvalid()) 9967 return nullptr; 9968 9969 bool Invalid = false; 9970 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 9971 TypeSourceInfo *TInfo = nullptr; 9972 GetTypeFromParser(Type.get(), &TInfo); 9973 9974 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 9975 return nullptr; 9976 9977 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 9978 UPPC_DeclarationType)) { 9979 Invalid = true; 9980 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9981 TInfo->getTypeLoc().getBeginLoc()); 9982 } 9983 9984 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 9985 LookupName(Previous, S); 9986 9987 // Warn about shadowing the name of a template parameter. 9988 if (Previous.isSingleResult() && 9989 Previous.getFoundDecl()->isTemplateParameter()) { 9990 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 9991 Previous.clear(); 9992 } 9993 9994 assert(Name.Kind == UnqualifiedId::IK_Identifier && 9995 "name in alias declaration must be an identifier"); 9996 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 9997 Name.StartLocation, 9998 Name.Identifier, TInfo); 9999 10000 NewTD->setAccess(AS); 10001 10002 if (Invalid) 10003 NewTD->setInvalidDecl(); 10004 10005 ProcessDeclAttributeList(S, NewTD, AttrList); 10006 AddPragmaAttributes(S, NewTD); 10007 10008 CheckTypedefForVariablyModifiedType(S, NewTD); 10009 Invalid |= NewTD->isInvalidDecl(); 10010 10011 bool Redeclaration = false; 10012 10013 NamedDecl *NewND; 10014 if (TemplateParamLists.size()) { 10015 TypeAliasTemplateDecl *OldDecl = nullptr; 10016 TemplateParameterList *OldTemplateParams = nullptr; 10017 10018 if (TemplateParamLists.size() != 1) { 10019 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10020 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10021 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10022 } 10023 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10024 10025 // Check that we can declare a template here. 10026 if (CheckTemplateDeclScope(S, TemplateParams)) 10027 return nullptr; 10028 10029 // Only consider previous declarations in the same scope. 10030 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10031 /*ExplicitInstantiationOrSpecialization*/false); 10032 if (!Previous.empty()) { 10033 Redeclaration = true; 10034 10035 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10036 if (!OldDecl && !Invalid) { 10037 Diag(UsingLoc, diag::err_redefinition_different_kind) 10038 << Name.Identifier; 10039 10040 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10041 if (OldD->getLocation().isValid()) 10042 Diag(OldD->getLocation(), diag::note_previous_definition); 10043 10044 Invalid = true; 10045 } 10046 10047 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10048 if (TemplateParameterListsAreEqual(TemplateParams, 10049 OldDecl->getTemplateParameters(), 10050 /*Complain=*/true, 10051 TPL_TemplateMatch)) 10052 OldTemplateParams = OldDecl->getTemplateParameters(); 10053 else 10054 Invalid = true; 10055 10056 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10057 if (!Invalid && 10058 !Context.hasSameType(OldTD->getUnderlyingType(), 10059 NewTD->getUnderlyingType())) { 10060 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10061 // but we can't reasonably accept it. 10062 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10063 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10064 if (OldTD->getLocation().isValid()) 10065 Diag(OldTD->getLocation(), diag::note_previous_definition); 10066 Invalid = true; 10067 } 10068 } 10069 } 10070 10071 // Merge any previous default template arguments into our parameters, 10072 // and check the parameter list. 10073 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10074 TPC_TypeAliasTemplate)) 10075 return nullptr; 10076 10077 TypeAliasTemplateDecl *NewDecl = 10078 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10079 Name.Identifier, TemplateParams, 10080 NewTD); 10081 NewTD->setDescribedAliasTemplate(NewDecl); 10082 10083 NewDecl->setAccess(AS); 10084 10085 if (Invalid) 10086 NewDecl->setInvalidDecl(); 10087 else if (OldDecl) 10088 NewDecl->setPreviousDecl(OldDecl); 10089 10090 NewND = NewDecl; 10091 } else { 10092 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10093 setTagNameForLinkagePurposes(TD, NewTD); 10094 handleTagNumbering(TD, S); 10095 } 10096 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10097 NewND = NewTD; 10098 } 10099 10100 PushOnScopeChains(NewND, S); 10101 ActOnDocumentableDecl(NewND); 10102 return NewND; 10103 } 10104 10105 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10106 SourceLocation AliasLoc, 10107 IdentifierInfo *Alias, CXXScopeSpec &SS, 10108 SourceLocation IdentLoc, 10109 IdentifierInfo *Ident) { 10110 10111 // Lookup the namespace name. 10112 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10113 LookupParsedName(R, S, &SS); 10114 10115 if (R.isAmbiguous()) 10116 return nullptr; 10117 10118 if (R.empty()) { 10119 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10120 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10121 return nullptr; 10122 } 10123 } 10124 assert(!R.isAmbiguous() && !R.empty()); 10125 NamedDecl *ND = R.getRepresentativeDecl(); 10126 10127 // Check if we have a previous declaration with the same name. 10128 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10129 ForRedeclaration); 10130 LookupName(PrevR, S); 10131 10132 // Check we're not shadowing a template parameter. 10133 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10134 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10135 PrevR.clear(); 10136 } 10137 10138 // Filter out any other lookup result from an enclosing scope. 10139 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10140 /*AllowInlineNamespace*/false); 10141 10142 // Find the previous declaration and check that we can redeclare it. 10143 NamespaceAliasDecl *Prev = nullptr; 10144 if (PrevR.isSingleResult()) { 10145 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10146 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10147 // We already have an alias with the same name that points to the same 10148 // namespace; check that it matches. 10149 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10150 Prev = AD; 10151 } else if (isVisible(PrevDecl)) { 10152 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10153 << Alias; 10154 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10155 << AD->getNamespace(); 10156 return nullptr; 10157 } 10158 } else if (isVisible(PrevDecl)) { 10159 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10160 ? diag::err_redefinition 10161 : diag::err_redefinition_different_kind; 10162 Diag(AliasLoc, DiagID) << Alias; 10163 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10164 return nullptr; 10165 } 10166 } 10167 10168 // The use of a nested name specifier may trigger deprecation warnings. 10169 DiagnoseUseOfDecl(ND, IdentLoc); 10170 10171 NamespaceAliasDecl *AliasDecl = 10172 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10173 Alias, SS.getWithLocInContext(Context), 10174 IdentLoc, ND); 10175 if (Prev) 10176 AliasDecl->setPreviousDecl(Prev); 10177 10178 PushOnScopeChains(AliasDecl, S); 10179 return AliasDecl; 10180 } 10181 10182 namespace { 10183 struct SpecialMemberExceptionSpecInfo 10184 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10185 SourceLocation Loc; 10186 Sema::ImplicitExceptionSpecification ExceptSpec; 10187 10188 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10189 Sema::CXXSpecialMember CSM, 10190 Sema::InheritedConstructorInfo *ICI, 10191 SourceLocation Loc) 10192 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10193 10194 bool visitBase(CXXBaseSpecifier *Base); 10195 bool visitField(FieldDecl *FD); 10196 10197 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10198 unsigned Quals); 10199 10200 void visitSubobjectCall(Subobject Subobj, 10201 Sema::SpecialMemberOverloadResult SMOR); 10202 }; 10203 } 10204 10205 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10206 auto *RT = Base->getType()->getAs<RecordType>(); 10207 if (!RT) 10208 return false; 10209 10210 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10211 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10212 if (auto *BaseCtor = SMOR.getMethod()) { 10213 visitSubobjectCall(Base, BaseCtor); 10214 return false; 10215 } 10216 10217 visitClassSubobject(BaseClass, Base, 0); 10218 return false; 10219 } 10220 10221 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10222 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10223 Expr *E = FD->getInClassInitializer(); 10224 if (!E) 10225 // FIXME: It's a little wasteful to build and throw away a 10226 // CXXDefaultInitExpr here. 10227 // FIXME: We should have a single context note pointing at Loc, and 10228 // this location should be MD->getLocation() instead, since that's 10229 // the location where we actually use the default init expression. 10230 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10231 if (E) 10232 ExceptSpec.CalledExpr(E); 10233 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10234 ->getAs<RecordType>()) { 10235 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10236 FD->getType().getCVRQualifiers()); 10237 } 10238 return false; 10239 } 10240 10241 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10242 Subobject Subobj, 10243 unsigned Quals) { 10244 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10245 bool IsMutable = Field && Field->isMutable(); 10246 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10247 } 10248 10249 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10250 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10251 // Note, if lookup fails, it doesn't matter what exception specification we 10252 // choose because the special member will be deleted. 10253 if (CXXMethodDecl *MD = SMOR.getMethod()) 10254 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10255 } 10256 10257 static Sema::ImplicitExceptionSpecification 10258 ComputeDefaultedSpecialMemberExceptionSpec( 10259 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10260 Sema::InheritedConstructorInfo *ICI) { 10261 CXXRecordDecl *ClassDecl = MD->getParent(); 10262 10263 // C++ [except.spec]p14: 10264 // An implicitly declared special member function (Clause 12) shall have an 10265 // exception-specification. [...] 10266 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10267 if (ClassDecl->isInvalidDecl()) 10268 return Info.ExceptSpec; 10269 10270 // C++1z [except.spec]p7: 10271 // [Look for exceptions thrown by] a constructor selected [...] to 10272 // initialize a potentially constructed subobject, 10273 // C++1z [except.spec]p8: 10274 // The exception specification for an implicitly-declared destructor, or a 10275 // destructor without a noexcept-specifier, is potentially-throwing if and 10276 // only if any of the destructors for any of its potentially constructed 10277 // subojects is potentially throwing. 10278 // FIXME: We respect the first rule but ignore the "potentially constructed" 10279 // in the second rule to resolve a core issue (no number yet) that would have 10280 // us reject: 10281 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10282 // struct B : A {}; 10283 // struct C : B { void f(); }; 10284 // ... due to giving B::~B() a non-throwing exception specification. 10285 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10286 : Info.VisitAllBases); 10287 10288 return Info.ExceptSpec; 10289 } 10290 10291 namespace { 10292 /// RAII object to register a special member as being currently declared. 10293 struct DeclaringSpecialMember { 10294 Sema &S; 10295 Sema::SpecialMemberDecl D; 10296 Sema::ContextRAII SavedContext; 10297 bool WasAlreadyBeingDeclared; 10298 10299 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10300 : S(S), D(RD, CSM), SavedContext(S, RD) { 10301 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10302 if (WasAlreadyBeingDeclared) 10303 // This almost never happens, but if it does, ensure that our cache 10304 // doesn't contain a stale result. 10305 S.SpecialMemberCache.clear(); 10306 else { 10307 // Register a note to be produced if we encounter an error while 10308 // declaring the special member. 10309 Sema::CodeSynthesisContext Ctx; 10310 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10311 // FIXME: We don't have a location to use here. Using the class's 10312 // location maintains the fiction that we declare all special members 10313 // with the class, but (1) it's not clear that lying about that helps our 10314 // users understand what's going on, and (2) there may be outer contexts 10315 // on the stack (some of which are relevant) and printing them exposes 10316 // our lies. 10317 Ctx.PointOfInstantiation = RD->getLocation(); 10318 Ctx.Entity = RD; 10319 Ctx.SpecialMember = CSM; 10320 S.pushCodeSynthesisContext(Ctx); 10321 } 10322 } 10323 ~DeclaringSpecialMember() { 10324 if (!WasAlreadyBeingDeclared) { 10325 S.SpecialMembersBeingDeclared.erase(D); 10326 S.popCodeSynthesisContext(); 10327 } 10328 } 10329 10330 /// \brief Are we already trying to declare this special member? 10331 bool isAlreadyBeingDeclared() const { 10332 return WasAlreadyBeingDeclared; 10333 } 10334 }; 10335 } 10336 10337 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10338 // Look up any existing declarations, but don't trigger declaration of all 10339 // implicit special members with this name. 10340 DeclarationName Name = FD->getDeclName(); 10341 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10342 ForRedeclaration); 10343 for (auto *D : FD->getParent()->lookup(Name)) 10344 if (auto *Acceptable = R.getAcceptableDecl(D)) 10345 R.addDecl(Acceptable); 10346 R.resolveKind(); 10347 R.suppressDiagnostics(); 10348 10349 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10350 } 10351 10352 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10353 CXXRecordDecl *ClassDecl) { 10354 // C++ [class.ctor]p5: 10355 // A default constructor for a class X is a constructor of class X 10356 // that can be called without an argument. If there is no 10357 // user-declared constructor for class X, a default constructor is 10358 // implicitly declared. An implicitly-declared default constructor 10359 // is an inline public member of its class. 10360 assert(ClassDecl->needsImplicitDefaultConstructor() && 10361 "Should not build implicit default constructor!"); 10362 10363 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10364 if (DSM.isAlreadyBeingDeclared()) 10365 return nullptr; 10366 10367 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10368 CXXDefaultConstructor, 10369 false); 10370 10371 // Create the actual constructor declaration. 10372 CanQualType ClassType 10373 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10374 SourceLocation ClassLoc = ClassDecl->getLocation(); 10375 DeclarationName Name 10376 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10377 DeclarationNameInfo NameInfo(Name, ClassLoc); 10378 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10379 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10380 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10381 /*isImplicitlyDeclared=*/true, Constexpr); 10382 DefaultCon->setAccess(AS_public); 10383 DefaultCon->setDefaulted(); 10384 10385 if (getLangOpts().CUDA) { 10386 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10387 DefaultCon, 10388 /* ConstRHS */ false, 10389 /* Diagnose */ false); 10390 } 10391 10392 // Build an exception specification pointing back at this constructor. 10393 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10394 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10395 10396 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10397 // constructors is easy to compute. 10398 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10399 10400 // Note that we have declared this constructor. 10401 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10402 10403 Scope *S = getScopeForContext(ClassDecl); 10404 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10405 10406 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10407 SetDeclDeleted(DefaultCon, ClassLoc); 10408 10409 if (S) 10410 PushOnScopeChains(DefaultCon, S, false); 10411 ClassDecl->addDecl(DefaultCon); 10412 10413 return DefaultCon; 10414 } 10415 10416 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10417 CXXConstructorDecl *Constructor) { 10418 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10419 !Constructor->doesThisDeclarationHaveABody() && 10420 !Constructor->isDeleted()) && 10421 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10422 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10423 return; 10424 10425 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10426 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10427 10428 SynthesizedFunctionScope Scope(*this, Constructor); 10429 10430 // The exception specification is needed because we are defining the 10431 // function. 10432 ResolveExceptionSpec(CurrentLocation, 10433 Constructor->getType()->castAs<FunctionProtoType>()); 10434 MarkVTableUsed(CurrentLocation, ClassDecl); 10435 10436 // Add a context note for diagnostics produced after this point. 10437 Scope.addContextNote(CurrentLocation); 10438 10439 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10440 Constructor->setInvalidDecl(); 10441 return; 10442 } 10443 10444 SourceLocation Loc = Constructor->getLocEnd().isValid() 10445 ? Constructor->getLocEnd() 10446 : Constructor->getLocation(); 10447 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10448 Constructor->markUsed(Context); 10449 10450 if (ASTMutationListener *L = getASTMutationListener()) { 10451 L->CompletedImplicitDefinition(Constructor); 10452 } 10453 10454 DiagnoseUninitializedFields(*this, Constructor); 10455 } 10456 10457 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10458 // Perform any delayed checks on exception specifications. 10459 CheckDelayedMemberExceptionSpecs(); 10460 } 10461 10462 /// Find or create the fake constructor we synthesize to model constructing an 10463 /// object of a derived class via a constructor of a base class. 10464 CXXConstructorDecl * 10465 Sema::findInheritingConstructor(SourceLocation Loc, 10466 CXXConstructorDecl *BaseCtor, 10467 ConstructorUsingShadowDecl *Shadow) { 10468 CXXRecordDecl *Derived = Shadow->getParent(); 10469 SourceLocation UsingLoc = Shadow->getLocation(); 10470 10471 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10472 // For now we use the name of the base class constructor as a member of the 10473 // derived class to indicate a (fake) inherited constructor name. 10474 DeclarationName Name = BaseCtor->getDeclName(); 10475 10476 // Check to see if we already have a fake constructor for this inherited 10477 // constructor call. 10478 for (NamedDecl *Ctor : Derived->lookup(Name)) 10479 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10480 ->getInheritedConstructor() 10481 .getConstructor(), 10482 BaseCtor)) 10483 return cast<CXXConstructorDecl>(Ctor); 10484 10485 DeclarationNameInfo NameInfo(Name, UsingLoc); 10486 TypeSourceInfo *TInfo = 10487 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10488 FunctionProtoTypeLoc ProtoLoc = 10489 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10490 10491 // Check the inherited constructor is valid and find the list of base classes 10492 // from which it was inherited. 10493 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10494 10495 bool Constexpr = 10496 BaseCtor->isConstexpr() && 10497 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10498 false, BaseCtor, &ICI); 10499 10500 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10501 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10502 BaseCtor->isExplicit(), /*Inline=*/true, 10503 /*ImplicitlyDeclared=*/true, Constexpr, 10504 InheritedConstructor(Shadow, BaseCtor)); 10505 if (Shadow->isInvalidDecl()) 10506 DerivedCtor->setInvalidDecl(); 10507 10508 // Build an unevaluated exception specification for this fake constructor. 10509 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10510 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10511 EPI.ExceptionSpec.Type = EST_Unevaluated; 10512 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10513 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10514 FPT->getParamTypes(), EPI)); 10515 10516 // Build the parameter declarations. 10517 SmallVector<ParmVarDecl *, 16> ParamDecls; 10518 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10519 TypeSourceInfo *TInfo = 10520 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10521 ParmVarDecl *PD = ParmVarDecl::Create( 10522 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10523 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10524 PD->setScopeInfo(0, I); 10525 PD->setImplicit(); 10526 // Ensure attributes are propagated onto parameters (this matters for 10527 // format, pass_object_size, ...). 10528 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10529 ParamDecls.push_back(PD); 10530 ProtoLoc.setParam(I, PD); 10531 } 10532 10533 // Set up the new constructor. 10534 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10535 DerivedCtor->setAccess(BaseCtor->getAccess()); 10536 DerivedCtor->setParams(ParamDecls); 10537 Derived->addDecl(DerivedCtor); 10538 10539 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10540 SetDeclDeleted(DerivedCtor, UsingLoc); 10541 10542 return DerivedCtor; 10543 } 10544 10545 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10546 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10547 Ctor->getInheritedConstructor().getShadowDecl()); 10548 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10549 /*Diagnose*/true); 10550 } 10551 10552 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10553 CXXConstructorDecl *Constructor) { 10554 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10555 assert(Constructor->getInheritedConstructor() && 10556 !Constructor->doesThisDeclarationHaveABody() && 10557 !Constructor->isDeleted()); 10558 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10559 return; 10560 10561 // Initializations are performed "as if by a defaulted default constructor", 10562 // so enter the appropriate scope. 10563 SynthesizedFunctionScope Scope(*this, Constructor); 10564 10565 // The exception specification is needed because we are defining the 10566 // function. 10567 ResolveExceptionSpec(CurrentLocation, 10568 Constructor->getType()->castAs<FunctionProtoType>()); 10569 MarkVTableUsed(CurrentLocation, ClassDecl); 10570 10571 // Add a context note for diagnostics produced after this point. 10572 Scope.addContextNote(CurrentLocation); 10573 10574 ConstructorUsingShadowDecl *Shadow = 10575 Constructor->getInheritedConstructor().getShadowDecl(); 10576 CXXConstructorDecl *InheritedCtor = 10577 Constructor->getInheritedConstructor().getConstructor(); 10578 10579 // [class.inhctor.init]p1: 10580 // initialization proceeds as if a defaulted default constructor is used to 10581 // initialize the D object and each base class subobject from which the 10582 // constructor was inherited 10583 10584 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10585 CXXRecordDecl *RD = Shadow->getParent(); 10586 SourceLocation InitLoc = Shadow->getLocation(); 10587 10588 // Build explicit initializers for all base classes from which the 10589 // constructor was inherited. 10590 SmallVector<CXXCtorInitializer*, 8> Inits; 10591 for (bool VBase : {false, true}) { 10592 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10593 if (B.isVirtual() != VBase) 10594 continue; 10595 10596 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10597 if (!BaseRD) 10598 continue; 10599 10600 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10601 if (!BaseCtor.first) 10602 continue; 10603 10604 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10605 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10606 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10607 10608 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10609 Inits.push_back(new (Context) CXXCtorInitializer( 10610 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10611 SourceLocation())); 10612 } 10613 } 10614 10615 // We now proceed as if for a defaulted default constructor, with the relevant 10616 // initializers replaced. 10617 10618 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 10619 Constructor->setInvalidDecl(); 10620 return; 10621 } 10622 10623 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10624 Constructor->markUsed(Context); 10625 10626 if (ASTMutationListener *L = getASTMutationListener()) { 10627 L->CompletedImplicitDefinition(Constructor); 10628 } 10629 10630 DiagnoseUninitializedFields(*this, Constructor); 10631 } 10632 10633 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10634 // C++ [class.dtor]p2: 10635 // If a class has no user-declared destructor, a destructor is 10636 // declared implicitly. An implicitly-declared destructor is an 10637 // inline public member of its class. 10638 assert(ClassDecl->needsImplicitDestructor()); 10639 10640 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10641 if (DSM.isAlreadyBeingDeclared()) 10642 return nullptr; 10643 10644 // Create the actual destructor declaration. 10645 CanQualType ClassType 10646 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10647 SourceLocation ClassLoc = ClassDecl->getLocation(); 10648 DeclarationName Name 10649 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10650 DeclarationNameInfo NameInfo(Name, ClassLoc); 10651 CXXDestructorDecl *Destructor 10652 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10653 QualType(), nullptr, /*isInline=*/true, 10654 /*isImplicitlyDeclared=*/true); 10655 Destructor->setAccess(AS_public); 10656 Destructor->setDefaulted(); 10657 10658 if (getLangOpts().CUDA) { 10659 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10660 Destructor, 10661 /* ConstRHS */ false, 10662 /* Diagnose */ false); 10663 } 10664 10665 // Build an exception specification pointing back at this destructor. 10666 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10667 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10668 10669 // We don't need to use SpecialMemberIsTrivial here; triviality for 10670 // destructors is easy to compute. 10671 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10672 10673 // Note that we have declared this destructor. 10674 ++ASTContext::NumImplicitDestructorsDeclared; 10675 10676 Scope *S = getScopeForContext(ClassDecl); 10677 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10678 10679 // We can't check whether an implicit destructor is deleted before we complete 10680 // the definition of the class, because its validity depends on the alignment 10681 // of the class. We'll check this from ActOnFields once the class is complete. 10682 if (ClassDecl->isCompleteDefinition() && 10683 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10684 SetDeclDeleted(Destructor, ClassLoc); 10685 10686 // Introduce this destructor into its scope. 10687 if (S) 10688 PushOnScopeChains(Destructor, S, false); 10689 ClassDecl->addDecl(Destructor); 10690 10691 return Destructor; 10692 } 10693 10694 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10695 CXXDestructorDecl *Destructor) { 10696 assert((Destructor->isDefaulted() && 10697 !Destructor->doesThisDeclarationHaveABody() && 10698 !Destructor->isDeleted()) && 10699 "DefineImplicitDestructor - call it for implicit default dtor"); 10700 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 10701 return; 10702 10703 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10704 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10705 10706 SynthesizedFunctionScope Scope(*this, Destructor); 10707 10708 // The exception specification is needed because we are defining the 10709 // function. 10710 ResolveExceptionSpec(CurrentLocation, 10711 Destructor->getType()->castAs<FunctionProtoType>()); 10712 MarkVTableUsed(CurrentLocation, ClassDecl); 10713 10714 // Add a context note for diagnostics produced after this point. 10715 Scope.addContextNote(CurrentLocation); 10716 10717 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10718 Destructor->getParent()); 10719 10720 if (CheckDestructor(Destructor)) { 10721 Destructor->setInvalidDecl(); 10722 return; 10723 } 10724 10725 SourceLocation Loc = Destructor->getLocEnd().isValid() 10726 ? Destructor->getLocEnd() 10727 : Destructor->getLocation(); 10728 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10729 Destructor->markUsed(Context); 10730 10731 if (ASTMutationListener *L = getASTMutationListener()) { 10732 L->CompletedImplicitDefinition(Destructor); 10733 } 10734 } 10735 10736 /// \brief Perform any semantic analysis which needs to be delayed until all 10737 /// pending class member declarations have been parsed. 10738 void Sema::ActOnFinishCXXMemberDecls() { 10739 // If the context is an invalid C++ class, just suppress these checks. 10740 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10741 if (Record->isInvalidDecl()) { 10742 DelayedDefaultedMemberExceptionSpecs.clear(); 10743 DelayedExceptionSpecChecks.clear(); 10744 return; 10745 } 10746 checkForMultipleExportedDefaultConstructors(*this, Record); 10747 } 10748 } 10749 10750 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10751 referenceDLLExportedClassMethods(); 10752 } 10753 10754 void Sema::referenceDLLExportedClassMethods() { 10755 if (!DelayedDllExportClasses.empty()) { 10756 // Calling ReferenceDllExportedMethods might cause the current function to 10757 // be called again, so use a local copy of DelayedDllExportClasses. 10758 SmallVector<CXXRecordDecl *, 4> WorkList; 10759 std::swap(DelayedDllExportClasses, WorkList); 10760 for (CXXRecordDecl *Class : WorkList) 10761 ReferenceDllExportedMethods(*this, Class); 10762 } 10763 } 10764 10765 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10766 CXXDestructorDecl *Destructor) { 10767 assert(getLangOpts().CPlusPlus11 && 10768 "adjusting dtor exception specs was introduced in c++11"); 10769 10770 // C++11 [class.dtor]p3: 10771 // A declaration of a destructor that does not have an exception- 10772 // specification is implicitly considered to have the same exception- 10773 // specification as an implicit declaration. 10774 const FunctionProtoType *DtorType = Destructor->getType()-> 10775 getAs<FunctionProtoType>(); 10776 if (DtorType->hasExceptionSpec()) 10777 return; 10778 10779 // Replace the destructor's type, building off the existing one. Fortunately, 10780 // the only thing of interest in the destructor type is its extended info. 10781 // The return and arguments are fixed. 10782 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10783 EPI.ExceptionSpec.Type = EST_Unevaluated; 10784 EPI.ExceptionSpec.SourceDecl = Destructor; 10785 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10786 10787 // FIXME: If the destructor has a body that could throw, and the newly created 10788 // spec doesn't allow exceptions, we should emit a warning, because this 10789 // change in behavior can break conforming C++03 programs at runtime. 10790 // However, we don't have a body or an exception specification yet, so it 10791 // needs to be done somewhere else. 10792 } 10793 10794 namespace { 10795 /// \brief An abstract base class for all helper classes used in building the 10796 // copy/move operators. These classes serve as factory functions and help us 10797 // avoid using the same Expr* in the AST twice. 10798 class ExprBuilder { 10799 ExprBuilder(const ExprBuilder&) = delete; 10800 ExprBuilder &operator=(const ExprBuilder&) = delete; 10801 10802 protected: 10803 static Expr *assertNotNull(Expr *E) { 10804 assert(E && "Expression construction must not fail."); 10805 return E; 10806 } 10807 10808 public: 10809 ExprBuilder() {} 10810 virtual ~ExprBuilder() {} 10811 10812 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10813 }; 10814 10815 class RefBuilder: public ExprBuilder { 10816 VarDecl *Var; 10817 QualType VarType; 10818 10819 public: 10820 Expr *build(Sema &S, SourceLocation Loc) const override { 10821 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10822 } 10823 10824 RefBuilder(VarDecl *Var, QualType VarType) 10825 : Var(Var), VarType(VarType) {} 10826 }; 10827 10828 class ThisBuilder: public ExprBuilder { 10829 public: 10830 Expr *build(Sema &S, SourceLocation Loc) const override { 10831 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 10832 } 10833 }; 10834 10835 class CastBuilder: public ExprBuilder { 10836 const ExprBuilder &Builder; 10837 QualType Type; 10838 ExprValueKind Kind; 10839 const CXXCastPath &Path; 10840 10841 public: 10842 Expr *build(Sema &S, SourceLocation Loc) const override { 10843 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 10844 CK_UncheckedDerivedToBase, Kind, 10845 &Path).get()); 10846 } 10847 10848 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 10849 const CXXCastPath &Path) 10850 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 10851 }; 10852 10853 class DerefBuilder: public ExprBuilder { 10854 const ExprBuilder &Builder; 10855 10856 public: 10857 Expr *build(Sema &S, SourceLocation Loc) const override { 10858 return assertNotNull( 10859 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 10860 } 10861 10862 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10863 }; 10864 10865 class MemberBuilder: public ExprBuilder { 10866 const ExprBuilder &Builder; 10867 QualType Type; 10868 CXXScopeSpec SS; 10869 bool IsArrow; 10870 LookupResult &MemberLookup; 10871 10872 public: 10873 Expr *build(Sema &S, SourceLocation Loc) const override { 10874 return assertNotNull(S.BuildMemberReferenceExpr( 10875 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 10876 nullptr, MemberLookup, nullptr, nullptr).get()); 10877 } 10878 10879 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 10880 LookupResult &MemberLookup) 10881 : Builder(Builder), Type(Type), IsArrow(IsArrow), 10882 MemberLookup(MemberLookup) {} 10883 }; 10884 10885 class MoveCastBuilder: public ExprBuilder { 10886 const ExprBuilder &Builder; 10887 10888 public: 10889 Expr *build(Sema &S, SourceLocation Loc) const override { 10890 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 10891 } 10892 10893 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10894 }; 10895 10896 class LvalueConvBuilder: public ExprBuilder { 10897 const ExprBuilder &Builder; 10898 10899 public: 10900 Expr *build(Sema &S, SourceLocation Loc) const override { 10901 return assertNotNull( 10902 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 10903 } 10904 10905 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10906 }; 10907 10908 class SubscriptBuilder: public ExprBuilder { 10909 const ExprBuilder &Base; 10910 const ExprBuilder &Index; 10911 10912 public: 10913 Expr *build(Sema &S, SourceLocation Loc) const override { 10914 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 10915 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 10916 } 10917 10918 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 10919 : Base(Base), Index(Index) {} 10920 }; 10921 10922 } // end anonymous namespace 10923 10924 /// When generating a defaulted copy or move assignment operator, if a field 10925 /// should be copied with __builtin_memcpy rather than via explicit assignments, 10926 /// do so. This optimization only applies for arrays of scalars, and for arrays 10927 /// of class type where the selected copy/move-assignment operator is trivial. 10928 static StmtResult 10929 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 10930 const ExprBuilder &ToB, const ExprBuilder &FromB) { 10931 // Compute the size of the memory buffer to be copied. 10932 QualType SizeType = S.Context.getSizeType(); 10933 llvm::APInt Size(S.Context.getTypeSize(SizeType), 10934 S.Context.getTypeSizeInChars(T).getQuantity()); 10935 10936 // Take the address of the field references for "from" and "to". We 10937 // directly construct UnaryOperators here because semantic analysis 10938 // does not permit us to take the address of an xvalue. 10939 Expr *From = FromB.build(S, Loc); 10940 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 10941 S.Context.getPointerType(From->getType()), 10942 VK_RValue, OK_Ordinary, Loc); 10943 Expr *To = ToB.build(S, Loc); 10944 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 10945 S.Context.getPointerType(To->getType()), 10946 VK_RValue, OK_Ordinary, Loc); 10947 10948 const Type *E = T->getBaseElementTypeUnsafe(); 10949 bool NeedsCollectableMemCpy = 10950 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 10951 10952 // Create a reference to the __builtin_objc_memmove_collectable function 10953 StringRef MemCpyName = NeedsCollectableMemCpy ? 10954 "__builtin_objc_memmove_collectable" : 10955 "__builtin_memcpy"; 10956 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 10957 Sema::LookupOrdinaryName); 10958 S.LookupName(R, S.TUScope, true); 10959 10960 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 10961 if (!MemCpy) 10962 // Something went horribly wrong earlier, and we will have complained 10963 // about it. 10964 return StmtError(); 10965 10966 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 10967 VK_RValue, Loc, nullptr); 10968 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 10969 10970 Expr *CallArgs[] = { 10971 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 10972 }; 10973 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 10974 Loc, CallArgs, Loc); 10975 10976 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 10977 return Call.getAs<Stmt>(); 10978 } 10979 10980 /// \brief Builds a statement that copies/moves the given entity from \p From to 10981 /// \c To. 10982 /// 10983 /// This routine is used to copy/move the members of a class with an 10984 /// implicitly-declared copy/move assignment operator. When the entities being 10985 /// copied are arrays, this routine builds for loops to copy them. 10986 /// 10987 /// \param S The Sema object used for type-checking. 10988 /// 10989 /// \param Loc The location where the implicit copy/move is being generated. 10990 /// 10991 /// \param T The type of the expressions being copied/moved. Both expressions 10992 /// must have this type. 10993 /// 10994 /// \param To The expression we are copying/moving to. 10995 /// 10996 /// \param From The expression we are copying/moving from. 10997 /// 10998 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 10999 /// Otherwise, it's a non-static member subobject. 11000 /// 11001 /// \param Copying Whether we're copying or moving. 11002 /// 11003 /// \param Depth Internal parameter recording the depth of the recursion. 11004 /// 11005 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11006 /// if a memcpy should be used instead. 11007 static StmtResult 11008 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11009 const ExprBuilder &To, const ExprBuilder &From, 11010 bool CopyingBaseSubobject, bool Copying, 11011 unsigned Depth = 0) { 11012 // C++11 [class.copy]p28: 11013 // Each subobject is assigned in the manner appropriate to its type: 11014 // 11015 // - if the subobject is of class type, as if by a call to operator= with 11016 // the subobject as the object expression and the corresponding 11017 // subobject of x as a single function argument (as if by explicit 11018 // qualification; that is, ignoring any possible virtual overriding 11019 // functions in more derived classes); 11020 // 11021 // C++03 [class.copy]p13: 11022 // - if the subobject is of class type, the copy assignment operator for 11023 // the class is used (as if by explicit qualification; that is, 11024 // ignoring any possible virtual overriding functions in more derived 11025 // classes); 11026 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11027 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11028 11029 // Look for operator=. 11030 DeclarationName Name 11031 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11032 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11033 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11034 11035 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11036 // operator. 11037 if (!S.getLangOpts().CPlusPlus11) { 11038 LookupResult::Filter F = OpLookup.makeFilter(); 11039 while (F.hasNext()) { 11040 NamedDecl *D = F.next(); 11041 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11042 if (Method->isCopyAssignmentOperator() || 11043 (!Copying && Method->isMoveAssignmentOperator())) 11044 continue; 11045 11046 F.erase(); 11047 } 11048 F.done(); 11049 } 11050 11051 // Suppress the protected check (C++ [class.protected]) for each of the 11052 // assignment operators we found. This strange dance is required when 11053 // we're assigning via a base classes's copy-assignment operator. To 11054 // ensure that we're getting the right base class subobject (without 11055 // ambiguities), we need to cast "this" to that subobject type; to 11056 // ensure that we don't go through the virtual call mechanism, we need 11057 // to qualify the operator= name with the base class (see below). However, 11058 // this means that if the base class has a protected copy assignment 11059 // operator, the protected member access check will fail. So, we 11060 // rewrite "protected" access to "public" access in this case, since we 11061 // know by construction that we're calling from a derived class. 11062 if (CopyingBaseSubobject) { 11063 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11064 L != LEnd; ++L) { 11065 if (L.getAccess() == AS_protected) 11066 L.setAccess(AS_public); 11067 } 11068 } 11069 11070 // Create the nested-name-specifier that will be used to qualify the 11071 // reference to operator=; this is required to suppress the virtual 11072 // call mechanism. 11073 CXXScopeSpec SS; 11074 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11075 SS.MakeTrivial(S.Context, 11076 NestedNameSpecifier::Create(S.Context, nullptr, false, 11077 CanonicalT), 11078 Loc); 11079 11080 // Create the reference to operator=. 11081 ExprResult OpEqualRef 11082 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11083 SS, /*TemplateKWLoc=*/SourceLocation(), 11084 /*FirstQualifierInScope=*/nullptr, 11085 OpLookup, 11086 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11087 /*SuppressQualifierCheck=*/true); 11088 if (OpEqualRef.isInvalid()) 11089 return StmtError(); 11090 11091 // Build the call to the assignment operator. 11092 11093 Expr *FromInst = From.build(S, Loc); 11094 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11095 OpEqualRef.getAs<Expr>(), 11096 Loc, FromInst, Loc); 11097 if (Call.isInvalid()) 11098 return StmtError(); 11099 11100 // If we built a call to a trivial 'operator=' while copying an array, 11101 // bail out. We'll replace the whole shebang with a memcpy. 11102 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11103 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11104 return StmtResult((Stmt*)nullptr); 11105 11106 // Convert to an expression-statement, and clean up any produced 11107 // temporaries. 11108 return S.ActOnExprStmt(Call); 11109 } 11110 11111 // - if the subobject is of scalar type, the built-in assignment 11112 // operator is used. 11113 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11114 if (!ArrayTy) { 11115 ExprResult Assignment = S.CreateBuiltinBinOp( 11116 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11117 if (Assignment.isInvalid()) 11118 return StmtError(); 11119 return S.ActOnExprStmt(Assignment); 11120 } 11121 11122 // - if the subobject is an array, each element is assigned, in the 11123 // manner appropriate to the element type; 11124 11125 // Construct a loop over the array bounds, e.g., 11126 // 11127 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11128 // 11129 // that will copy each of the array elements. 11130 QualType SizeType = S.Context.getSizeType(); 11131 11132 // Create the iteration variable. 11133 IdentifierInfo *IterationVarName = nullptr; 11134 { 11135 SmallString<8> Str; 11136 llvm::raw_svector_ostream OS(Str); 11137 OS << "__i" << Depth; 11138 IterationVarName = &S.Context.Idents.get(OS.str()); 11139 } 11140 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11141 IterationVarName, SizeType, 11142 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11143 SC_None); 11144 11145 // Initialize the iteration variable to zero. 11146 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11147 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11148 11149 // Creates a reference to the iteration variable. 11150 RefBuilder IterationVarRef(IterationVar, SizeType); 11151 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11152 11153 // Create the DeclStmt that holds the iteration variable. 11154 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11155 11156 // Subscript the "from" and "to" expressions with the iteration variable. 11157 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11158 MoveCastBuilder FromIndexMove(FromIndexCopy); 11159 const ExprBuilder *FromIndex; 11160 if (Copying) 11161 FromIndex = &FromIndexCopy; 11162 else 11163 FromIndex = &FromIndexMove; 11164 11165 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11166 11167 // Build the copy/move for an individual element of the array. 11168 StmtResult Copy = 11169 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11170 ToIndex, *FromIndex, CopyingBaseSubobject, 11171 Copying, Depth + 1); 11172 // Bail out if copying fails or if we determined that we should use memcpy. 11173 if (Copy.isInvalid() || !Copy.get()) 11174 return Copy; 11175 11176 // Create the comparison against the array bound. 11177 llvm::APInt Upper 11178 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11179 Expr *Comparison 11180 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11181 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11182 BO_NE, S.Context.BoolTy, 11183 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11184 11185 // Create the pre-increment of the iteration variable. 11186 Expr *Increment 11187 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 11188 SizeType, VK_LValue, OK_Ordinary, Loc); 11189 11190 // Construct the loop that copies all elements of this array. 11191 return S.ActOnForStmt( 11192 Loc, Loc, InitStmt, 11193 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11194 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11195 } 11196 11197 static StmtResult 11198 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11199 const ExprBuilder &To, const ExprBuilder &From, 11200 bool CopyingBaseSubobject, bool Copying) { 11201 // Maybe we should use a memcpy? 11202 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11203 T.isTriviallyCopyableType(S.Context)) 11204 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11205 11206 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11207 CopyingBaseSubobject, 11208 Copying, 0)); 11209 11210 // If we ended up picking a trivial assignment operator for an array of a 11211 // non-trivially-copyable class type, just emit a memcpy. 11212 if (!Result.isInvalid() && !Result.get()) 11213 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11214 11215 return Result; 11216 } 11217 11218 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11219 // Note: The following rules are largely analoguous to the copy 11220 // constructor rules. Note that virtual bases are not taken into account 11221 // for determining the argument type of the operator. Note also that 11222 // operators taking an object instead of a reference are allowed. 11223 assert(ClassDecl->needsImplicitCopyAssignment()); 11224 11225 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11226 if (DSM.isAlreadyBeingDeclared()) 11227 return nullptr; 11228 11229 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11230 QualType RetType = Context.getLValueReferenceType(ArgType); 11231 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11232 if (Const) 11233 ArgType = ArgType.withConst(); 11234 ArgType = Context.getLValueReferenceType(ArgType); 11235 11236 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11237 CXXCopyAssignment, 11238 Const); 11239 11240 // An implicitly-declared copy assignment operator is an inline public 11241 // member of its class. 11242 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11243 SourceLocation ClassLoc = ClassDecl->getLocation(); 11244 DeclarationNameInfo NameInfo(Name, ClassLoc); 11245 CXXMethodDecl *CopyAssignment = 11246 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11247 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11248 /*isInline=*/true, Constexpr, SourceLocation()); 11249 CopyAssignment->setAccess(AS_public); 11250 CopyAssignment->setDefaulted(); 11251 CopyAssignment->setImplicit(); 11252 11253 if (getLangOpts().CUDA) { 11254 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11255 CopyAssignment, 11256 /* ConstRHS */ Const, 11257 /* Diagnose */ false); 11258 } 11259 11260 // Build an exception specification pointing back at this member. 11261 FunctionProtoType::ExtProtoInfo EPI = 11262 getImplicitMethodEPI(*this, CopyAssignment); 11263 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11264 11265 // Add the parameter to the operator. 11266 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11267 ClassLoc, ClassLoc, 11268 /*Id=*/nullptr, ArgType, 11269 /*TInfo=*/nullptr, SC_None, 11270 nullptr); 11271 CopyAssignment->setParams(FromParam); 11272 11273 CopyAssignment->setTrivial( 11274 ClassDecl->needsOverloadResolutionForCopyAssignment() 11275 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11276 : ClassDecl->hasTrivialCopyAssignment()); 11277 11278 // Note that we have added this copy-assignment operator. 11279 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11280 11281 Scope *S = getScopeForContext(ClassDecl); 11282 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11283 11284 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11285 SetDeclDeleted(CopyAssignment, ClassLoc); 11286 11287 if (S) 11288 PushOnScopeChains(CopyAssignment, S, false); 11289 ClassDecl->addDecl(CopyAssignment); 11290 11291 return CopyAssignment; 11292 } 11293 11294 /// Diagnose an implicit copy operation for a class which is odr-used, but 11295 /// which is deprecated because the class has a user-declared copy constructor, 11296 /// copy assignment operator, or destructor. 11297 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11298 assert(CopyOp->isImplicit()); 11299 11300 CXXRecordDecl *RD = CopyOp->getParent(); 11301 CXXMethodDecl *UserDeclaredOperation = nullptr; 11302 11303 // In Microsoft mode, assignment operations don't affect constructors and 11304 // vice versa. 11305 if (RD->hasUserDeclaredDestructor()) { 11306 UserDeclaredOperation = RD->getDestructor(); 11307 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11308 RD->hasUserDeclaredCopyConstructor() && 11309 !S.getLangOpts().MSVCCompat) { 11310 // Find any user-declared copy constructor. 11311 for (auto *I : RD->ctors()) { 11312 if (I->isCopyConstructor()) { 11313 UserDeclaredOperation = I; 11314 break; 11315 } 11316 } 11317 assert(UserDeclaredOperation); 11318 } else if (isa<CXXConstructorDecl>(CopyOp) && 11319 RD->hasUserDeclaredCopyAssignment() && 11320 !S.getLangOpts().MSVCCompat) { 11321 // Find any user-declared move assignment operator. 11322 for (auto *I : RD->methods()) { 11323 if (I->isCopyAssignmentOperator()) { 11324 UserDeclaredOperation = I; 11325 break; 11326 } 11327 } 11328 assert(UserDeclaredOperation); 11329 } 11330 11331 if (UserDeclaredOperation) { 11332 S.Diag(UserDeclaredOperation->getLocation(), 11333 diag::warn_deprecated_copy_operation) 11334 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11335 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11336 } 11337 } 11338 11339 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11340 CXXMethodDecl *CopyAssignOperator) { 11341 assert((CopyAssignOperator->isDefaulted() && 11342 CopyAssignOperator->isOverloadedOperator() && 11343 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11344 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11345 !CopyAssignOperator->isDeleted()) && 11346 "DefineImplicitCopyAssignment called for wrong function"); 11347 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11348 return; 11349 11350 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11351 if (ClassDecl->isInvalidDecl()) { 11352 CopyAssignOperator->setInvalidDecl(); 11353 return; 11354 } 11355 11356 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11357 11358 // The exception specification is needed because we are defining the 11359 // function. 11360 ResolveExceptionSpec(CurrentLocation, 11361 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11362 11363 // Add a context note for diagnostics produced after this point. 11364 Scope.addContextNote(CurrentLocation); 11365 11366 // C++11 [class.copy]p18: 11367 // The [definition of an implicitly declared copy assignment operator] is 11368 // deprecated if the class has a user-declared copy constructor or a 11369 // user-declared destructor. 11370 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11371 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11372 11373 // C++0x [class.copy]p30: 11374 // The implicitly-defined or explicitly-defaulted copy assignment operator 11375 // for a non-union class X performs memberwise copy assignment of its 11376 // subobjects. The direct base classes of X are assigned first, in the 11377 // order of their declaration in the base-specifier-list, and then the 11378 // immediate non-static data members of X are assigned, in the order in 11379 // which they were declared in the class definition. 11380 11381 // The statements that form the synthesized function body. 11382 SmallVector<Stmt*, 8> Statements; 11383 11384 // The parameter for the "other" object, which we are copying from. 11385 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11386 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11387 QualType OtherRefType = Other->getType(); 11388 if (const LValueReferenceType *OtherRef 11389 = OtherRefType->getAs<LValueReferenceType>()) { 11390 OtherRefType = OtherRef->getPointeeType(); 11391 OtherQuals = OtherRefType.getQualifiers(); 11392 } 11393 11394 // Our location for everything implicitly-generated. 11395 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11396 ? CopyAssignOperator->getLocEnd() 11397 : CopyAssignOperator->getLocation(); 11398 11399 // Builds a DeclRefExpr for the "other" object. 11400 RefBuilder OtherRef(Other, OtherRefType); 11401 11402 // Builds the "this" pointer. 11403 ThisBuilder This; 11404 11405 // Assign base classes. 11406 bool Invalid = false; 11407 for (auto &Base : ClassDecl->bases()) { 11408 // Form the assignment: 11409 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11410 QualType BaseType = Base.getType().getUnqualifiedType(); 11411 if (!BaseType->isRecordType()) { 11412 Invalid = true; 11413 continue; 11414 } 11415 11416 CXXCastPath BasePath; 11417 BasePath.push_back(&Base); 11418 11419 // Construct the "from" expression, which is an implicit cast to the 11420 // appropriately-qualified base type. 11421 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11422 VK_LValue, BasePath); 11423 11424 // Dereference "this". 11425 DerefBuilder DerefThis(This); 11426 CastBuilder To(DerefThis, 11427 Context.getCVRQualifiedType( 11428 BaseType, CopyAssignOperator->getTypeQualifiers()), 11429 VK_LValue, BasePath); 11430 11431 // Build the copy. 11432 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11433 To, From, 11434 /*CopyingBaseSubobject=*/true, 11435 /*Copying=*/true); 11436 if (Copy.isInvalid()) { 11437 CopyAssignOperator->setInvalidDecl(); 11438 return; 11439 } 11440 11441 // Success! Record the copy. 11442 Statements.push_back(Copy.getAs<Expr>()); 11443 } 11444 11445 // Assign non-static members. 11446 for (auto *Field : ClassDecl->fields()) { 11447 // FIXME: We should form some kind of AST representation for the implied 11448 // memcpy in a union copy operation. 11449 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11450 continue; 11451 11452 if (Field->isInvalidDecl()) { 11453 Invalid = true; 11454 continue; 11455 } 11456 11457 // Check for members of reference type; we can't copy those. 11458 if (Field->getType()->isReferenceType()) { 11459 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11460 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11461 Diag(Field->getLocation(), diag::note_declared_at); 11462 Invalid = true; 11463 continue; 11464 } 11465 11466 // Check for members of const-qualified, non-class type. 11467 QualType BaseType = Context.getBaseElementType(Field->getType()); 11468 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11469 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11470 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11471 Diag(Field->getLocation(), diag::note_declared_at); 11472 Invalid = true; 11473 continue; 11474 } 11475 11476 // Suppress assigning zero-width bitfields. 11477 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11478 continue; 11479 11480 QualType FieldType = Field->getType().getNonReferenceType(); 11481 if (FieldType->isIncompleteArrayType()) { 11482 assert(ClassDecl->hasFlexibleArrayMember() && 11483 "Incomplete array type is not valid"); 11484 continue; 11485 } 11486 11487 // Build references to the field in the object we're copying from and to. 11488 CXXScopeSpec SS; // Intentionally empty 11489 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11490 LookupMemberName); 11491 MemberLookup.addDecl(Field); 11492 MemberLookup.resolveKind(); 11493 11494 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11495 11496 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11497 11498 // Build the copy of this field. 11499 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11500 To, From, 11501 /*CopyingBaseSubobject=*/false, 11502 /*Copying=*/true); 11503 if (Copy.isInvalid()) { 11504 CopyAssignOperator->setInvalidDecl(); 11505 return; 11506 } 11507 11508 // Success! Record the copy. 11509 Statements.push_back(Copy.getAs<Stmt>()); 11510 } 11511 11512 if (!Invalid) { 11513 // Add a "return *this;" 11514 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11515 11516 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11517 if (Return.isInvalid()) 11518 Invalid = true; 11519 else 11520 Statements.push_back(Return.getAs<Stmt>()); 11521 } 11522 11523 if (Invalid) { 11524 CopyAssignOperator->setInvalidDecl(); 11525 return; 11526 } 11527 11528 StmtResult Body; 11529 { 11530 CompoundScopeRAII CompoundScope(*this); 11531 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11532 /*isStmtExpr=*/false); 11533 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11534 } 11535 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11536 CopyAssignOperator->markUsed(Context); 11537 11538 if (ASTMutationListener *L = getASTMutationListener()) { 11539 L->CompletedImplicitDefinition(CopyAssignOperator); 11540 } 11541 } 11542 11543 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11544 assert(ClassDecl->needsImplicitMoveAssignment()); 11545 11546 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11547 if (DSM.isAlreadyBeingDeclared()) 11548 return nullptr; 11549 11550 // Note: The following rules are largely analoguous to the move 11551 // constructor rules. 11552 11553 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11554 QualType RetType = Context.getLValueReferenceType(ArgType); 11555 ArgType = Context.getRValueReferenceType(ArgType); 11556 11557 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11558 CXXMoveAssignment, 11559 false); 11560 11561 // An implicitly-declared move assignment operator is an inline public 11562 // member of its class. 11563 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11564 SourceLocation ClassLoc = ClassDecl->getLocation(); 11565 DeclarationNameInfo NameInfo(Name, ClassLoc); 11566 CXXMethodDecl *MoveAssignment = 11567 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11568 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11569 /*isInline=*/true, Constexpr, SourceLocation()); 11570 MoveAssignment->setAccess(AS_public); 11571 MoveAssignment->setDefaulted(); 11572 MoveAssignment->setImplicit(); 11573 11574 if (getLangOpts().CUDA) { 11575 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11576 MoveAssignment, 11577 /* ConstRHS */ false, 11578 /* Diagnose */ false); 11579 } 11580 11581 // Build an exception specification pointing back at this member. 11582 FunctionProtoType::ExtProtoInfo EPI = 11583 getImplicitMethodEPI(*this, MoveAssignment); 11584 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11585 11586 // Add the parameter to the operator. 11587 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11588 ClassLoc, ClassLoc, 11589 /*Id=*/nullptr, ArgType, 11590 /*TInfo=*/nullptr, SC_None, 11591 nullptr); 11592 MoveAssignment->setParams(FromParam); 11593 11594 MoveAssignment->setTrivial( 11595 ClassDecl->needsOverloadResolutionForMoveAssignment() 11596 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11597 : ClassDecl->hasTrivialMoveAssignment()); 11598 11599 // Note that we have added this copy-assignment operator. 11600 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11601 11602 Scope *S = getScopeForContext(ClassDecl); 11603 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11604 11605 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11606 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11607 SetDeclDeleted(MoveAssignment, ClassLoc); 11608 } 11609 11610 if (S) 11611 PushOnScopeChains(MoveAssignment, S, false); 11612 ClassDecl->addDecl(MoveAssignment); 11613 11614 return MoveAssignment; 11615 } 11616 11617 /// Check if we're implicitly defining a move assignment operator for a class 11618 /// with virtual bases. Such a move assignment might move-assign the virtual 11619 /// base multiple times. 11620 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11621 SourceLocation CurrentLocation) { 11622 assert(!Class->isDependentContext() && "should not define dependent move"); 11623 11624 // Only a virtual base could get implicitly move-assigned multiple times. 11625 // Only a non-trivial move assignment can observe this. We only want to 11626 // diagnose if we implicitly define an assignment operator that assigns 11627 // two base classes, both of which move-assign the same virtual base. 11628 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11629 Class->getNumBases() < 2) 11630 return; 11631 11632 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11633 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11634 VBaseMap VBases; 11635 11636 for (auto &BI : Class->bases()) { 11637 Worklist.push_back(&BI); 11638 while (!Worklist.empty()) { 11639 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11640 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11641 11642 // If the base has no non-trivial move assignment operators, 11643 // we don't care about moves from it. 11644 if (!Base->hasNonTrivialMoveAssignment()) 11645 continue; 11646 11647 // If there's nothing virtual here, skip it. 11648 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11649 continue; 11650 11651 // If we're not actually going to call a move assignment for this base, 11652 // or the selected move assignment is trivial, skip it. 11653 Sema::SpecialMemberOverloadResult SMOR = 11654 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11655 /*ConstArg*/false, /*VolatileArg*/false, 11656 /*RValueThis*/true, /*ConstThis*/false, 11657 /*VolatileThis*/false); 11658 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 11659 !SMOR.getMethod()->isMoveAssignmentOperator()) 11660 continue; 11661 11662 if (BaseSpec->isVirtual()) { 11663 // We're going to move-assign this virtual base, and its move 11664 // assignment operator is not trivial. If this can happen for 11665 // multiple distinct direct bases of Class, diagnose it. (If it 11666 // only happens in one base, we'll diagnose it when synthesizing 11667 // that base class's move assignment operator.) 11668 CXXBaseSpecifier *&Existing = 11669 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11670 .first->second; 11671 if (Existing && Existing != &BI) { 11672 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11673 << Class << Base; 11674 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11675 << (Base->getCanonicalDecl() == 11676 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11677 << Base << Existing->getType() << Existing->getSourceRange(); 11678 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11679 << (Base->getCanonicalDecl() == 11680 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11681 << Base << BI.getType() << BaseSpec->getSourceRange(); 11682 11683 // Only diagnose each vbase once. 11684 Existing = nullptr; 11685 } 11686 } else { 11687 // Only walk over bases that have defaulted move assignment operators. 11688 // We assume that any user-provided move assignment operator handles 11689 // the multiple-moves-of-vbase case itself somehow. 11690 if (!SMOR.getMethod()->isDefaulted()) 11691 continue; 11692 11693 // We're going to move the base classes of Base. Add them to the list. 11694 for (auto &BI : Base->bases()) 11695 Worklist.push_back(&BI); 11696 } 11697 } 11698 } 11699 } 11700 11701 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11702 CXXMethodDecl *MoveAssignOperator) { 11703 assert((MoveAssignOperator->isDefaulted() && 11704 MoveAssignOperator->isOverloadedOperator() && 11705 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11706 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11707 !MoveAssignOperator->isDeleted()) && 11708 "DefineImplicitMoveAssignment called for wrong function"); 11709 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 11710 return; 11711 11712 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11713 if (ClassDecl->isInvalidDecl()) { 11714 MoveAssignOperator->setInvalidDecl(); 11715 return; 11716 } 11717 11718 // C++0x [class.copy]p28: 11719 // The implicitly-defined or move assignment operator for a non-union class 11720 // X performs memberwise move assignment of its subobjects. The direct base 11721 // classes of X are assigned first, in the order of their declaration in the 11722 // base-specifier-list, and then the immediate non-static data members of X 11723 // are assigned, in the order in which they were declared in the class 11724 // definition. 11725 11726 // Issue a warning if our implicit move assignment operator will move 11727 // from a virtual base more than once. 11728 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11729 11730 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11731 11732 // The exception specification is needed because we are defining the 11733 // function. 11734 ResolveExceptionSpec(CurrentLocation, 11735 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11736 11737 // Add a context note for diagnostics produced after this point. 11738 Scope.addContextNote(CurrentLocation); 11739 11740 // The statements that form the synthesized function body. 11741 SmallVector<Stmt*, 8> Statements; 11742 11743 // The parameter for the "other" object, which we are move from. 11744 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11745 QualType OtherRefType = Other->getType()-> 11746 getAs<RValueReferenceType>()->getPointeeType(); 11747 assert(!OtherRefType.getQualifiers() && 11748 "Bad argument type of defaulted move assignment"); 11749 11750 // Our location for everything implicitly-generated. 11751 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11752 ? MoveAssignOperator->getLocEnd() 11753 : MoveAssignOperator->getLocation(); 11754 11755 // Builds a reference to the "other" object. 11756 RefBuilder OtherRef(Other, OtherRefType); 11757 // Cast to rvalue. 11758 MoveCastBuilder MoveOther(OtherRef); 11759 11760 // Builds the "this" pointer. 11761 ThisBuilder This; 11762 11763 // Assign base classes. 11764 bool Invalid = false; 11765 for (auto &Base : ClassDecl->bases()) { 11766 // C++11 [class.copy]p28: 11767 // It is unspecified whether subobjects representing virtual base classes 11768 // are assigned more than once by the implicitly-defined copy assignment 11769 // operator. 11770 // FIXME: Do not assign to a vbase that will be assigned by some other base 11771 // class. For a move-assignment, this can result in the vbase being moved 11772 // multiple times. 11773 11774 // Form the assignment: 11775 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11776 QualType BaseType = Base.getType().getUnqualifiedType(); 11777 if (!BaseType->isRecordType()) { 11778 Invalid = true; 11779 continue; 11780 } 11781 11782 CXXCastPath BasePath; 11783 BasePath.push_back(&Base); 11784 11785 // Construct the "from" expression, which is an implicit cast to the 11786 // appropriately-qualified base type. 11787 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11788 11789 // Dereference "this". 11790 DerefBuilder DerefThis(This); 11791 11792 // Implicitly cast "this" to the appropriately-qualified base type. 11793 CastBuilder To(DerefThis, 11794 Context.getCVRQualifiedType( 11795 BaseType, MoveAssignOperator->getTypeQualifiers()), 11796 VK_LValue, BasePath); 11797 11798 // Build the move. 11799 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11800 To, From, 11801 /*CopyingBaseSubobject=*/true, 11802 /*Copying=*/false); 11803 if (Move.isInvalid()) { 11804 MoveAssignOperator->setInvalidDecl(); 11805 return; 11806 } 11807 11808 // Success! Record the move. 11809 Statements.push_back(Move.getAs<Expr>()); 11810 } 11811 11812 // Assign non-static members. 11813 for (auto *Field : ClassDecl->fields()) { 11814 // FIXME: We should form some kind of AST representation for the implied 11815 // memcpy in a union copy operation. 11816 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11817 continue; 11818 11819 if (Field->isInvalidDecl()) { 11820 Invalid = true; 11821 continue; 11822 } 11823 11824 // Check for members of reference type; we can't move those. 11825 if (Field->getType()->isReferenceType()) { 11826 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11827 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11828 Diag(Field->getLocation(), diag::note_declared_at); 11829 Invalid = true; 11830 continue; 11831 } 11832 11833 // Check for members of const-qualified, non-class type. 11834 QualType BaseType = Context.getBaseElementType(Field->getType()); 11835 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11836 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11837 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11838 Diag(Field->getLocation(), diag::note_declared_at); 11839 Invalid = true; 11840 continue; 11841 } 11842 11843 // Suppress assigning zero-width bitfields. 11844 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11845 continue; 11846 11847 QualType FieldType = Field->getType().getNonReferenceType(); 11848 if (FieldType->isIncompleteArrayType()) { 11849 assert(ClassDecl->hasFlexibleArrayMember() && 11850 "Incomplete array type is not valid"); 11851 continue; 11852 } 11853 11854 // Build references to the field in the object we're copying from and to. 11855 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11856 LookupMemberName); 11857 MemberLookup.addDecl(Field); 11858 MemberLookup.resolveKind(); 11859 MemberBuilder From(MoveOther, OtherRefType, 11860 /*IsArrow=*/false, MemberLookup); 11861 MemberBuilder To(This, getCurrentThisType(), 11862 /*IsArrow=*/true, MemberLookup); 11863 11864 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 11865 "Member reference with rvalue base must be rvalue except for reference " 11866 "members, which aren't allowed for move assignment."); 11867 11868 // Build the move of this field. 11869 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 11870 To, From, 11871 /*CopyingBaseSubobject=*/false, 11872 /*Copying=*/false); 11873 if (Move.isInvalid()) { 11874 MoveAssignOperator->setInvalidDecl(); 11875 return; 11876 } 11877 11878 // Success! Record the copy. 11879 Statements.push_back(Move.getAs<Stmt>()); 11880 } 11881 11882 if (!Invalid) { 11883 // Add a "return *this;" 11884 ExprResult ThisObj = 11885 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11886 11887 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11888 if (Return.isInvalid()) 11889 Invalid = true; 11890 else 11891 Statements.push_back(Return.getAs<Stmt>()); 11892 } 11893 11894 if (Invalid) { 11895 MoveAssignOperator->setInvalidDecl(); 11896 return; 11897 } 11898 11899 StmtResult Body; 11900 { 11901 CompoundScopeRAII CompoundScope(*this); 11902 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11903 /*isStmtExpr=*/false); 11904 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11905 } 11906 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 11907 MoveAssignOperator->markUsed(Context); 11908 11909 if (ASTMutationListener *L = getASTMutationListener()) { 11910 L->CompletedImplicitDefinition(MoveAssignOperator); 11911 } 11912 } 11913 11914 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 11915 CXXRecordDecl *ClassDecl) { 11916 // C++ [class.copy]p4: 11917 // If the class definition does not explicitly declare a copy 11918 // constructor, one is declared implicitly. 11919 assert(ClassDecl->needsImplicitCopyConstructor()); 11920 11921 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 11922 if (DSM.isAlreadyBeingDeclared()) 11923 return nullptr; 11924 11925 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11926 QualType ArgType = ClassType; 11927 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 11928 if (Const) 11929 ArgType = ArgType.withConst(); 11930 ArgType = Context.getLValueReferenceType(ArgType); 11931 11932 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11933 CXXCopyConstructor, 11934 Const); 11935 11936 DeclarationName Name 11937 = Context.DeclarationNames.getCXXConstructorName( 11938 Context.getCanonicalType(ClassType)); 11939 SourceLocation ClassLoc = ClassDecl->getLocation(); 11940 DeclarationNameInfo NameInfo(Name, ClassLoc); 11941 11942 // An implicitly-declared copy constructor is an inline public 11943 // member of its class. 11944 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 11945 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11946 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11947 Constexpr); 11948 CopyConstructor->setAccess(AS_public); 11949 CopyConstructor->setDefaulted(); 11950 11951 if (getLangOpts().CUDA) { 11952 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 11953 CopyConstructor, 11954 /* ConstRHS */ Const, 11955 /* Diagnose */ false); 11956 } 11957 11958 // Build an exception specification pointing back at this member. 11959 FunctionProtoType::ExtProtoInfo EPI = 11960 getImplicitMethodEPI(*this, CopyConstructor); 11961 CopyConstructor->setType( 11962 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11963 11964 // Add the parameter to the constructor. 11965 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 11966 ClassLoc, ClassLoc, 11967 /*IdentifierInfo=*/nullptr, 11968 ArgType, /*TInfo=*/nullptr, 11969 SC_None, nullptr); 11970 CopyConstructor->setParams(FromParam); 11971 11972 CopyConstructor->setTrivial( 11973 ClassDecl->needsOverloadResolutionForCopyConstructor() 11974 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 11975 : ClassDecl->hasTrivialCopyConstructor()); 11976 11977 // Note that we have declared this constructor. 11978 ++ASTContext::NumImplicitCopyConstructorsDeclared; 11979 11980 Scope *S = getScopeForContext(ClassDecl); 11981 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 11982 11983 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 11984 ClassDecl->setImplicitCopyConstructorIsDeleted(); 11985 SetDeclDeleted(CopyConstructor, ClassLoc); 11986 } 11987 11988 if (S) 11989 PushOnScopeChains(CopyConstructor, S, false); 11990 ClassDecl->addDecl(CopyConstructor); 11991 11992 return CopyConstructor; 11993 } 11994 11995 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 11996 CXXConstructorDecl *CopyConstructor) { 11997 assert((CopyConstructor->isDefaulted() && 11998 CopyConstructor->isCopyConstructor() && 11999 !CopyConstructor->doesThisDeclarationHaveABody() && 12000 !CopyConstructor->isDeleted()) && 12001 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12002 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12003 return; 12004 12005 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12006 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12007 12008 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12009 12010 // The exception specification is needed because we are defining the 12011 // function. 12012 ResolveExceptionSpec(CurrentLocation, 12013 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12014 MarkVTableUsed(CurrentLocation, ClassDecl); 12015 12016 // Add a context note for diagnostics produced after this point. 12017 Scope.addContextNote(CurrentLocation); 12018 12019 // C++11 [class.copy]p7: 12020 // The [definition of an implicitly declared copy constructor] is 12021 // deprecated if the class has a user-declared copy assignment operator 12022 // or a user-declared destructor. 12023 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12024 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12025 12026 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12027 CopyConstructor->setInvalidDecl(); 12028 } else { 12029 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12030 ? CopyConstructor->getLocEnd() 12031 : CopyConstructor->getLocation(); 12032 Sema::CompoundScopeRAII CompoundScope(*this); 12033 CopyConstructor->setBody( 12034 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12035 CopyConstructor->markUsed(Context); 12036 } 12037 12038 if (ASTMutationListener *L = getASTMutationListener()) { 12039 L->CompletedImplicitDefinition(CopyConstructor); 12040 } 12041 } 12042 12043 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12044 CXXRecordDecl *ClassDecl) { 12045 assert(ClassDecl->needsImplicitMoveConstructor()); 12046 12047 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12048 if (DSM.isAlreadyBeingDeclared()) 12049 return nullptr; 12050 12051 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12052 QualType ArgType = Context.getRValueReferenceType(ClassType); 12053 12054 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12055 CXXMoveConstructor, 12056 false); 12057 12058 DeclarationName Name 12059 = Context.DeclarationNames.getCXXConstructorName( 12060 Context.getCanonicalType(ClassType)); 12061 SourceLocation ClassLoc = ClassDecl->getLocation(); 12062 DeclarationNameInfo NameInfo(Name, ClassLoc); 12063 12064 // C++11 [class.copy]p11: 12065 // An implicitly-declared copy/move constructor is an inline public 12066 // member of its class. 12067 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12068 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12069 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12070 Constexpr); 12071 MoveConstructor->setAccess(AS_public); 12072 MoveConstructor->setDefaulted(); 12073 12074 if (getLangOpts().CUDA) { 12075 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12076 MoveConstructor, 12077 /* ConstRHS */ false, 12078 /* Diagnose */ false); 12079 } 12080 12081 // Build an exception specification pointing back at this member. 12082 FunctionProtoType::ExtProtoInfo EPI = 12083 getImplicitMethodEPI(*this, MoveConstructor); 12084 MoveConstructor->setType( 12085 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12086 12087 // Add the parameter to the constructor. 12088 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12089 ClassLoc, ClassLoc, 12090 /*IdentifierInfo=*/nullptr, 12091 ArgType, /*TInfo=*/nullptr, 12092 SC_None, nullptr); 12093 MoveConstructor->setParams(FromParam); 12094 12095 MoveConstructor->setTrivial( 12096 ClassDecl->needsOverloadResolutionForMoveConstructor() 12097 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12098 : ClassDecl->hasTrivialMoveConstructor()); 12099 12100 // Note that we have declared this constructor. 12101 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12102 12103 Scope *S = getScopeForContext(ClassDecl); 12104 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12105 12106 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12107 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12108 SetDeclDeleted(MoveConstructor, ClassLoc); 12109 } 12110 12111 if (S) 12112 PushOnScopeChains(MoveConstructor, S, false); 12113 ClassDecl->addDecl(MoveConstructor); 12114 12115 return MoveConstructor; 12116 } 12117 12118 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12119 CXXConstructorDecl *MoveConstructor) { 12120 assert((MoveConstructor->isDefaulted() && 12121 MoveConstructor->isMoveConstructor() && 12122 !MoveConstructor->doesThisDeclarationHaveABody() && 12123 !MoveConstructor->isDeleted()) && 12124 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12125 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12126 return; 12127 12128 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12129 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12130 12131 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12132 12133 // The exception specification is needed because we are defining the 12134 // function. 12135 ResolveExceptionSpec(CurrentLocation, 12136 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12137 MarkVTableUsed(CurrentLocation, ClassDecl); 12138 12139 // Add a context note for diagnostics produced after this point. 12140 Scope.addContextNote(CurrentLocation); 12141 12142 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12143 MoveConstructor->setInvalidDecl(); 12144 } else { 12145 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12146 ? MoveConstructor->getLocEnd() 12147 : MoveConstructor->getLocation(); 12148 Sema::CompoundScopeRAII CompoundScope(*this); 12149 MoveConstructor->setBody(ActOnCompoundStmt( 12150 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12151 MoveConstructor->markUsed(Context); 12152 } 12153 12154 if (ASTMutationListener *L = getASTMutationListener()) { 12155 L->CompletedImplicitDefinition(MoveConstructor); 12156 } 12157 } 12158 12159 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12160 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12161 } 12162 12163 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12164 SourceLocation CurrentLocation, 12165 CXXConversionDecl *Conv) { 12166 SynthesizedFunctionScope Scope(*this, Conv); 12167 12168 CXXRecordDecl *Lambda = Conv->getParent(); 12169 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 12170 // If we are defining a specialization of a conversion to function-ptr 12171 // cache the deduced template arguments for this specialization 12172 // so that we can use them to retrieve the corresponding call-operator 12173 // and static-invoker. 12174 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 12175 12176 // Retrieve the corresponding call-operator specialization. 12177 if (Lambda->isGenericLambda()) { 12178 assert(Conv->isFunctionTemplateSpecialization()); 12179 FunctionTemplateDecl *CallOpTemplate = 12180 CallOp->getDescribedFunctionTemplate(); 12181 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 12182 void *InsertPos = nullptr; 12183 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 12184 DeducedTemplateArgs->asArray(), 12185 InsertPos); 12186 assert(CallOpSpec && 12187 "Conversion operator must have a corresponding call operator"); 12188 CallOp = cast<CXXMethodDecl>(CallOpSpec); 12189 } 12190 12191 // Mark the call operator referenced (and add to pending instantiations 12192 // if necessary). 12193 // For both the conversion and static-invoker template specializations 12194 // we construct their body's in this function, so no need to add them 12195 // to the PendingInstantiations. 12196 MarkFunctionReferenced(CurrentLocation, CallOp); 12197 12198 // Retrieve the static invoker... 12199 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12200 // ... and get the corresponding specialization for a generic lambda. 12201 if (Lambda->isGenericLambda()) { 12202 assert(DeducedTemplateArgs && 12203 "Must have deduced template arguments from Conversion Operator"); 12204 FunctionTemplateDecl *InvokeTemplate = 12205 Invoker->getDescribedFunctionTemplate(); 12206 void *InsertPos = nullptr; 12207 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 12208 DeducedTemplateArgs->asArray(), 12209 InsertPos); 12210 assert(InvokeSpec && 12211 "Must have a corresponding static invoker specialization"); 12212 Invoker = cast<CXXMethodDecl>(InvokeSpec); 12213 } 12214 // Construct the body of the conversion function { return __invoke; }. 12215 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12216 VK_LValue, Conv->getLocation()).get(); 12217 assert(FunctionRef && "Can't refer to __invoke function?"); 12218 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12219 Conv->setBody(new (Context) CompoundStmt(Context, Return, 12220 Conv->getLocation(), 12221 Conv->getLocation())); 12222 12223 Conv->markUsed(Context); 12224 Conv->setReferenced(); 12225 12226 // Fill in the __invoke function with a dummy implementation. IR generation 12227 // will fill in the actual details. 12228 Invoker->markUsed(Context); 12229 Invoker->setReferenced(); 12230 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12231 12232 if (ASTMutationListener *L = getASTMutationListener()) { 12233 L->CompletedImplicitDefinition(Conv); 12234 L->CompletedImplicitDefinition(Invoker); 12235 } 12236 } 12237 12238 12239 12240 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12241 SourceLocation CurrentLocation, 12242 CXXConversionDecl *Conv) 12243 { 12244 assert(!Conv->getParent()->isGenericLambda()); 12245 12246 SynthesizedFunctionScope Scope(*this, Conv); 12247 12248 // Copy-initialize the lambda object as needed to capture it. 12249 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12250 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12251 12252 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12253 Conv->getLocation(), 12254 Conv, DerefThis); 12255 12256 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12257 // behavior. Note that only the general conversion function does this 12258 // (since it's unusable otherwise); in the case where we inline the 12259 // block literal, it has block literal lifetime semantics. 12260 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12261 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12262 CK_CopyAndAutoreleaseBlockObject, 12263 BuildBlock.get(), nullptr, VK_RValue); 12264 12265 if (BuildBlock.isInvalid()) { 12266 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12267 Conv->setInvalidDecl(); 12268 return; 12269 } 12270 12271 // Create the return statement that returns the block from the conversion 12272 // function. 12273 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12274 if (Return.isInvalid()) { 12275 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12276 Conv->setInvalidDecl(); 12277 return; 12278 } 12279 12280 // Set the body of the conversion function. 12281 Stmt *ReturnS = Return.get(); 12282 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 12283 Conv->getLocation(), 12284 Conv->getLocation())); 12285 Conv->markUsed(Context); 12286 12287 // We're done; notify the mutation listener, if any. 12288 if (ASTMutationListener *L = getASTMutationListener()) { 12289 L->CompletedImplicitDefinition(Conv); 12290 } 12291 } 12292 12293 /// \brief Determine whether the given list arguments contains exactly one 12294 /// "real" (non-default) argument. 12295 static bool hasOneRealArgument(MultiExprArg Args) { 12296 switch (Args.size()) { 12297 case 0: 12298 return false; 12299 12300 default: 12301 if (!Args[1]->isDefaultArgument()) 12302 return false; 12303 12304 // fall through 12305 case 1: 12306 return !Args[0]->isDefaultArgument(); 12307 } 12308 12309 return false; 12310 } 12311 12312 ExprResult 12313 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12314 NamedDecl *FoundDecl, 12315 CXXConstructorDecl *Constructor, 12316 MultiExprArg ExprArgs, 12317 bool HadMultipleCandidates, 12318 bool IsListInitialization, 12319 bool IsStdInitListInitialization, 12320 bool RequiresZeroInit, 12321 unsigned ConstructKind, 12322 SourceRange ParenRange) { 12323 bool Elidable = false; 12324 12325 // C++0x [class.copy]p34: 12326 // When certain criteria are met, an implementation is allowed to 12327 // omit the copy/move construction of a class object, even if the 12328 // copy/move constructor and/or destructor for the object have 12329 // side effects. [...] 12330 // - when a temporary class object that has not been bound to a 12331 // reference (12.2) would be copied/moved to a class object 12332 // with the same cv-unqualified type, the copy/move operation 12333 // can be omitted by constructing the temporary object 12334 // directly into the target of the omitted copy/move 12335 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12336 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12337 Expr *SubExpr = ExprArgs[0]; 12338 Elidable = SubExpr->isTemporaryObject( 12339 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12340 } 12341 12342 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12343 FoundDecl, Constructor, 12344 Elidable, ExprArgs, HadMultipleCandidates, 12345 IsListInitialization, 12346 IsStdInitListInitialization, RequiresZeroInit, 12347 ConstructKind, ParenRange); 12348 } 12349 12350 ExprResult 12351 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12352 NamedDecl *FoundDecl, 12353 CXXConstructorDecl *Constructor, 12354 bool Elidable, 12355 MultiExprArg ExprArgs, 12356 bool HadMultipleCandidates, 12357 bool IsListInitialization, 12358 bool IsStdInitListInitialization, 12359 bool RequiresZeroInit, 12360 unsigned ConstructKind, 12361 SourceRange ParenRange) { 12362 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12363 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12364 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12365 return ExprError(); 12366 } 12367 12368 return BuildCXXConstructExpr( 12369 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12370 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12371 RequiresZeroInit, ConstructKind, ParenRange); 12372 } 12373 12374 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12375 /// including handling of its default argument expressions. 12376 ExprResult 12377 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12378 CXXConstructorDecl *Constructor, 12379 bool Elidable, 12380 MultiExprArg ExprArgs, 12381 bool HadMultipleCandidates, 12382 bool IsListInitialization, 12383 bool IsStdInitListInitialization, 12384 bool RequiresZeroInit, 12385 unsigned ConstructKind, 12386 SourceRange ParenRange) { 12387 assert(declaresSameEntity( 12388 Constructor->getParent(), 12389 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12390 "given constructor for wrong type"); 12391 MarkFunctionReferenced(ConstructLoc, Constructor); 12392 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12393 return ExprError(); 12394 12395 return CXXConstructExpr::Create( 12396 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12397 ExprArgs, HadMultipleCandidates, IsListInitialization, 12398 IsStdInitListInitialization, RequiresZeroInit, 12399 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12400 ParenRange); 12401 } 12402 12403 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12404 assert(Field->hasInClassInitializer()); 12405 12406 // If we already have the in-class initializer nothing needs to be done. 12407 if (Field->getInClassInitializer()) 12408 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12409 12410 // If we might have already tried and failed to instantiate, don't try again. 12411 if (Field->isInvalidDecl()) 12412 return ExprError(); 12413 12414 // Maybe we haven't instantiated the in-class initializer. Go check the 12415 // pattern FieldDecl to see if it has one. 12416 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12417 12418 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12419 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12420 DeclContext::lookup_result Lookup = 12421 ClassPattern->lookup(Field->getDeclName()); 12422 12423 // Lookup can return at most two results: the pattern for the field, or the 12424 // injected class name of the parent record. No other member can have the 12425 // same name as the field. 12426 // In modules mode, lookup can return multiple results (coming from 12427 // different modules). 12428 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12429 "more than two lookup results for field name"); 12430 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12431 if (!Pattern) { 12432 assert(isa<CXXRecordDecl>(Lookup[0]) && 12433 "cannot have other non-field member with same name"); 12434 for (auto L : Lookup) 12435 if (isa<FieldDecl>(L)) { 12436 Pattern = cast<FieldDecl>(L); 12437 break; 12438 } 12439 assert(Pattern && "We must have set the Pattern!"); 12440 } 12441 12442 if (!Pattern->hasInClassInitializer() || 12443 InstantiateInClassInitializer(Loc, Field, Pattern, 12444 getTemplateInstantiationArgs(Field))) { 12445 // Don't diagnose this again. 12446 Field->setInvalidDecl(); 12447 return ExprError(); 12448 } 12449 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12450 } 12451 12452 // DR1351: 12453 // If the brace-or-equal-initializer of a non-static data member 12454 // invokes a defaulted default constructor of its class or of an 12455 // enclosing class in a potentially evaluated subexpression, the 12456 // program is ill-formed. 12457 // 12458 // This resolution is unworkable: the exception specification of the 12459 // default constructor can be needed in an unevaluated context, in 12460 // particular, in the operand of a noexcept-expression, and we can be 12461 // unable to compute an exception specification for an enclosed class. 12462 // 12463 // Any attempt to resolve the exception specification of a defaulted default 12464 // constructor before the initializer is lexically complete will ultimately 12465 // come here at which point we can diagnose it. 12466 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12467 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12468 << OutermostClass << Field; 12469 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12470 // Recover by marking the field invalid, unless we're in a SFINAE context. 12471 if (!isSFINAEContext()) 12472 Field->setInvalidDecl(); 12473 return ExprError(); 12474 } 12475 12476 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12477 if (VD->isInvalidDecl()) return; 12478 12479 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12480 if (ClassDecl->isInvalidDecl()) return; 12481 if (ClassDecl->hasIrrelevantDestructor()) return; 12482 if (ClassDecl->isDependentContext()) return; 12483 12484 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12485 MarkFunctionReferenced(VD->getLocation(), Destructor); 12486 CheckDestructorAccess(VD->getLocation(), Destructor, 12487 PDiag(diag::err_access_dtor_var) 12488 << VD->getDeclName() 12489 << VD->getType()); 12490 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12491 12492 if (Destructor->isTrivial()) return; 12493 if (!VD->hasGlobalStorage()) return; 12494 12495 // Emit warning for non-trivial dtor in global scope (a real global, 12496 // class-static, function-static). 12497 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12498 12499 // TODO: this should be re-enabled for static locals by !CXAAtExit 12500 if (!VD->isStaticLocal()) 12501 Diag(VD->getLocation(), diag::warn_global_destructor); 12502 } 12503 12504 /// \brief Given a constructor and the set of arguments provided for the 12505 /// constructor, convert the arguments and add any required default arguments 12506 /// to form a proper call to this constructor. 12507 /// 12508 /// \returns true if an error occurred, false otherwise. 12509 bool 12510 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12511 MultiExprArg ArgsPtr, 12512 SourceLocation Loc, 12513 SmallVectorImpl<Expr*> &ConvertedArgs, 12514 bool AllowExplicit, 12515 bool IsListInitialization) { 12516 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12517 unsigned NumArgs = ArgsPtr.size(); 12518 Expr **Args = ArgsPtr.data(); 12519 12520 const FunctionProtoType *Proto 12521 = Constructor->getType()->getAs<FunctionProtoType>(); 12522 assert(Proto && "Constructor without a prototype?"); 12523 unsigned NumParams = Proto->getNumParams(); 12524 12525 // If too few arguments are available, we'll fill in the rest with defaults. 12526 if (NumArgs < NumParams) 12527 ConvertedArgs.reserve(NumParams); 12528 else 12529 ConvertedArgs.reserve(NumArgs); 12530 12531 VariadicCallType CallType = 12532 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12533 SmallVector<Expr *, 8> AllArgs; 12534 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12535 Proto, 0, 12536 llvm::makeArrayRef(Args, NumArgs), 12537 AllArgs, 12538 CallType, AllowExplicit, 12539 IsListInitialization); 12540 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12541 12542 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12543 12544 CheckConstructorCall(Constructor, 12545 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12546 Proto, Loc); 12547 12548 return Invalid; 12549 } 12550 12551 static inline bool 12552 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12553 const FunctionDecl *FnDecl) { 12554 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12555 if (isa<NamespaceDecl>(DC)) { 12556 return SemaRef.Diag(FnDecl->getLocation(), 12557 diag::err_operator_new_delete_declared_in_namespace) 12558 << FnDecl->getDeclName(); 12559 } 12560 12561 if (isa<TranslationUnitDecl>(DC) && 12562 FnDecl->getStorageClass() == SC_Static) { 12563 return SemaRef.Diag(FnDecl->getLocation(), 12564 diag::err_operator_new_delete_declared_static) 12565 << FnDecl->getDeclName(); 12566 } 12567 12568 return false; 12569 } 12570 12571 static inline bool 12572 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12573 CanQualType ExpectedResultType, 12574 CanQualType ExpectedFirstParamType, 12575 unsigned DependentParamTypeDiag, 12576 unsigned InvalidParamTypeDiag) { 12577 QualType ResultType = 12578 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12579 12580 // Check that the result type is not dependent. 12581 if (ResultType->isDependentType()) 12582 return SemaRef.Diag(FnDecl->getLocation(), 12583 diag::err_operator_new_delete_dependent_result_type) 12584 << FnDecl->getDeclName() << ExpectedResultType; 12585 12586 // Check that the result type is what we expect. 12587 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12588 return SemaRef.Diag(FnDecl->getLocation(), 12589 diag::err_operator_new_delete_invalid_result_type) 12590 << FnDecl->getDeclName() << ExpectedResultType; 12591 12592 // A function template must have at least 2 parameters. 12593 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12594 return SemaRef.Diag(FnDecl->getLocation(), 12595 diag::err_operator_new_delete_template_too_few_parameters) 12596 << FnDecl->getDeclName(); 12597 12598 // The function decl must have at least 1 parameter. 12599 if (FnDecl->getNumParams() == 0) 12600 return SemaRef.Diag(FnDecl->getLocation(), 12601 diag::err_operator_new_delete_too_few_parameters) 12602 << FnDecl->getDeclName(); 12603 12604 // Check the first parameter type is not dependent. 12605 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12606 if (FirstParamType->isDependentType()) 12607 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12608 << FnDecl->getDeclName() << ExpectedFirstParamType; 12609 12610 // Check that the first parameter type is what we expect. 12611 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12612 ExpectedFirstParamType) 12613 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12614 << FnDecl->getDeclName() << ExpectedFirstParamType; 12615 12616 return false; 12617 } 12618 12619 static bool 12620 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12621 // C++ [basic.stc.dynamic.allocation]p1: 12622 // A program is ill-formed if an allocation function is declared in a 12623 // namespace scope other than global scope or declared static in global 12624 // scope. 12625 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12626 return true; 12627 12628 CanQualType SizeTy = 12629 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12630 12631 // C++ [basic.stc.dynamic.allocation]p1: 12632 // The return type shall be void*. The first parameter shall have type 12633 // std::size_t. 12634 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12635 SizeTy, 12636 diag::err_operator_new_dependent_param_type, 12637 diag::err_operator_new_param_type)) 12638 return true; 12639 12640 // C++ [basic.stc.dynamic.allocation]p1: 12641 // The first parameter shall not have an associated default argument. 12642 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12643 return SemaRef.Diag(FnDecl->getLocation(), 12644 diag::err_operator_new_default_arg) 12645 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12646 12647 return false; 12648 } 12649 12650 static bool 12651 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12652 // C++ [basic.stc.dynamic.deallocation]p1: 12653 // A program is ill-formed if deallocation functions are declared in a 12654 // namespace scope other than global scope or declared static in global 12655 // scope. 12656 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12657 return true; 12658 12659 // C++ [basic.stc.dynamic.deallocation]p2: 12660 // Each deallocation function shall return void and its first parameter 12661 // shall be void*. 12662 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 12663 SemaRef.Context.VoidPtrTy, 12664 diag::err_operator_delete_dependent_param_type, 12665 diag::err_operator_delete_param_type)) 12666 return true; 12667 12668 return false; 12669 } 12670 12671 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12672 /// of this overloaded operator is well-formed. If so, returns false; 12673 /// otherwise, emits appropriate diagnostics and returns true. 12674 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12675 assert(FnDecl && FnDecl->isOverloadedOperator() && 12676 "Expected an overloaded operator declaration"); 12677 12678 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12679 12680 // C++ [over.oper]p5: 12681 // The allocation and deallocation functions, operator new, 12682 // operator new[], operator delete and operator delete[], are 12683 // described completely in 3.7.3. The attributes and restrictions 12684 // found in the rest of this subclause do not apply to them unless 12685 // explicitly stated in 3.7.3. 12686 if (Op == OO_Delete || Op == OO_Array_Delete) 12687 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12688 12689 if (Op == OO_New || Op == OO_Array_New) 12690 return CheckOperatorNewDeclaration(*this, FnDecl); 12691 12692 // C++ [over.oper]p6: 12693 // An operator function shall either be a non-static member 12694 // function or be a non-member function and have at least one 12695 // parameter whose type is a class, a reference to a class, an 12696 // enumeration, or a reference to an enumeration. 12697 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12698 if (MethodDecl->isStatic()) 12699 return Diag(FnDecl->getLocation(), 12700 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12701 } else { 12702 bool ClassOrEnumParam = false; 12703 for (auto Param : FnDecl->parameters()) { 12704 QualType ParamType = Param->getType().getNonReferenceType(); 12705 if (ParamType->isDependentType() || ParamType->isRecordType() || 12706 ParamType->isEnumeralType()) { 12707 ClassOrEnumParam = true; 12708 break; 12709 } 12710 } 12711 12712 if (!ClassOrEnumParam) 12713 return Diag(FnDecl->getLocation(), 12714 diag::err_operator_overload_needs_class_or_enum) 12715 << FnDecl->getDeclName(); 12716 } 12717 12718 // C++ [over.oper]p8: 12719 // An operator function cannot have default arguments (8.3.6), 12720 // except where explicitly stated below. 12721 // 12722 // Only the function-call operator allows default arguments 12723 // (C++ [over.call]p1). 12724 if (Op != OO_Call) { 12725 for (auto Param : FnDecl->parameters()) { 12726 if (Param->hasDefaultArg()) 12727 return Diag(Param->getLocation(), 12728 diag::err_operator_overload_default_arg) 12729 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12730 } 12731 } 12732 12733 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12734 { false, false, false } 12735 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12736 , { Unary, Binary, MemberOnly } 12737 #include "clang/Basic/OperatorKinds.def" 12738 }; 12739 12740 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12741 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12742 bool MustBeMemberOperator = OperatorUses[Op][2]; 12743 12744 // C++ [over.oper]p8: 12745 // [...] Operator functions cannot have more or fewer parameters 12746 // than the number required for the corresponding operator, as 12747 // described in the rest of this subclause. 12748 unsigned NumParams = FnDecl->getNumParams() 12749 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12750 if (Op != OO_Call && 12751 ((NumParams == 1 && !CanBeUnaryOperator) || 12752 (NumParams == 2 && !CanBeBinaryOperator) || 12753 (NumParams < 1) || (NumParams > 2))) { 12754 // We have the wrong number of parameters. 12755 unsigned ErrorKind; 12756 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12757 ErrorKind = 2; // 2 -> unary or binary. 12758 } else if (CanBeUnaryOperator) { 12759 ErrorKind = 0; // 0 -> unary 12760 } else { 12761 assert(CanBeBinaryOperator && 12762 "All non-call overloaded operators are unary or binary!"); 12763 ErrorKind = 1; // 1 -> binary 12764 } 12765 12766 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12767 << FnDecl->getDeclName() << NumParams << ErrorKind; 12768 } 12769 12770 // Overloaded operators other than operator() cannot be variadic. 12771 if (Op != OO_Call && 12772 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12773 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12774 << FnDecl->getDeclName(); 12775 } 12776 12777 // Some operators must be non-static member functions. 12778 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12779 return Diag(FnDecl->getLocation(), 12780 diag::err_operator_overload_must_be_member) 12781 << FnDecl->getDeclName(); 12782 } 12783 12784 // C++ [over.inc]p1: 12785 // The user-defined function called operator++ implements the 12786 // prefix and postfix ++ operator. If this function is a member 12787 // function with no parameters, or a non-member function with one 12788 // parameter of class or enumeration type, it defines the prefix 12789 // increment operator ++ for objects of that type. If the function 12790 // is a member function with one parameter (which shall be of type 12791 // int) or a non-member function with two parameters (the second 12792 // of which shall be of type int), it defines the postfix 12793 // increment operator ++ for objects of that type. 12794 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12795 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12796 QualType ParamType = LastParam->getType(); 12797 12798 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12799 !ParamType->isDependentType()) 12800 return Diag(LastParam->getLocation(), 12801 diag::err_operator_overload_post_incdec_must_be_int) 12802 << LastParam->getType() << (Op == OO_MinusMinus); 12803 } 12804 12805 return false; 12806 } 12807 12808 static bool 12809 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12810 FunctionTemplateDecl *TpDecl) { 12811 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 12812 12813 // Must have one or two template parameters. 12814 if (TemplateParams->size() == 1) { 12815 NonTypeTemplateParmDecl *PmDecl = 12816 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 12817 12818 // The template parameter must be a char parameter pack. 12819 if (PmDecl && PmDecl->isTemplateParameterPack() && 12820 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 12821 return false; 12822 12823 } else if (TemplateParams->size() == 2) { 12824 TemplateTypeParmDecl *PmType = 12825 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 12826 NonTypeTemplateParmDecl *PmArgs = 12827 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 12828 12829 // The second template parameter must be a parameter pack with the 12830 // first template parameter as its type. 12831 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 12832 PmArgs->isTemplateParameterPack()) { 12833 const TemplateTypeParmType *TArgs = 12834 PmArgs->getType()->getAs<TemplateTypeParmType>(); 12835 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 12836 TArgs->getIndex() == PmType->getIndex()) { 12837 if (!SemaRef.inTemplateInstantiation()) 12838 SemaRef.Diag(TpDecl->getLocation(), 12839 diag::ext_string_literal_operator_template); 12840 return false; 12841 } 12842 } 12843 } 12844 12845 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 12846 diag::err_literal_operator_template) 12847 << TpDecl->getTemplateParameters()->getSourceRange(); 12848 return true; 12849 } 12850 12851 /// CheckLiteralOperatorDeclaration - Check whether the declaration 12852 /// of this literal operator function is well-formed. If so, returns 12853 /// false; otherwise, emits appropriate diagnostics and returns true. 12854 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 12855 if (isa<CXXMethodDecl>(FnDecl)) { 12856 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 12857 << FnDecl->getDeclName(); 12858 return true; 12859 } 12860 12861 if (FnDecl->isExternC()) { 12862 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 12863 if (const LinkageSpecDecl *LSD = 12864 FnDecl->getDeclContext()->getExternCContext()) 12865 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 12866 return true; 12867 } 12868 12869 // This might be the definition of a literal operator template. 12870 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 12871 12872 // This might be a specialization of a literal operator template. 12873 if (!TpDecl) 12874 TpDecl = FnDecl->getPrimaryTemplate(); 12875 12876 // template <char...> type operator "" name() and 12877 // template <class T, T...> type operator "" name() are the only valid 12878 // template signatures, and the only valid signatures with no parameters. 12879 if (TpDecl) { 12880 if (FnDecl->param_size() != 0) { 12881 Diag(FnDecl->getLocation(), 12882 diag::err_literal_operator_template_with_params); 12883 return true; 12884 } 12885 12886 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 12887 return true; 12888 12889 } else if (FnDecl->param_size() == 1) { 12890 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 12891 12892 QualType ParamType = Param->getType().getUnqualifiedType(); 12893 12894 // Only unsigned long long int, long double, any character type, and const 12895 // char * are allowed as the only parameters. 12896 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 12897 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 12898 Context.hasSameType(ParamType, Context.CharTy) || 12899 Context.hasSameType(ParamType, Context.WideCharTy) || 12900 Context.hasSameType(ParamType, Context.Char16Ty) || 12901 Context.hasSameType(ParamType, Context.Char32Ty)) { 12902 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 12903 QualType InnerType = Ptr->getPointeeType(); 12904 12905 // Pointer parameter must be a const char *. 12906 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 12907 Context.CharTy) && 12908 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 12909 Diag(Param->getSourceRange().getBegin(), 12910 diag::err_literal_operator_param) 12911 << ParamType << "'const char *'" << Param->getSourceRange(); 12912 return true; 12913 } 12914 12915 } else if (ParamType->isRealFloatingType()) { 12916 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12917 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 12918 return true; 12919 12920 } else if (ParamType->isIntegerType()) { 12921 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12922 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 12923 return true; 12924 12925 } else { 12926 Diag(Param->getSourceRange().getBegin(), 12927 diag::err_literal_operator_invalid_param) 12928 << ParamType << Param->getSourceRange(); 12929 return true; 12930 } 12931 12932 } else if (FnDecl->param_size() == 2) { 12933 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 12934 12935 // First, verify that the first parameter is correct. 12936 12937 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 12938 12939 // Two parameter function must have a pointer to const as a 12940 // first parameter; let's strip those qualifiers. 12941 const PointerType *PT = FirstParamType->getAs<PointerType>(); 12942 12943 if (!PT) { 12944 Diag((*Param)->getSourceRange().getBegin(), 12945 diag::err_literal_operator_param) 12946 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12947 return true; 12948 } 12949 12950 QualType PointeeType = PT->getPointeeType(); 12951 // First parameter must be const 12952 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 12953 Diag((*Param)->getSourceRange().getBegin(), 12954 diag::err_literal_operator_param) 12955 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12956 return true; 12957 } 12958 12959 QualType InnerType = PointeeType.getUnqualifiedType(); 12960 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 12961 // are allowed as the first parameter to a two-parameter function 12962 if (!(Context.hasSameType(InnerType, Context.CharTy) || 12963 Context.hasSameType(InnerType, Context.WideCharTy) || 12964 Context.hasSameType(InnerType, Context.Char16Ty) || 12965 Context.hasSameType(InnerType, Context.Char32Ty))) { 12966 Diag((*Param)->getSourceRange().getBegin(), 12967 diag::err_literal_operator_param) 12968 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12969 return true; 12970 } 12971 12972 // Move on to the second and final parameter. 12973 ++Param; 12974 12975 // The second parameter must be a std::size_t. 12976 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 12977 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 12978 Diag((*Param)->getSourceRange().getBegin(), 12979 diag::err_literal_operator_param) 12980 << SecondParamType << Context.getSizeType() 12981 << (*Param)->getSourceRange(); 12982 return true; 12983 } 12984 } else { 12985 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 12986 return true; 12987 } 12988 12989 // Parameters are good. 12990 12991 // A parameter-declaration-clause containing a default argument is not 12992 // equivalent to any of the permitted forms. 12993 for (auto Param : FnDecl->parameters()) { 12994 if (Param->hasDefaultArg()) { 12995 Diag(Param->getDefaultArgRange().getBegin(), 12996 diag::err_literal_operator_default_argument) 12997 << Param->getDefaultArgRange(); 12998 break; 12999 } 13000 } 13001 13002 StringRef LiteralName 13003 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13004 if (LiteralName[0] != '_') { 13005 // C++11 [usrlit.suffix]p1: 13006 // Literal suffix identifiers that do not start with an underscore 13007 // are reserved for future standardization. 13008 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13009 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13010 } 13011 13012 return false; 13013 } 13014 13015 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13016 /// linkage specification, including the language and (if present) 13017 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13018 /// language string literal. LBraceLoc, if valid, provides the location of 13019 /// the '{' brace. Otherwise, this linkage specification does not 13020 /// have any braces. 13021 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13022 Expr *LangStr, 13023 SourceLocation LBraceLoc) { 13024 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13025 if (!Lit->isAscii()) { 13026 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13027 << LangStr->getSourceRange(); 13028 return nullptr; 13029 } 13030 13031 StringRef Lang = Lit->getString(); 13032 LinkageSpecDecl::LanguageIDs Language; 13033 if (Lang == "C") 13034 Language = LinkageSpecDecl::lang_c; 13035 else if (Lang == "C++") 13036 Language = LinkageSpecDecl::lang_cxx; 13037 else { 13038 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13039 << LangStr->getSourceRange(); 13040 return nullptr; 13041 } 13042 13043 // FIXME: Add all the various semantics of linkage specifications 13044 13045 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13046 LangStr->getExprLoc(), Language, 13047 LBraceLoc.isValid()); 13048 CurContext->addDecl(D); 13049 PushDeclContext(S, D); 13050 return D; 13051 } 13052 13053 /// ActOnFinishLinkageSpecification - Complete the definition of 13054 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13055 /// valid, it's the position of the closing '}' brace in a linkage 13056 /// specification that uses braces. 13057 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13058 Decl *LinkageSpec, 13059 SourceLocation RBraceLoc) { 13060 if (RBraceLoc.isValid()) { 13061 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13062 LSDecl->setRBraceLoc(RBraceLoc); 13063 } 13064 PopDeclContext(); 13065 return LinkageSpec; 13066 } 13067 13068 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13069 AttributeList *AttrList, 13070 SourceLocation SemiLoc) { 13071 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13072 // Attribute declarations appertain to empty declaration so we handle 13073 // them here. 13074 if (AttrList) 13075 ProcessDeclAttributeList(S, ED, AttrList); 13076 13077 CurContext->addDecl(ED); 13078 return ED; 13079 } 13080 13081 /// \brief Perform semantic analysis for the variable declaration that 13082 /// occurs within a C++ catch clause, returning the newly-created 13083 /// variable. 13084 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13085 TypeSourceInfo *TInfo, 13086 SourceLocation StartLoc, 13087 SourceLocation Loc, 13088 IdentifierInfo *Name) { 13089 bool Invalid = false; 13090 QualType ExDeclType = TInfo->getType(); 13091 13092 // Arrays and functions decay. 13093 if (ExDeclType->isArrayType()) 13094 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13095 else if (ExDeclType->isFunctionType()) 13096 ExDeclType = Context.getPointerType(ExDeclType); 13097 13098 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13099 // The exception-declaration shall not denote a pointer or reference to an 13100 // incomplete type, other than [cv] void*. 13101 // N2844 forbids rvalue references. 13102 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13103 Diag(Loc, diag::err_catch_rvalue_ref); 13104 Invalid = true; 13105 } 13106 13107 if (ExDeclType->isVariablyModifiedType()) { 13108 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13109 Invalid = true; 13110 } 13111 13112 QualType BaseType = ExDeclType; 13113 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13114 unsigned DK = diag::err_catch_incomplete; 13115 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13116 BaseType = Ptr->getPointeeType(); 13117 Mode = 1; 13118 DK = diag::err_catch_incomplete_ptr; 13119 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13120 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13121 BaseType = Ref->getPointeeType(); 13122 Mode = 2; 13123 DK = diag::err_catch_incomplete_ref; 13124 } 13125 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13126 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13127 Invalid = true; 13128 13129 if (!Invalid && !ExDeclType->isDependentType() && 13130 RequireNonAbstractType(Loc, ExDeclType, 13131 diag::err_abstract_type_in_decl, 13132 AbstractVariableType)) 13133 Invalid = true; 13134 13135 // Only the non-fragile NeXT runtime currently supports C++ catches 13136 // of ObjC types, and no runtime supports catching ObjC types by value. 13137 if (!Invalid && getLangOpts().ObjC1) { 13138 QualType T = ExDeclType; 13139 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13140 T = RT->getPointeeType(); 13141 13142 if (T->isObjCObjectType()) { 13143 Diag(Loc, diag::err_objc_object_catch); 13144 Invalid = true; 13145 } else if (T->isObjCObjectPointerType()) { 13146 // FIXME: should this be a test for macosx-fragile specifically? 13147 if (getLangOpts().ObjCRuntime.isFragile()) 13148 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13149 } 13150 } 13151 13152 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13153 ExDeclType, TInfo, SC_None); 13154 ExDecl->setExceptionVariable(true); 13155 13156 // In ARC, infer 'retaining' for variables of retainable type. 13157 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13158 Invalid = true; 13159 13160 if (!Invalid && !ExDeclType->isDependentType()) { 13161 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13162 // Insulate this from anything else we might currently be parsing. 13163 EnterExpressionEvaluationContext scope( 13164 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13165 13166 // C++ [except.handle]p16: 13167 // The object declared in an exception-declaration or, if the 13168 // exception-declaration does not specify a name, a temporary (12.2) is 13169 // copy-initialized (8.5) from the exception object. [...] 13170 // The object is destroyed when the handler exits, after the destruction 13171 // of any automatic objects initialized within the handler. 13172 // 13173 // We just pretend to initialize the object with itself, then make sure 13174 // it can be destroyed later. 13175 QualType initType = Context.getExceptionObjectType(ExDeclType); 13176 13177 InitializedEntity entity = 13178 InitializedEntity::InitializeVariable(ExDecl); 13179 InitializationKind initKind = 13180 InitializationKind::CreateCopy(Loc, SourceLocation()); 13181 13182 Expr *opaqueValue = 13183 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13184 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13185 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13186 if (result.isInvalid()) 13187 Invalid = true; 13188 else { 13189 // If the constructor used was non-trivial, set this as the 13190 // "initializer". 13191 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13192 if (!construct->getConstructor()->isTrivial()) { 13193 Expr *init = MaybeCreateExprWithCleanups(construct); 13194 ExDecl->setInit(init); 13195 } 13196 13197 // And make sure it's destructable. 13198 FinalizeVarWithDestructor(ExDecl, recordType); 13199 } 13200 } 13201 } 13202 13203 if (Invalid) 13204 ExDecl->setInvalidDecl(); 13205 13206 return ExDecl; 13207 } 13208 13209 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13210 /// handler. 13211 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13212 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13213 bool Invalid = D.isInvalidType(); 13214 13215 // Check for unexpanded parameter packs. 13216 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13217 UPPC_ExceptionType)) { 13218 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13219 D.getIdentifierLoc()); 13220 Invalid = true; 13221 } 13222 13223 IdentifierInfo *II = D.getIdentifier(); 13224 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13225 LookupOrdinaryName, 13226 ForRedeclaration)) { 13227 // The scope should be freshly made just for us. There is just no way 13228 // it contains any previous declaration, except for function parameters in 13229 // a function-try-block's catch statement. 13230 assert(!S->isDeclScope(PrevDecl)); 13231 if (isDeclInScope(PrevDecl, CurContext, S)) { 13232 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13233 << D.getIdentifier(); 13234 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13235 Invalid = true; 13236 } else if (PrevDecl->isTemplateParameter()) 13237 // Maybe we will complain about the shadowed template parameter. 13238 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13239 } 13240 13241 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13242 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13243 << D.getCXXScopeSpec().getRange(); 13244 Invalid = true; 13245 } 13246 13247 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13248 D.getLocStart(), 13249 D.getIdentifierLoc(), 13250 D.getIdentifier()); 13251 if (Invalid) 13252 ExDecl->setInvalidDecl(); 13253 13254 // Add the exception declaration into this scope. 13255 if (II) 13256 PushOnScopeChains(ExDecl, S); 13257 else 13258 CurContext->addDecl(ExDecl); 13259 13260 ProcessDeclAttributes(S, ExDecl, D); 13261 return ExDecl; 13262 } 13263 13264 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13265 Expr *AssertExpr, 13266 Expr *AssertMessageExpr, 13267 SourceLocation RParenLoc) { 13268 StringLiteral *AssertMessage = 13269 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13270 13271 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13272 return nullptr; 13273 13274 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13275 AssertMessage, RParenLoc, false); 13276 } 13277 13278 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13279 Expr *AssertExpr, 13280 StringLiteral *AssertMessage, 13281 SourceLocation RParenLoc, 13282 bool Failed) { 13283 assert(AssertExpr != nullptr && "Expected non-null condition"); 13284 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13285 !Failed) { 13286 // In a static_assert-declaration, the constant-expression shall be a 13287 // constant expression that can be contextually converted to bool. 13288 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13289 if (Converted.isInvalid()) 13290 Failed = true; 13291 13292 llvm::APSInt Cond; 13293 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13294 diag::err_static_assert_expression_is_not_constant, 13295 /*AllowFold=*/false).isInvalid()) 13296 Failed = true; 13297 13298 if (!Failed && !Cond) { 13299 SmallString<256> MsgBuffer; 13300 llvm::raw_svector_ostream Msg(MsgBuffer); 13301 if (AssertMessage) 13302 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13303 13304 Expr *InnerCond = nullptr; 13305 std::string InnerCondDescription; 13306 std::tie(InnerCond, InnerCondDescription) = 13307 findFailedBooleanCondition(Converted.get(), 13308 /*AllowTopLevelCond=*/false); 13309 if (InnerCond) { 13310 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13311 << InnerCondDescription << !AssertMessage 13312 << Msg.str() << InnerCond->getSourceRange(); 13313 } else { 13314 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13315 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13316 } 13317 Failed = true; 13318 } 13319 } 13320 13321 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13322 /*DiscardedValue*/false, 13323 /*IsConstexpr*/true); 13324 if (FullAssertExpr.isInvalid()) 13325 Failed = true; 13326 else 13327 AssertExpr = FullAssertExpr.get(); 13328 13329 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13330 AssertExpr, AssertMessage, RParenLoc, 13331 Failed); 13332 13333 CurContext->addDecl(Decl); 13334 return Decl; 13335 } 13336 13337 /// \brief Perform semantic analysis of the given friend type declaration. 13338 /// 13339 /// \returns A friend declaration that. 13340 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13341 SourceLocation FriendLoc, 13342 TypeSourceInfo *TSInfo) { 13343 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13344 13345 QualType T = TSInfo->getType(); 13346 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13347 13348 // C++03 [class.friend]p2: 13349 // An elaborated-type-specifier shall be used in a friend declaration 13350 // for a class.* 13351 // 13352 // * The class-key of the elaborated-type-specifier is required. 13353 if (!CodeSynthesisContexts.empty()) { 13354 // Do not complain about the form of friend template types during any kind 13355 // of code synthesis. For template instantiation, we will have complained 13356 // when the template was defined. 13357 } else { 13358 if (!T->isElaboratedTypeSpecifier()) { 13359 // If we evaluated the type to a record type, suggest putting 13360 // a tag in front. 13361 if (const RecordType *RT = T->getAs<RecordType>()) { 13362 RecordDecl *RD = RT->getDecl(); 13363 13364 SmallString<16> InsertionText(" "); 13365 InsertionText += RD->getKindName(); 13366 13367 Diag(TypeRange.getBegin(), 13368 getLangOpts().CPlusPlus11 ? 13369 diag::warn_cxx98_compat_unelaborated_friend_type : 13370 diag::ext_unelaborated_friend_type) 13371 << (unsigned) RD->getTagKind() 13372 << T 13373 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13374 InsertionText); 13375 } else { 13376 Diag(FriendLoc, 13377 getLangOpts().CPlusPlus11 ? 13378 diag::warn_cxx98_compat_nonclass_type_friend : 13379 diag::ext_nonclass_type_friend) 13380 << T 13381 << TypeRange; 13382 } 13383 } else if (T->getAs<EnumType>()) { 13384 Diag(FriendLoc, 13385 getLangOpts().CPlusPlus11 ? 13386 diag::warn_cxx98_compat_enum_friend : 13387 diag::ext_enum_friend) 13388 << T 13389 << TypeRange; 13390 } 13391 13392 // C++11 [class.friend]p3: 13393 // A friend declaration that does not declare a function shall have one 13394 // of the following forms: 13395 // friend elaborated-type-specifier ; 13396 // friend simple-type-specifier ; 13397 // friend typename-specifier ; 13398 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13399 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13400 } 13401 13402 // If the type specifier in a friend declaration designates a (possibly 13403 // cv-qualified) class type, that class is declared as a friend; otherwise, 13404 // the friend declaration is ignored. 13405 return FriendDecl::Create(Context, CurContext, 13406 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13407 FriendLoc); 13408 } 13409 13410 /// Handle a friend tag declaration where the scope specifier was 13411 /// templated. 13412 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13413 unsigned TagSpec, SourceLocation TagLoc, 13414 CXXScopeSpec &SS, 13415 IdentifierInfo *Name, 13416 SourceLocation NameLoc, 13417 AttributeList *Attr, 13418 MultiTemplateParamsArg TempParamLists) { 13419 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13420 13421 bool IsMemberSpecialization = false; 13422 bool Invalid = false; 13423 13424 if (TemplateParameterList *TemplateParams = 13425 MatchTemplateParametersToScopeSpecifier( 13426 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13427 IsMemberSpecialization, Invalid)) { 13428 if (TemplateParams->size() > 0) { 13429 // This is a declaration of a class template. 13430 if (Invalid) 13431 return nullptr; 13432 13433 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13434 NameLoc, Attr, TemplateParams, AS_public, 13435 /*ModulePrivateLoc=*/SourceLocation(), 13436 FriendLoc, TempParamLists.size() - 1, 13437 TempParamLists.data()).get(); 13438 } else { 13439 // The "template<>" header is extraneous. 13440 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13441 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13442 IsMemberSpecialization = true; 13443 } 13444 } 13445 13446 if (Invalid) return nullptr; 13447 13448 bool isAllExplicitSpecializations = true; 13449 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13450 if (TempParamLists[I]->size()) { 13451 isAllExplicitSpecializations = false; 13452 break; 13453 } 13454 } 13455 13456 // FIXME: don't ignore attributes. 13457 13458 // If it's explicit specializations all the way down, just forget 13459 // about the template header and build an appropriate non-templated 13460 // friend. TODO: for source fidelity, remember the headers. 13461 if (isAllExplicitSpecializations) { 13462 if (SS.isEmpty()) { 13463 bool Owned = false; 13464 bool IsDependent = false; 13465 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13466 Attr, AS_public, 13467 /*ModulePrivateLoc=*/SourceLocation(), 13468 MultiTemplateParamsArg(), Owned, IsDependent, 13469 /*ScopedEnumKWLoc=*/SourceLocation(), 13470 /*ScopedEnumUsesClassTag=*/false, 13471 /*UnderlyingType=*/TypeResult(), 13472 /*IsTypeSpecifier=*/false, 13473 /*IsTemplateParamOrArg=*/false); 13474 } 13475 13476 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13477 ElaboratedTypeKeyword Keyword 13478 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13479 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13480 *Name, NameLoc); 13481 if (T.isNull()) 13482 return nullptr; 13483 13484 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13485 if (isa<DependentNameType>(T)) { 13486 DependentNameTypeLoc TL = 13487 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13488 TL.setElaboratedKeywordLoc(TagLoc); 13489 TL.setQualifierLoc(QualifierLoc); 13490 TL.setNameLoc(NameLoc); 13491 } else { 13492 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13493 TL.setElaboratedKeywordLoc(TagLoc); 13494 TL.setQualifierLoc(QualifierLoc); 13495 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13496 } 13497 13498 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13499 TSI, FriendLoc, TempParamLists); 13500 Friend->setAccess(AS_public); 13501 CurContext->addDecl(Friend); 13502 return Friend; 13503 } 13504 13505 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13506 13507 13508 13509 // Handle the case of a templated-scope friend class. e.g. 13510 // template <class T> class A<T>::B; 13511 // FIXME: we don't support these right now. 13512 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13513 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13514 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13515 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13516 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13517 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13518 TL.setElaboratedKeywordLoc(TagLoc); 13519 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13520 TL.setNameLoc(NameLoc); 13521 13522 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13523 TSI, FriendLoc, TempParamLists); 13524 Friend->setAccess(AS_public); 13525 Friend->setUnsupportedFriend(true); 13526 CurContext->addDecl(Friend); 13527 return Friend; 13528 } 13529 13530 13531 /// Handle a friend type declaration. This works in tandem with 13532 /// ActOnTag. 13533 /// 13534 /// Notes on friend class templates: 13535 /// 13536 /// We generally treat friend class declarations as if they were 13537 /// declaring a class. So, for example, the elaborated type specifier 13538 /// in a friend declaration is required to obey the restrictions of a 13539 /// class-head (i.e. no typedefs in the scope chain), template 13540 /// parameters are required to match up with simple template-ids, &c. 13541 /// However, unlike when declaring a template specialization, it's 13542 /// okay to refer to a template specialization without an empty 13543 /// template parameter declaration, e.g. 13544 /// friend class A<T>::B<unsigned>; 13545 /// We permit this as a special case; if there are any template 13546 /// parameters present at all, require proper matching, i.e. 13547 /// template <> template \<class T> friend class A<int>::B; 13548 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13549 MultiTemplateParamsArg TempParams) { 13550 SourceLocation Loc = DS.getLocStart(); 13551 13552 assert(DS.isFriendSpecified()); 13553 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13554 13555 // Try to convert the decl specifier to a type. This works for 13556 // friend templates because ActOnTag never produces a ClassTemplateDecl 13557 // for a TUK_Friend. 13558 Declarator TheDeclarator(DS, Declarator::MemberContext); 13559 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13560 QualType T = TSI->getType(); 13561 if (TheDeclarator.isInvalidType()) 13562 return nullptr; 13563 13564 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13565 return nullptr; 13566 13567 // This is definitely an error in C++98. It's probably meant to 13568 // be forbidden in C++0x, too, but the specification is just 13569 // poorly written. 13570 // 13571 // The problem is with declarations like the following: 13572 // template <T> friend A<T>::foo; 13573 // where deciding whether a class C is a friend or not now hinges 13574 // on whether there exists an instantiation of A that causes 13575 // 'foo' to equal C. There are restrictions on class-heads 13576 // (which we declare (by fiat) elaborated friend declarations to 13577 // be) that makes this tractable. 13578 // 13579 // FIXME: handle "template <> friend class A<T>;", which 13580 // is possibly well-formed? Who even knows? 13581 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13582 Diag(Loc, diag::err_tagless_friend_type_template) 13583 << DS.getSourceRange(); 13584 return nullptr; 13585 } 13586 13587 // C++98 [class.friend]p1: A friend of a class is a function 13588 // or class that is not a member of the class . . . 13589 // This is fixed in DR77, which just barely didn't make the C++03 13590 // deadline. It's also a very silly restriction that seriously 13591 // affects inner classes and which nobody else seems to implement; 13592 // thus we never diagnose it, not even in -pedantic. 13593 // 13594 // But note that we could warn about it: it's always useless to 13595 // friend one of your own members (it's not, however, worthless to 13596 // friend a member of an arbitrary specialization of your template). 13597 13598 Decl *D; 13599 if (!TempParams.empty()) 13600 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13601 TempParams, 13602 TSI, 13603 DS.getFriendSpecLoc()); 13604 else 13605 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13606 13607 if (!D) 13608 return nullptr; 13609 13610 D->setAccess(AS_public); 13611 CurContext->addDecl(D); 13612 13613 return D; 13614 } 13615 13616 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13617 MultiTemplateParamsArg TemplateParams) { 13618 const DeclSpec &DS = D.getDeclSpec(); 13619 13620 assert(DS.isFriendSpecified()); 13621 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13622 13623 SourceLocation Loc = D.getIdentifierLoc(); 13624 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13625 13626 // C++ [class.friend]p1 13627 // A friend of a class is a function or class.... 13628 // Note that this sees through typedefs, which is intended. 13629 // It *doesn't* see through dependent types, which is correct 13630 // according to [temp.arg.type]p3: 13631 // If a declaration acquires a function type through a 13632 // type dependent on a template-parameter and this causes 13633 // a declaration that does not use the syntactic form of a 13634 // function declarator to have a function type, the program 13635 // is ill-formed. 13636 if (!TInfo->getType()->isFunctionType()) { 13637 Diag(Loc, diag::err_unexpected_friend); 13638 13639 // It might be worthwhile to try to recover by creating an 13640 // appropriate declaration. 13641 return nullptr; 13642 } 13643 13644 // C++ [namespace.memdef]p3 13645 // - If a friend declaration in a non-local class first declares a 13646 // class or function, the friend class or function is a member 13647 // of the innermost enclosing namespace. 13648 // - The name of the friend is not found by simple name lookup 13649 // until a matching declaration is provided in that namespace 13650 // scope (either before or after the class declaration granting 13651 // friendship). 13652 // - If a friend function is called, its name may be found by the 13653 // name lookup that considers functions from namespaces and 13654 // classes associated with the types of the function arguments. 13655 // - When looking for a prior declaration of a class or a function 13656 // declared as a friend, scopes outside the innermost enclosing 13657 // namespace scope are not considered. 13658 13659 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13660 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13661 DeclarationName Name = NameInfo.getName(); 13662 assert(Name); 13663 13664 // Check for unexpanded parameter packs. 13665 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13666 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13667 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13668 return nullptr; 13669 13670 // The context we found the declaration in, or in which we should 13671 // create the declaration. 13672 DeclContext *DC; 13673 Scope *DCScope = S; 13674 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13675 ForRedeclaration); 13676 13677 // There are five cases here. 13678 // - There's no scope specifier and we're in a local class. Only look 13679 // for functions declared in the immediately-enclosing block scope. 13680 // We recover from invalid scope qualifiers as if they just weren't there. 13681 FunctionDecl *FunctionContainingLocalClass = nullptr; 13682 if ((SS.isInvalid() || !SS.isSet()) && 13683 (FunctionContainingLocalClass = 13684 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13685 // C++11 [class.friend]p11: 13686 // If a friend declaration appears in a local class and the name 13687 // specified is an unqualified name, a prior declaration is 13688 // looked up without considering scopes that are outside the 13689 // innermost enclosing non-class scope. For a friend function 13690 // declaration, if there is no prior declaration, the program is 13691 // ill-formed. 13692 13693 // Find the innermost enclosing non-class scope. This is the block 13694 // scope containing the local class definition (or for a nested class, 13695 // the outer local class). 13696 DCScope = S->getFnParent(); 13697 13698 // Look up the function name in the scope. 13699 Previous.clear(LookupLocalFriendName); 13700 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13701 13702 if (!Previous.empty()) { 13703 // All possible previous declarations must have the same context: 13704 // either they were declared at block scope or they are members of 13705 // one of the enclosing local classes. 13706 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13707 } else { 13708 // This is ill-formed, but provide the context that we would have 13709 // declared the function in, if we were permitted to, for error recovery. 13710 DC = FunctionContainingLocalClass; 13711 } 13712 adjustContextForLocalExternDecl(DC); 13713 13714 // C++ [class.friend]p6: 13715 // A function can be defined in a friend declaration of a class if and 13716 // only if the class is a non-local class (9.8), the function name is 13717 // unqualified, and the function has namespace scope. 13718 if (D.isFunctionDefinition()) { 13719 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13720 } 13721 13722 // - There's no scope specifier, in which case we just go to the 13723 // appropriate scope and look for a function or function template 13724 // there as appropriate. 13725 } else if (SS.isInvalid() || !SS.isSet()) { 13726 // C++11 [namespace.memdef]p3: 13727 // If the name in a friend declaration is neither qualified nor 13728 // a template-id and the declaration is a function or an 13729 // elaborated-type-specifier, the lookup to determine whether 13730 // the entity has been previously declared shall not consider 13731 // any scopes outside the innermost enclosing namespace. 13732 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 13733 13734 // Find the appropriate context according to the above. 13735 DC = CurContext; 13736 13737 // Skip class contexts. If someone can cite chapter and verse 13738 // for this behavior, that would be nice --- it's what GCC and 13739 // EDG do, and it seems like a reasonable intent, but the spec 13740 // really only says that checks for unqualified existing 13741 // declarations should stop at the nearest enclosing namespace, 13742 // not that they should only consider the nearest enclosing 13743 // namespace. 13744 while (DC->isRecord()) 13745 DC = DC->getParent(); 13746 13747 DeclContext *LookupDC = DC; 13748 while (LookupDC->isTransparentContext()) 13749 LookupDC = LookupDC->getParent(); 13750 13751 while (true) { 13752 LookupQualifiedName(Previous, LookupDC); 13753 13754 if (!Previous.empty()) { 13755 DC = LookupDC; 13756 break; 13757 } 13758 13759 if (isTemplateId) { 13760 if (isa<TranslationUnitDecl>(LookupDC)) break; 13761 } else { 13762 if (LookupDC->isFileContext()) break; 13763 } 13764 LookupDC = LookupDC->getParent(); 13765 } 13766 13767 DCScope = getScopeForDeclContext(S, DC); 13768 13769 // - There's a non-dependent scope specifier, in which case we 13770 // compute it and do a previous lookup there for a function 13771 // or function template. 13772 } else if (!SS.getScopeRep()->isDependent()) { 13773 DC = computeDeclContext(SS); 13774 if (!DC) return nullptr; 13775 13776 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13777 13778 LookupQualifiedName(Previous, DC); 13779 13780 // Ignore things found implicitly in the wrong scope. 13781 // TODO: better diagnostics for this case. Suggesting the right 13782 // qualified scope would be nice... 13783 LookupResult::Filter F = Previous.makeFilter(); 13784 while (F.hasNext()) { 13785 NamedDecl *D = F.next(); 13786 if (!DC->InEnclosingNamespaceSetOf( 13787 D->getDeclContext()->getRedeclContext())) 13788 F.erase(); 13789 } 13790 F.done(); 13791 13792 if (Previous.empty()) { 13793 D.setInvalidType(); 13794 Diag(Loc, diag::err_qualified_friend_not_found) 13795 << Name << TInfo->getType(); 13796 return nullptr; 13797 } 13798 13799 // C++ [class.friend]p1: A friend of a class is a function or 13800 // class that is not a member of the class . . . 13801 if (DC->Equals(CurContext)) 13802 Diag(DS.getFriendSpecLoc(), 13803 getLangOpts().CPlusPlus11 ? 13804 diag::warn_cxx98_compat_friend_is_member : 13805 diag::err_friend_is_member); 13806 13807 if (D.isFunctionDefinition()) { 13808 // C++ [class.friend]p6: 13809 // A function can be defined in a friend declaration of a class if and 13810 // only if the class is a non-local class (9.8), the function name is 13811 // unqualified, and the function has namespace scope. 13812 SemaDiagnosticBuilder DB 13813 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 13814 13815 DB << SS.getScopeRep(); 13816 if (DC->isFileContext()) 13817 DB << FixItHint::CreateRemoval(SS.getRange()); 13818 SS.clear(); 13819 } 13820 13821 // - There's a scope specifier that does not match any template 13822 // parameter lists, in which case we use some arbitrary context, 13823 // create a method or method template, and wait for instantiation. 13824 // - There's a scope specifier that does match some template 13825 // parameter lists, which we don't handle right now. 13826 } else { 13827 if (D.isFunctionDefinition()) { 13828 // C++ [class.friend]p6: 13829 // A function can be defined in a friend declaration of a class if and 13830 // only if the class is a non-local class (9.8), the function name is 13831 // unqualified, and the function has namespace scope. 13832 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 13833 << SS.getScopeRep(); 13834 } 13835 13836 DC = CurContext; 13837 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 13838 } 13839 13840 if (!DC->isRecord()) { 13841 int DiagArg = -1; 13842 switch (D.getName().getKind()) { 13843 case UnqualifiedId::IK_ConstructorTemplateId: 13844 case UnqualifiedId::IK_ConstructorName: 13845 DiagArg = 0; 13846 break; 13847 case UnqualifiedId::IK_DestructorName: 13848 DiagArg = 1; 13849 break; 13850 case UnqualifiedId::IK_ConversionFunctionId: 13851 DiagArg = 2; 13852 break; 13853 case UnqualifiedId::IK_DeductionGuideName: 13854 DiagArg = 3; 13855 break; 13856 case UnqualifiedId::IK_Identifier: 13857 case UnqualifiedId::IK_ImplicitSelfParam: 13858 case UnqualifiedId::IK_LiteralOperatorId: 13859 case UnqualifiedId::IK_OperatorFunctionId: 13860 case UnqualifiedId::IK_TemplateId: 13861 break; 13862 } 13863 // This implies that it has to be an operator or function. 13864 if (DiagArg >= 0) { 13865 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 13866 return nullptr; 13867 } 13868 } 13869 13870 // FIXME: This is an egregious hack to cope with cases where the scope stack 13871 // does not contain the declaration context, i.e., in an out-of-line 13872 // definition of a class. 13873 Scope FakeDCScope(S, Scope::DeclScope, Diags); 13874 if (!DCScope) { 13875 FakeDCScope.setEntity(DC); 13876 DCScope = &FakeDCScope; 13877 } 13878 13879 bool AddToScope = true; 13880 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 13881 TemplateParams, AddToScope); 13882 if (!ND) return nullptr; 13883 13884 assert(ND->getLexicalDeclContext() == CurContext); 13885 13886 // If we performed typo correction, we might have added a scope specifier 13887 // and changed the decl context. 13888 DC = ND->getDeclContext(); 13889 13890 // Add the function declaration to the appropriate lookup tables, 13891 // adjusting the redeclarations list as necessary. We don't 13892 // want to do this yet if the friending class is dependent. 13893 // 13894 // Also update the scope-based lookup if the target context's 13895 // lookup context is in lexical scope. 13896 if (!CurContext->isDependentContext()) { 13897 DC = DC->getRedeclContext(); 13898 DC->makeDeclVisibleInContext(ND); 13899 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13900 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 13901 } 13902 13903 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 13904 D.getIdentifierLoc(), ND, 13905 DS.getFriendSpecLoc()); 13906 FrD->setAccess(AS_public); 13907 CurContext->addDecl(FrD); 13908 13909 if (ND->isInvalidDecl()) { 13910 FrD->setInvalidDecl(); 13911 } else { 13912 if (DC->isRecord()) CheckFriendAccess(ND); 13913 13914 FunctionDecl *FD; 13915 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 13916 FD = FTD->getTemplatedDecl(); 13917 else 13918 FD = cast<FunctionDecl>(ND); 13919 13920 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 13921 // default argument expression, that declaration shall be a definition 13922 // and shall be the only declaration of the function or function 13923 // template in the translation unit. 13924 if (functionDeclHasDefaultArgument(FD)) { 13925 // We can't look at FD->getPreviousDecl() because it may not have been set 13926 // if we're in a dependent context. If the function is known to be a 13927 // redeclaration, we will have narrowed Previous down to the right decl. 13928 if (D.isRedeclaration()) { 13929 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 13930 Diag(Previous.getRepresentativeDecl()->getLocation(), 13931 diag::note_previous_declaration); 13932 } else if (!D.isFunctionDefinition()) 13933 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 13934 } 13935 13936 // Mark templated-scope function declarations as unsupported. 13937 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 13938 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 13939 << SS.getScopeRep() << SS.getRange() 13940 << cast<CXXRecordDecl>(CurContext); 13941 FrD->setUnsupportedFriend(true); 13942 } 13943 } 13944 13945 return ND; 13946 } 13947 13948 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 13949 AdjustDeclIfTemplate(Dcl); 13950 13951 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 13952 if (!Fn) { 13953 Diag(DelLoc, diag::err_deleted_non_function); 13954 return; 13955 } 13956 13957 // Deleted function does not have a body. 13958 Fn->setWillHaveBody(false); 13959 13960 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 13961 // Don't consider the implicit declaration we generate for explicit 13962 // specializations. FIXME: Do not generate these implicit declarations. 13963 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 13964 Prev->getPreviousDecl()) && 13965 !Prev->isDefined()) { 13966 Diag(DelLoc, diag::err_deleted_decl_not_first); 13967 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 13968 Prev->isImplicit() ? diag::note_previous_implicit_declaration 13969 : diag::note_previous_declaration); 13970 } 13971 // If the declaration wasn't the first, we delete the function anyway for 13972 // recovery. 13973 Fn = Fn->getCanonicalDecl(); 13974 } 13975 13976 // dllimport/dllexport cannot be deleted. 13977 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 13978 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 13979 Fn->setInvalidDecl(); 13980 } 13981 13982 if (Fn->isDeleted()) 13983 return; 13984 13985 // See if we're deleting a function which is already known to override a 13986 // non-deleted virtual function. 13987 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 13988 bool IssuedDiagnostic = false; 13989 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 13990 E = MD->end_overridden_methods(); 13991 I != E; ++I) { 13992 if (!(*MD->begin_overridden_methods())->isDeleted()) { 13993 if (!IssuedDiagnostic) { 13994 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 13995 IssuedDiagnostic = true; 13996 } 13997 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 13998 } 13999 } 14000 // If this function was implicitly deleted because it was defaulted, 14001 // explain why it was deleted. 14002 if (IssuedDiagnostic && MD->isDefaulted()) 14003 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14004 /*Diagnose*/true); 14005 } 14006 14007 // C++11 [basic.start.main]p3: 14008 // A program that defines main as deleted [...] is ill-formed. 14009 if (Fn->isMain()) 14010 Diag(DelLoc, diag::err_deleted_main); 14011 14012 // C++11 [dcl.fct.def.delete]p4: 14013 // A deleted function is implicitly inline. 14014 Fn->setImplicitlyInline(); 14015 Fn->setDeletedAsWritten(); 14016 } 14017 14018 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14019 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14020 14021 if (MD) { 14022 if (MD->getParent()->isDependentType()) { 14023 MD->setDefaulted(); 14024 MD->setExplicitlyDefaulted(); 14025 return; 14026 } 14027 14028 CXXSpecialMember Member = getSpecialMember(MD); 14029 if (Member == CXXInvalid) { 14030 if (!MD->isInvalidDecl()) 14031 Diag(DefaultLoc, diag::err_default_special_members); 14032 return; 14033 } 14034 14035 MD->setDefaulted(); 14036 MD->setExplicitlyDefaulted(); 14037 14038 // Unset that we will have a body for this function. We might not, 14039 // if it turns out to be trivial, and we don't need this marking now 14040 // that we've marked it as defaulted. 14041 MD->setWillHaveBody(false); 14042 14043 // If this definition appears within the record, do the checking when 14044 // the record is complete. 14045 const FunctionDecl *Primary = MD; 14046 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14047 // Ask the template instantiation pattern that actually had the 14048 // '= default' on it. 14049 Primary = Pattern; 14050 14051 // If the method was defaulted on its first declaration, we will have 14052 // already performed the checking in CheckCompletedCXXClass. Such a 14053 // declaration doesn't trigger an implicit definition. 14054 if (Primary->getCanonicalDecl()->isDefaulted()) 14055 return; 14056 14057 CheckExplicitlyDefaultedSpecialMember(MD); 14058 14059 if (!MD->isInvalidDecl()) 14060 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14061 } else { 14062 Diag(DefaultLoc, diag::err_default_special_members); 14063 } 14064 } 14065 14066 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14067 for (Stmt *SubStmt : S->children()) { 14068 if (!SubStmt) 14069 continue; 14070 if (isa<ReturnStmt>(SubStmt)) 14071 Self.Diag(SubStmt->getLocStart(), 14072 diag::err_return_in_constructor_handler); 14073 if (!isa<Expr>(SubStmt)) 14074 SearchForReturnInStmt(Self, SubStmt); 14075 } 14076 } 14077 14078 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14079 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14080 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14081 SearchForReturnInStmt(*this, Handler); 14082 } 14083 } 14084 14085 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14086 const CXXMethodDecl *Old) { 14087 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14088 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14089 14090 if (OldFT->hasExtParameterInfos()) { 14091 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14092 // A parameter of the overriding method should be annotated with noescape 14093 // if the corresponding parameter of the overridden method is annotated. 14094 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14095 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14096 Diag(New->getParamDecl(I)->getLocation(), 14097 diag::warn_overriding_method_missing_noescape); 14098 Diag(Old->getParamDecl(I)->getLocation(), 14099 diag::note_overridden_marked_noescape); 14100 } 14101 } 14102 14103 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14104 14105 // If the calling conventions match, everything is fine 14106 if (NewCC == OldCC) 14107 return false; 14108 14109 // If the calling conventions mismatch because the new function is static, 14110 // suppress the calling convention mismatch error; the error about static 14111 // function override (err_static_overrides_virtual from 14112 // Sema::CheckFunctionDeclaration) is more clear. 14113 if (New->getStorageClass() == SC_Static) 14114 return false; 14115 14116 Diag(New->getLocation(), 14117 diag::err_conflicting_overriding_cc_attributes) 14118 << New->getDeclName() << New->getType() << Old->getType(); 14119 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14120 return true; 14121 } 14122 14123 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14124 const CXXMethodDecl *Old) { 14125 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14126 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14127 14128 if (Context.hasSameType(NewTy, OldTy) || 14129 NewTy->isDependentType() || OldTy->isDependentType()) 14130 return false; 14131 14132 // Check if the return types are covariant 14133 QualType NewClassTy, OldClassTy; 14134 14135 /// Both types must be pointers or references to classes. 14136 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14137 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14138 NewClassTy = NewPT->getPointeeType(); 14139 OldClassTy = OldPT->getPointeeType(); 14140 } 14141 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14142 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14143 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14144 NewClassTy = NewRT->getPointeeType(); 14145 OldClassTy = OldRT->getPointeeType(); 14146 } 14147 } 14148 } 14149 14150 // The return types aren't either both pointers or references to a class type. 14151 if (NewClassTy.isNull()) { 14152 Diag(New->getLocation(), 14153 diag::err_different_return_type_for_overriding_virtual_function) 14154 << New->getDeclName() << NewTy << OldTy 14155 << New->getReturnTypeSourceRange(); 14156 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14157 << Old->getReturnTypeSourceRange(); 14158 14159 return true; 14160 } 14161 14162 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14163 // C++14 [class.virtual]p8: 14164 // If the class type in the covariant return type of D::f differs from 14165 // that of B::f, the class type in the return type of D::f shall be 14166 // complete at the point of declaration of D::f or shall be the class 14167 // type D. 14168 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14169 if (!RT->isBeingDefined() && 14170 RequireCompleteType(New->getLocation(), NewClassTy, 14171 diag::err_covariant_return_incomplete, 14172 New->getDeclName())) 14173 return true; 14174 } 14175 14176 // Check if the new class derives from the old class. 14177 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14178 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14179 << New->getDeclName() << NewTy << OldTy 14180 << New->getReturnTypeSourceRange(); 14181 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14182 << Old->getReturnTypeSourceRange(); 14183 return true; 14184 } 14185 14186 // Check if we the conversion from derived to base is valid. 14187 if (CheckDerivedToBaseConversion( 14188 NewClassTy, OldClassTy, 14189 diag::err_covariant_return_inaccessible_base, 14190 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14191 New->getLocation(), New->getReturnTypeSourceRange(), 14192 New->getDeclName(), nullptr)) { 14193 // FIXME: this note won't trigger for delayed access control 14194 // diagnostics, and it's impossible to get an undelayed error 14195 // here from access control during the original parse because 14196 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14197 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14198 << Old->getReturnTypeSourceRange(); 14199 return true; 14200 } 14201 } 14202 14203 // The qualifiers of the return types must be the same. 14204 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14205 Diag(New->getLocation(), 14206 diag::err_covariant_return_type_different_qualifications) 14207 << New->getDeclName() << NewTy << OldTy 14208 << New->getReturnTypeSourceRange(); 14209 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14210 << Old->getReturnTypeSourceRange(); 14211 return true; 14212 } 14213 14214 14215 // The new class type must have the same or less qualifiers as the old type. 14216 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14217 Diag(New->getLocation(), 14218 diag::err_covariant_return_type_class_type_more_qualified) 14219 << New->getDeclName() << NewTy << OldTy 14220 << New->getReturnTypeSourceRange(); 14221 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14222 << Old->getReturnTypeSourceRange(); 14223 return true; 14224 } 14225 14226 return false; 14227 } 14228 14229 /// \brief Mark the given method pure. 14230 /// 14231 /// \param Method the method to be marked pure. 14232 /// 14233 /// \param InitRange the source range that covers the "0" initializer. 14234 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14235 SourceLocation EndLoc = InitRange.getEnd(); 14236 if (EndLoc.isValid()) 14237 Method->setRangeEnd(EndLoc); 14238 14239 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14240 Method->setPure(); 14241 return false; 14242 } 14243 14244 if (!Method->isInvalidDecl()) 14245 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14246 << Method->getDeclName() << InitRange; 14247 return true; 14248 } 14249 14250 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14251 if (D->getFriendObjectKind()) 14252 Diag(D->getLocation(), diag::err_pure_friend); 14253 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14254 CheckPureMethod(M, ZeroLoc); 14255 else 14256 Diag(D->getLocation(), diag::err_illegal_initializer); 14257 } 14258 14259 /// \brief Determine whether the given declaration is a global variable or 14260 /// static data member. 14261 static bool isNonlocalVariable(const Decl *D) { 14262 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14263 return Var->hasGlobalStorage(); 14264 14265 return false; 14266 } 14267 14268 /// Invoked when we are about to parse an initializer for the declaration 14269 /// 'Dcl'. 14270 /// 14271 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14272 /// static data member of class X, names should be looked up in the scope of 14273 /// class X. If the declaration had a scope specifier, a scope will have 14274 /// been created and passed in for this purpose. Otherwise, S will be null. 14275 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14276 // If there is no declaration, there was an error parsing it. 14277 if (!D || D->isInvalidDecl()) 14278 return; 14279 14280 // We will always have a nested name specifier here, but this declaration 14281 // might not be out of line if the specifier names the current namespace: 14282 // extern int n; 14283 // int ::n = 0; 14284 if (S && D->isOutOfLine()) 14285 EnterDeclaratorContext(S, D->getDeclContext()); 14286 14287 // If we are parsing the initializer for a static data member, push a 14288 // new expression evaluation context that is associated with this static 14289 // data member. 14290 if (isNonlocalVariable(D)) 14291 PushExpressionEvaluationContext( 14292 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14293 } 14294 14295 /// Invoked after we are finished parsing an initializer for the declaration D. 14296 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14297 // If there is no declaration, there was an error parsing it. 14298 if (!D || D->isInvalidDecl()) 14299 return; 14300 14301 if (isNonlocalVariable(D)) 14302 PopExpressionEvaluationContext(); 14303 14304 if (S && D->isOutOfLine()) 14305 ExitDeclaratorContext(S); 14306 } 14307 14308 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14309 /// C++ if/switch/while/for statement. 14310 /// e.g: "if (int x = f()) {...}" 14311 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14312 // C++ 6.4p2: 14313 // The declarator shall not specify a function or an array. 14314 // The type-specifier-seq shall not contain typedef and shall not declare a 14315 // new class or enumeration. 14316 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14317 "Parser allowed 'typedef' as storage class of condition decl."); 14318 14319 Decl *Dcl = ActOnDeclarator(S, D); 14320 if (!Dcl) 14321 return true; 14322 14323 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14324 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14325 << D.getSourceRange(); 14326 return true; 14327 } 14328 14329 return Dcl; 14330 } 14331 14332 void Sema::LoadExternalVTableUses() { 14333 if (!ExternalSource) 14334 return; 14335 14336 SmallVector<ExternalVTableUse, 4> VTables; 14337 ExternalSource->ReadUsedVTables(VTables); 14338 SmallVector<VTableUse, 4> NewUses; 14339 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14340 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14341 = VTablesUsed.find(VTables[I].Record); 14342 // Even if a definition wasn't required before, it may be required now. 14343 if (Pos != VTablesUsed.end()) { 14344 if (!Pos->second && VTables[I].DefinitionRequired) 14345 Pos->second = true; 14346 continue; 14347 } 14348 14349 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14350 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14351 } 14352 14353 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14354 } 14355 14356 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14357 bool DefinitionRequired) { 14358 // Ignore any vtable uses in unevaluated operands or for classes that do 14359 // not have a vtable. 14360 if (!Class->isDynamicClass() || Class->isDependentContext() || 14361 CurContext->isDependentContext() || isUnevaluatedContext()) 14362 return; 14363 14364 // Try to insert this class into the map. 14365 LoadExternalVTableUses(); 14366 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14367 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14368 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14369 if (!Pos.second) { 14370 // If we already had an entry, check to see if we are promoting this vtable 14371 // to require a definition. If so, we need to reappend to the VTableUses 14372 // list, since we may have already processed the first entry. 14373 if (DefinitionRequired && !Pos.first->second) { 14374 Pos.first->second = true; 14375 } else { 14376 // Otherwise, we can early exit. 14377 return; 14378 } 14379 } else { 14380 // The Microsoft ABI requires that we perform the destructor body 14381 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14382 // the deleting destructor is emitted with the vtable, not with the 14383 // destructor definition as in the Itanium ABI. 14384 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14385 CXXDestructorDecl *DD = Class->getDestructor(); 14386 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14387 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14388 // If this is an out-of-line declaration, marking it referenced will 14389 // not do anything. Manually call CheckDestructor to look up operator 14390 // delete(). 14391 ContextRAII SavedContext(*this, DD); 14392 CheckDestructor(DD); 14393 } else { 14394 MarkFunctionReferenced(Loc, Class->getDestructor()); 14395 } 14396 } 14397 } 14398 } 14399 14400 // Local classes need to have their virtual members marked 14401 // immediately. For all other classes, we mark their virtual members 14402 // at the end of the translation unit. 14403 if (Class->isLocalClass()) 14404 MarkVirtualMembersReferenced(Loc, Class); 14405 else 14406 VTableUses.push_back(std::make_pair(Class, Loc)); 14407 } 14408 14409 bool Sema::DefineUsedVTables() { 14410 LoadExternalVTableUses(); 14411 if (VTableUses.empty()) 14412 return false; 14413 14414 // Note: The VTableUses vector could grow as a result of marking 14415 // the members of a class as "used", so we check the size each 14416 // time through the loop and prefer indices (which are stable) to 14417 // iterators (which are not). 14418 bool DefinedAnything = false; 14419 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14420 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14421 if (!Class) 14422 continue; 14423 TemplateSpecializationKind ClassTSK = 14424 Class->getTemplateSpecializationKind(); 14425 14426 SourceLocation Loc = VTableUses[I].second; 14427 14428 bool DefineVTable = true; 14429 14430 // If this class has a key function, but that key function is 14431 // defined in another translation unit, we don't need to emit the 14432 // vtable even though we're using it. 14433 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14434 if (KeyFunction && !KeyFunction->hasBody()) { 14435 // The key function is in another translation unit. 14436 DefineVTable = false; 14437 TemplateSpecializationKind TSK = 14438 KeyFunction->getTemplateSpecializationKind(); 14439 assert(TSK != TSK_ExplicitInstantiationDefinition && 14440 TSK != TSK_ImplicitInstantiation && 14441 "Instantiations don't have key functions"); 14442 (void)TSK; 14443 } else if (!KeyFunction) { 14444 // If we have a class with no key function that is the subject 14445 // of an explicit instantiation declaration, suppress the 14446 // vtable; it will live with the explicit instantiation 14447 // definition. 14448 bool IsExplicitInstantiationDeclaration = 14449 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14450 for (auto R : Class->redecls()) { 14451 TemplateSpecializationKind TSK 14452 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14453 if (TSK == TSK_ExplicitInstantiationDeclaration) 14454 IsExplicitInstantiationDeclaration = true; 14455 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14456 IsExplicitInstantiationDeclaration = false; 14457 break; 14458 } 14459 } 14460 14461 if (IsExplicitInstantiationDeclaration) 14462 DefineVTable = false; 14463 } 14464 14465 // The exception specifications for all virtual members may be needed even 14466 // if we are not providing an authoritative form of the vtable in this TU. 14467 // We may choose to emit it available_externally anyway. 14468 if (!DefineVTable) { 14469 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14470 continue; 14471 } 14472 14473 // Mark all of the virtual members of this class as referenced, so 14474 // that we can build a vtable. Then, tell the AST consumer that a 14475 // vtable for this class is required. 14476 DefinedAnything = true; 14477 MarkVirtualMembersReferenced(Loc, Class); 14478 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14479 if (VTablesUsed[Canonical]) 14480 Consumer.HandleVTable(Class); 14481 14482 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14483 // no key function or the key function is inlined. Don't warn in C++ ABIs 14484 // that lack key functions, since the user won't be able to make one. 14485 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14486 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14487 const FunctionDecl *KeyFunctionDef = nullptr; 14488 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14489 KeyFunctionDef->isInlined())) { 14490 Diag(Class->getLocation(), 14491 ClassTSK == TSK_ExplicitInstantiationDefinition 14492 ? diag::warn_weak_template_vtable 14493 : diag::warn_weak_vtable) 14494 << Class; 14495 } 14496 } 14497 } 14498 VTableUses.clear(); 14499 14500 return DefinedAnything; 14501 } 14502 14503 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14504 const CXXRecordDecl *RD) { 14505 for (const auto *I : RD->methods()) 14506 if (I->isVirtual() && !I->isPure()) 14507 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14508 } 14509 14510 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14511 const CXXRecordDecl *RD) { 14512 // Mark all functions which will appear in RD's vtable as used. 14513 CXXFinalOverriderMap FinalOverriders; 14514 RD->getFinalOverriders(FinalOverriders); 14515 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14516 E = FinalOverriders.end(); 14517 I != E; ++I) { 14518 for (OverridingMethods::const_iterator OI = I->second.begin(), 14519 OE = I->second.end(); 14520 OI != OE; ++OI) { 14521 assert(OI->second.size() > 0 && "no final overrider"); 14522 CXXMethodDecl *Overrider = OI->second.front().Method; 14523 14524 // C++ [basic.def.odr]p2: 14525 // [...] A virtual member function is used if it is not pure. [...] 14526 if (!Overrider->isPure()) 14527 MarkFunctionReferenced(Loc, Overrider); 14528 } 14529 } 14530 14531 // Only classes that have virtual bases need a VTT. 14532 if (RD->getNumVBases() == 0) 14533 return; 14534 14535 for (const auto &I : RD->bases()) { 14536 const CXXRecordDecl *Base = 14537 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14538 if (Base->getNumVBases() == 0) 14539 continue; 14540 MarkVirtualMembersReferenced(Loc, Base); 14541 } 14542 } 14543 14544 /// SetIvarInitializers - This routine builds initialization ASTs for the 14545 /// Objective-C implementation whose ivars need be initialized. 14546 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14547 if (!getLangOpts().CPlusPlus) 14548 return; 14549 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14550 SmallVector<ObjCIvarDecl*, 8> ivars; 14551 CollectIvarsToConstructOrDestruct(OID, ivars); 14552 if (ivars.empty()) 14553 return; 14554 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14555 for (unsigned i = 0; i < ivars.size(); i++) { 14556 FieldDecl *Field = ivars[i]; 14557 if (Field->isInvalidDecl()) 14558 continue; 14559 14560 CXXCtorInitializer *Member; 14561 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14562 InitializationKind InitKind = 14563 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14564 14565 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14566 ExprResult MemberInit = 14567 InitSeq.Perform(*this, InitEntity, InitKind, None); 14568 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14569 // Note, MemberInit could actually come back empty if no initialization 14570 // is required (e.g., because it would call a trivial default constructor) 14571 if (!MemberInit.get() || MemberInit.isInvalid()) 14572 continue; 14573 14574 Member = 14575 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14576 SourceLocation(), 14577 MemberInit.getAs<Expr>(), 14578 SourceLocation()); 14579 AllToInit.push_back(Member); 14580 14581 // Be sure that the destructor is accessible and is marked as referenced. 14582 if (const RecordType *RecordTy = 14583 Context.getBaseElementType(Field->getType()) 14584 ->getAs<RecordType>()) { 14585 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14586 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14587 MarkFunctionReferenced(Field->getLocation(), Destructor); 14588 CheckDestructorAccess(Field->getLocation(), Destructor, 14589 PDiag(diag::err_access_dtor_ivar) 14590 << Context.getBaseElementType(Field->getType())); 14591 } 14592 } 14593 } 14594 ObjCImplementation->setIvarInitializers(Context, 14595 AllToInit.data(), AllToInit.size()); 14596 } 14597 } 14598 14599 static 14600 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14601 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14602 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14603 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14604 Sema &S) { 14605 if (Ctor->isInvalidDecl()) 14606 return; 14607 14608 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14609 14610 // Target may not be determinable yet, for instance if this is a dependent 14611 // call in an uninstantiated template. 14612 if (Target) { 14613 const FunctionDecl *FNTarget = nullptr; 14614 (void)Target->hasBody(FNTarget); 14615 Target = const_cast<CXXConstructorDecl*>( 14616 cast_or_null<CXXConstructorDecl>(FNTarget)); 14617 } 14618 14619 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14620 // Avoid dereferencing a null pointer here. 14621 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14622 14623 if (!Current.insert(Canonical).second) 14624 return; 14625 14626 // We know that beyond here, we aren't chaining into a cycle. 14627 if (!Target || !Target->isDelegatingConstructor() || 14628 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14629 Valid.insert(Current.begin(), Current.end()); 14630 Current.clear(); 14631 // We've hit a cycle. 14632 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14633 Current.count(TCanonical)) { 14634 // If we haven't diagnosed this cycle yet, do so now. 14635 if (!Invalid.count(TCanonical)) { 14636 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14637 diag::warn_delegating_ctor_cycle) 14638 << Ctor; 14639 14640 // Don't add a note for a function delegating directly to itself. 14641 if (TCanonical != Canonical) 14642 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14643 14644 CXXConstructorDecl *C = Target; 14645 while (C->getCanonicalDecl() != Canonical) { 14646 const FunctionDecl *FNTarget = nullptr; 14647 (void)C->getTargetConstructor()->hasBody(FNTarget); 14648 assert(FNTarget && "Ctor cycle through bodiless function"); 14649 14650 C = const_cast<CXXConstructorDecl*>( 14651 cast<CXXConstructorDecl>(FNTarget)); 14652 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14653 } 14654 } 14655 14656 Invalid.insert(Current.begin(), Current.end()); 14657 Current.clear(); 14658 } else { 14659 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14660 } 14661 } 14662 14663 14664 void Sema::CheckDelegatingCtorCycles() { 14665 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14666 14667 for (DelegatingCtorDeclsType::iterator 14668 I = DelegatingCtorDecls.begin(ExternalSource), 14669 E = DelegatingCtorDecls.end(); 14670 I != E; ++I) 14671 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14672 14673 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14674 CE = Invalid.end(); 14675 CI != CE; ++CI) 14676 (*CI)->setInvalidDecl(); 14677 } 14678 14679 namespace { 14680 /// \brief AST visitor that finds references to the 'this' expression. 14681 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14682 Sema &S; 14683 14684 public: 14685 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14686 14687 bool VisitCXXThisExpr(CXXThisExpr *E) { 14688 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14689 << E->isImplicit(); 14690 return false; 14691 } 14692 }; 14693 } 14694 14695 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14696 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14697 if (!TSInfo) 14698 return false; 14699 14700 TypeLoc TL = TSInfo->getTypeLoc(); 14701 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14702 if (!ProtoTL) 14703 return false; 14704 14705 // C++11 [expr.prim.general]p3: 14706 // [The expression this] shall not appear before the optional 14707 // cv-qualifier-seq and it shall not appear within the declaration of a 14708 // static member function (although its type and value category are defined 14709 // within a static member function as they are within a non-static member 14710 // function). [ Note: this is because declaration matching does not occur 14711 // until the complete declarator is known. - end note ] 14712 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14713 FindCXXThisExpr Finder(*this); 14714 14715 // If the return type came after the cv-qualifier-seq, check it now. 14716 if (Proto->hasTrailingReturn() && 14717 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14718 return true; 14719 14720 // Check the exception specification. 14721 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14722 return true; 14723 14724 return checkThisInStaticMemberFunctionAttributes(Method); 14725 } 14726 14727 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14728 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14729 if (!TSInfo) 14730 return false; 14731 14732 TypeLoc TL = TSInfo->getTypeLoc(); 14733 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14734 if (!ProtoTL) 14735 return false; 14736 14737 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14738 FindCXXThisExpr Finder(*this); 14739 14740 switch (Proto->getExceptionSpecType()) { 14741 case EST_Unparsed: 14742 case EST_Uninstantiated: 14743 case EST_Unevaluated: 14744 case EST_BasicNoexcept: 14745 case EST_DynamicNone: 14746 case EST_MSAny: 14747 case EST_None: 14748 break; 14749 14750 case EST_ComputedNoexcept: 14751 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14752 return true; 14753 LLVM_FALLTHROUGH; 14754 14755 case EST_Dynamic: 14756 for (const auto &E : Proto->exceptions()) { 14757 if (!Finder.TraverseType(E)) 14758 return true; 14759 } 14760 break; 14761 } 14762 14763 return false; 14764 } 14765 14766 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14767 FindCXXThisExpr Finder(*this); 14768 14769 // Check attributes. 14770 for (const auto *A : Method->attrs()) { 14771 // FIXME: This should be emitted by tblgen. 14772 Expr *Arg = nullptr; 14773 ArrayRef<Expr *> Args; 14774 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14775 Arg = G->getArg(); 14776 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14777 Arg = G->getArg(); 14778 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14779 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14780 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14781 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14782 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14783 Arg = ETLF->getSuccessValue(); 14784 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14785 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14786 Arg = STLF->getSuccessValue(); 14787 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14788 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14789 Arg = LR->getArg(); 14790 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14791 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14792 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14793 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14794 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14795 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14796 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14797 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14798 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14799 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14800 14801 if (Arg && !Finder.TraverseStmt(Arg)) 14802 return true; 14803 14804 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14805 if (!Finder.TraverseStmt(Args[I])) 14806 return true; 14807 } 14808 } 14809 14810 return false; 14811 } 14812 14813 void Sema::checkExceptionSpecification( 14814 bool IsTopLevel, ExceptionSpecificationType EST, 14815 ArrayRef<ParsedType> DynamicExceptions, 14816 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 14817 SmallVectorImpl<QualType> &Exceptions, 14818 FunctionProtoType::ExceptionSpecInfo &ESI) { 14819 Exceptions.clear(); 14820 ESI.Type = EST; 14821 if (EST == EST_Dynamic) { 14822 Exceptions.reserve(DynamicExceptions.size()); 14823 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 14824 // FIXME: Preserve type source info. 14825 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 14826 14827 if (IsTopLevel) { 14828 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 14829 collectUnexpandedParameterPacks(ET, Unexpanded); 14830 if (!Unexpanded.empty()) { 14831 DiagnoseUnexpandedParameterPacks( 14832 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 14833 Unexpanded); 14834 continue; 14835 } 14836 } 14837 14838 // Check that the type is valid for an exception spec, and 14839 // drop it if not. 14840 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 14841 Exceptions.push_back(ET); 14842 } 14843 ESI.Exceptions = Exceptions; 14844 return; 14845 } 14846 14847 if (EST == EST_ComputedNoexcept) { 14848 // If an error occurred, there's no expression here. 14849 if (NoexceptExpr) { 14850 assert((NoexceptExpr->isTypeDependent() || 14851 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 14852 Context.BoolTy) && 14853 "Parser should have made sure that the expression is boolean"); 14854 if (IsTopLevel && NoexceptExpr && 14855 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 14856 ESI.Type = EST_BasicNoexcept; 14857 return; 14858 } 14859 14860 if (!NoexceptExpr->isValueDependent()) 14861 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 14862 diag::err_noexcept_needs_constant_expression, 14863 /*AllowFold*/ false).get(); 14864 ESI.NoexceptExpr = NoexceptExpr; 14865 } 14866 return; 14867 } 14868 } 14869 14870 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 14871 ExceptionSpecificationType EST, 14872 SourceRange SpecificationRange, 14873 ArrayRef<ParsedType> DynamicExceptions, 14874 ArrayRef<SourceRange> DynamicExceptionRanges, 14875 Expr *NoexceptExpr) { 14876 if (!MethodD) 14877 return; 14878 14879 // Dig out the method we're referring to. 14880 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 14881 MethodD = FunTmpl->getTemplatedDecl(); 14882 14883 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 14884 if (!Method) 14885 return; 14886 14887 // Check the exception specification. 14888 llvm::SmallVector<QualType, 4> Exceptions; 14889 FunctionProtoType::ExceptionSpecInfo ESI; 14890 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 14891 DynamicExceptionRanges, NoexceptExpr, Exceptions, 14892 ESI); 14893 14894 // Update the exception specification on the function type. 14895 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 14896 14897 if (Method->isStatic()) 14898 checkThisInStaticMemberFunctionExceptionSpec(Method); 14899 14900 if (Method->isVirtual()) { 14901 // Check overrides, which we previously had to delay. 14902 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 14903 OEnd = Method->end_overridden_methods(); 14904 O != OEnd; ++O) 14905 CheckOverridingFunctionExceptionSpec(Method, *O); 14906 } 14907 } 14908 14909 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 14910 /// 14911 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 14912 SourceLocation DeclStart, 14913 Declarator &D, Expr *BitWidth, 14914 InClassInitStyle InitStyle, 14915 AccessSpecifier AS, 14916 AttributeList *MSPropertyAttr) { 14917 IdentifierInfo *II = D.getIdentifier(); 14918 if (!II) { 14919 Diag(DeclStart, diag::err_anonymous_property); 14920 return nullptr; 14921 } 14922 SourceLocation Loc = D.getIdentifierLoc(); 14923 14924 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14925 QualType T = TInfo->getType(); 14926 if (getLangOpts().CPlusPlus) { 14927 CheckExtraCXXDefaultArguments(D); 14928 14929 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14930 UPPC_DataMemberType)) { 14931 D.setInvalidType(); 14932 T = Context.IntTy; 14933 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14934 } 14935 } 14936 14937 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14938 14939 if (D.getDeclSpec().isInlineSpecified()) 14940 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14941 << getLangOpts().CPlusPlus1z; 14942 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14943 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14944 diag::err_invalid_thread) 14945 << DeclSpec::getSpecifierName(TSCS); 14946 14947 // Check to see if this name was declared as a member previously 14948 NamedDecl *PrevDecl = nullptr; 14949 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14950 LookupName(Previous, S); 14951 switch (Previous.getResultKind()) { 14952 case LookupResult::Found: 14953 case LookupResult::FoundUnresolvedValue: 14954 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14955 break; 14956 14957 case LookupResult::FoundOverloaded: 14958 PrevDecl = Previous.getRepresentativeDecl(); 14959 break; 14960 14961 case LookupResult::NotFound: 14962 case LookupResult::NotFoundInCurrentInstantiation: 14963 case LookupResult::Ambiguous: 14964 break; 14965 } 14966 14967 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14968 // Maybe we will complain about the shadowed template parameter. 14969 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14970 // Just pretend that we didn't see the previous declaration. 14971 PrevDecl = nullptr; 14972 } 14973 14974 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14975 PrevDecl = nullptr; 14976 14977 SourceLocation TSSL = D.getLocStart(); 14978 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 14979 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 14980 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 14981 ProcessDeclAttributes(TUScope, NewPD, D); 14982 NewPD->setAccess(AS); 14983 14984 if (NewPD->isInvalidDecl()) 14985 Record->setInvalidDecl(); 14986 14987 if (D.getDeclSpec().isModulePrivateSpecified()) 14988 NewPD->setModulePrivate(); 14989 14990 if (NewPD->isInvalidDecl() && PrevDecl) { 14991 // Don't introduce NewFD into scope; there's already something 14992 // with the same name in the same scope. 14993 } else if (II) { 14994 PushOnScopeChains(NewPD, S); 14995 } else 14996 Record->addDecl(NewPD); 14997 14998 return NewPD; 14999 } 15000