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 // sufficent, 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. 551 // It's important to use getInit() here; getDefaultArg() 552 // strips off any top-level ExprWithCleanups. 553 NewParam->setHasInheritedDefaultArg(); 554 if (OldParam->hasUnparsedDefaultArg()) 555 NewParam->setUnparsedDefaultArg(); 556 else if (OldParam->hasUninstantiatedDefaultArg()) 557 NewParam->setUninstantiatedDefaultArg( 558 OldParam->getUninstantiatedDefaultArg()); 559 else 560 NewParam->setDefaultArg(OldParam->getInit()); 561 } else if (NewParamHasDfl) { 562 if (New->getDescribedFunctionTemplate()) { 563 // Paragraph 4, quoted above, only applies to non-template functions. 564 Diag(NewParam->getLocation(), 565 diag::err_param_default_argument_template_redecl) 566 << NewParam->getDefaultArgRange(); 567 Diag(PrevForDefaultArgs->getLocation(), 568 diag::note_template_prev_declaration) 569 << false; 570 } else if (New->getTemplateSpecializationKind() 571 != TSK_ImplicitInstantiation && 572 New->getTemplateSpecializationKind() != TSK_Undeclared) { 573 // C++ [temp.expr.spec]p21: 574 // Default function arguments shall not be specified in a declaration 575 // or a definition for one of the following explicit specializations: 576 // - the explicit specialization of a function template; 577 // - the explicit specialization of a member function template; 578 // - the explicit specialization of a member function of a class 579 // template where the class template specialization to which the 580 // member function specialization belongs is implicitly 581 // instantiated. 582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 584 << New->getDeclName() 585 << NewParam->getDefaultArgRange(); 586 } else if (New->getDeclContext()->isDependentContext()) { 587 // C++ [dcl.fct.default]p6 (DR217): 588 // Default arguments for a member function of a class template shall 589 // be specified on the initial declaration of the member function 590 // within the class template. 591 // 592 // Reading the tea leaves a bit in DR217 and its reference to DR205 593 // leads me to the conclusion that one cannot add default function 594 // arguments for an out-of-line definition of a member function of a 595 // dependent type. 596 int WhichKind = 2; 597 if (CXXRecordDecl *Record 598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 599 if (Record->getDescribedClassTemplate()) 600 WhichKind = 0; 601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 602 WhichKind = 1; 603 else 604 WhichKind = 2; 605 } 606 607 Diag(NewParam->getLocation(), 608 diag::err_param_default_argument_member_template_redecl) 609 << WhichKind 610 << NewParam->getDefaultArgRange(); 611 } 612 } 613 } 614 615 // DR1344: If a default argument is added outside a class definition and that 616 // default argument makes the function a special member function, the program 617 // is ill-formed. This can only happen for constructors. 618 if (isa<CXXConstructorDecl>(New) && 619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 622 if (NewSM != OldSM) { 623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 624 assert(NewParam->hasDefaultArg()); 625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 626 << NewParam->getDefaultArgRange() << NewSM; 627 Diag(Old->getLocation(), diag::note_previous_declaration); 628 } 629 } 630 631 const FunctionDecl *Def; 632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 633 // template has a constexpr specifier then all its declarations shall 634 // contain the constexpr specifier. 635 if (New->isConstexpr() != Old->isConstexpr()) { 636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 637 << New << New->isConstexpr(); 638 Diag(Old->getLocation(), diag::note_previous_declaration); 639 Invalid = true; 640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 641 Old->isDefined(Def)) { 642 // C++11 [dcl.fcn.spec]p4: 643 // If the definition of a function appears in a translation unit before its 644 // first declaration as inline, the program is ill-formed. 645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 646 Diag(Def->getLocation(), diag::note_previous_definition); 647 Invalid = true; 648 } 649 650 // FIXME: It's not clear what should happen if multiple declarations of a 651 // deduction guide have different explicitness. For now at least we simply 652 // reject any case where the explicitness changes. 653 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 654 if (NewGuide && NewGuide->isExplicitSpecified() != 655 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 656 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 657 << NewGuide->isExplicitSpecified(); 658 Diag(Old->getLocation(), diag::note_previous_declaration); 659 } 660 661 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 662 // argument expression, that declaration shall be a definition and shall be 663 // the only declaration of the function or function template in the 664 // translation unit. 665 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 666 functionDeclHasDefaultArgument(Old)) { 667 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 668 Diag(Old->getLocation(), diag::note_previous_declaration); 669 Invalid = true; 670 } 671 672 return Invalid; 673 } 674 675 NamedDecl * 676 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 677 MultiTemplateParamsArg TemplateParamLists) { 678 assert(D.isDecompositionDeclarator()); 679 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 680 681 // The syntax only allows a decomposition declarator as a simple-declaration 682 // or a for-range-declaration, but we parse it in more cases than that. 683 if (!D.mayHaveDecompositionDeclarator()) { 684 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 685 << Decomp.getSourceRange(); 686 return nullptr; 687 } 688 689 if (!TemplateParamLists.empty()) { 690 // FIXME: There's no rule against this, but there are also no rules that 691 // would actually make it usable, so we reject it for now. 692 Diag(TemplateParamLists.front()->getTemplateLoc(), 693 diag::err_decomp_decl_template); 694 return nullptr; 695 } 696 697 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z 698 ? diag::warn_cxx14_compat_decomp_decl 699 : diag::ext_decomp_decl) 700 << Decomp.getSourceRange(); 701 702 // The semantic context is always just the current context. 703 DeclContext *const DC = CurContext; 704 705 // C++1z [dcl.dcl]/8: 706 // The decl-specifier-seq shall contain only the type-specifier auto 707 // and cv-qualifiers. 708 auto &DS = D.getDeclSpec(); 709 { 710 SmallVector<StringRef, 8> BadSpecifiers; 711 SmallVector<SourceLocation, 8> BadSpecifierLocs; 712 if (auto SCS = DS.getStorageClassSpec()) { 713 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 714 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 715 } 716 if (auto TSCS = DS.getThreadStorageClassSpec()) { 717 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 718 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 719 } 720 if (DS.isConstexprSpecified()) { 721 BadSpecifiers.push_back("constexpr"); 722 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 723 } 724 if (DS.isInlineSpecified()) { 725 BadSpecifiers.push_back("inline"); 726 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 727 } 728 if (!BadSpecifiers.empty()) { 729 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 730 Err << (int)BadSpecifiers.size() 731 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 732 // Don't add FixItHints to remove the specifiers; we do still respect 733 // them when building the underlying variable. 734 for (auto Loc : BadSpecifierLocs) 735 Err << SourceRange(Loc, Loc); 736 } 737 // We can't recover from it being declared as a typedef. 738 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 739 return nullptr; 740 } 741 742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 743 QualType R = TInfo->getType(); 744 745 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 746 UPPC_DeclarationType)) 747 D.setInvalidType(); 748 749 // The syntax only allows a single ref-qualifier prior to the decomposition 750 // declarator. No other declarator chunks are permitted. Also check the type 751 // specifier here. 752 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 753 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 754 (D.getNumTypeObjects() == 1 && 755 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 756 Diag(Decomp.getLSquareLoc(), 757 (D.hasGroupingParens() || 758 (D.getNumTypeObjects() && 759 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 760 ? diag::err_decomp_decl_parens 761 : diag::err_decomp_decl_type) 762 << R; 763 764 // In most cases, there's no actual problem with an explicitly-specified 765 // type, but a function type won't work here, and ActOnVariableDeclarator 766 // shouldn't be called for such a type. 767 if (R->isFunctionType()) 768 D.setInvalidType(); 769 } 770 771 // Build the BindingDecls. 772 SmallVector<BindingDecl*, 8> Bindings; 773 774 // Build the BindingDecls. 775 for (auto &B : D.getDecompositionDeclarator().bindings()) { 776 // Check for name conflicts. 777 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 778 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 779 ForRedeclaration); 780 LookupName(Previous, S, 781 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 782 783 // It's not permitted to shadow a template parameter name. 784 if (Previous.isSingleResult() && 785 Previous.getFoundDecl()->isTemplateParameter()) { 786 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 787 Previous.getFoundDecl()); 788 Previous.clear(); 789 } 790 791 bool ConsiderLinkage = DC->isFunctionOrMethod() && 792 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 793 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 794 /*AllowInlineNamespace*/false); 795 if (!Previous.empty()) { 796 auto *Old = Previous.getRepresentativeDecl(); 797 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 798 Diag(Old->getLocation(), diag::note_previous_definition); 799 } 800 801 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 802 PushOnScopeChains(BD, S, true); 803 Bindings.push_back(BD); 804 ParsingInitForAutoVars.insert(BD); 805 } 806 807 // There are no prior lookup results for the variable itself, because it 808 // is unnamed. 809 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 810 Decomp.getLSquareLoc()); 811 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 812 813 // Build the variable that holds the non-decomposed object. 814 bool AddToScope = true; 815 NamedDecl *New = 816 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 817 MultiTemplateParamsArg(), AddToScope, Bindings); 818 CurContext->addHiddenDecl(New); 819 820 if (isInOpenMPDeclareTargetContext()) 821 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 822 823 return New; 824 } 825 826 static bool checkSimpleDecomposition( 827 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 828 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 829 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 830 if ((int64_t)Bindings.size() != NumElems) { 831 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 832 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 833 << (NumElems < Bindings.size()); 834 return true; 835 } 836 837 unsigned I = 0; 838 for (auto *B : Bindings) { 839 SourceLocation Loc = B->getLocation(); 840 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 841 if (E.isInvalid()) 842 return true; 843 E = GetInit(Loc, E.get(), I++); 844 if (E.isInvalid()) 845 return true; 846 B->setBinding(ElemType, E.get()); 847 } 848 849 return false; 850 } 851 852 static bool checkArrayLikeDecomposition(Sema &S, 853 ArrayRef<BindingDecl *> Bindings, 854 ValueDecl *Src, QualType DecompType, 855 const llvm::APSInt &NumElems, 856 QualType ElemType) { 857 return checkSimpleDecomposition( 858 S, Bindings, Src, DecompType, NumElems, ElemType, 859 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 860 ExprResult E = S.ActOnIntegerConstant(Loc, I); 861 if (E.isInvalid()) 862 return ExprError(); 863 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 864 }); 865 } 866 867 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 868 ValueDecl *Src, QualType DecompType, 869 const ConstantArrayType *CAT) { 870 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 871 llvm::APSInt(CAT->getSize()), 872 CAT->getElementType()); 873 } 874 875 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 876 ValueDecl *Src, QualType DecompType, 877 const VectorType *VT) { 878 return checkArrayLikeDecomposition( 879 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 880 S.Context.getQualifiedType(VT->getElementType(), 881 DecompType.getQualifiers())); 882 } 883 884 static bool checkComplexDecomposition(Sema &S, 885 ArrayRef<BindingDecl *> Bindings, 886 ValueDecl *Src, QualType DecompType, 887 const ComplexType *CT) { 888 return checkSimpleDecomposition( 889 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 890 S.Context.getQualifiedType(CT->getElementType(), 891 DecompType.getQualifiers()), 892 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 893 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 894 }); 895 } 896 897 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 898 TemplateArgumentListInfo &Args) { 899 SmallString<128> SS; 900 llvm::raw_svector_ostream OS(SS); 901 bool First = true; 902 for (auto &Arg : Args.arguments()) { 903 if (!First) 904 OS << ", "; 905 Arg.getArgument().print(PrintingPolicy, OS); 906 First = false; 907 } 908 return OS.str(); 909 } 910 911 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 912 SourceLocation Loc, StringRef Trait, 913 TemplateArgumentListInfo &Args, 914 unsigned DiagID) { 915 auto DiagnoseMissing = [&] { 916 if (DiagID) 917 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 918 Args); 919 return true; 920 }; 921 922 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 923 NamespaceDecl *Std = S.getStdNamespace(); 924 if (!Std) 925 return DiagnoseMissing(); 926 927 // Look up the trait itself, within namespace std. We can diagnose various 928 // problems with this lookup even if we've been asked to not diagnose a 929 // missing specialization, because this can only fail if the user has been 930 // declaring their own names in namespace std or we don't support the 931 // standard library implementation in use. 932 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 933 Loc, Sema::LookupOrdinaryName); 934 if (!S.LookupQualifiedName(Result, Std)) 935 return DiagnoseMissing(); 936 if (Result.isAmbiguous()) 937 return true; 938 939 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 940 if (!TraitTD) { 941 Result.suppressDiagnostics(); 942 NamedDecl *Found = *Result.begin(); 943 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 944 S.Diag(Found->getLocation(), diag::note_declared_at); 945 return true; 946 } 947 948 // Build the template-id. 949 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 950 if (TraitTy.isNull()) 951 return true; 952 if (!S.isCompleteType(Loc, TraitTy)) { 953 if (DiagID) 954 S.RequireCompleteType( 955 Loc, TraitTy, DiagID, 956 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 957 return true; 958 } 959 960 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 961 assert(RD && "specialization of class template is not a class?"); 962 963 // Look up the member of the trait type. 964 S.LookupQualifiedName(TraitMemberLookup, RD); 965 return TraitMemberLookup.isAmbiguous(); 966 } 967 968 static TemplateArgumentLoc 969 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 970 uint64_t I) { 971 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 972 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 973 } 974 975 static TemplateArgumentLoc 976 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 977 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 978 } 979 980 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 981 982 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 983 llvm::APSInt &Size) { 984 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated); 985 986 DeclarationName Value = S.PP.getIdentifierInfo("value"); 987 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 988 989 // Form template argument list for tuple_size<T>. 990 TemplateArgumentListInfo Args(Loc, Loc); 991 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 992 993 // If there's no tuple_size specialization, it's not tuple-like. 994 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 995 return IsTupleLike::NotTupleLike; 996 997 // If we get this far, we've committed to the tuple interpretation, but 998 // we can still fail if there actually isn't a usable ::value. 999 1000 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1001 LookupResult &R; 1002 TemplateArgumentListInfo &Args; 1003 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1004 : R(R), Args(Args) {} 1005 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1006 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1007 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1008 } 1009 } Diagnoser(R, Args); 1010 1011 if (R.empty()) { 1012 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1013 return IsTupleLike::Error; 1014 } 1015 1016 ExprResult E = 1017 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1018 if (E.isInvalid()) 1019 return IsTupleLike::Error; 1020 1021 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1022 if (E.isInvalid()) 1023 return IsTupleLike::Error; 1024 1025 return IsTupleLike::TupleLike; 1026 } 1027 1028 /// \return std::tuple_element<I, T>::type. 1029 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1030 unsigned I, QualType T) { 1031 // Form template argument list for tuple_element<I, T>. 1032 TemplateArgumentListInfo Args(Loc, Loc); 1033 Args.addArgument( 1034 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1035 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1036 1037 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1038 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1039 if (lookupStdTypeTraitMember( 1040 S, R, Loc, "tuple_element", Args, 1041 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1042 return QualType(); 1043 1044 auto *TD = R.getAsSingle<TypeDecl>(); 1045 if (!TD) { 1046 R.suppressDiagnostics(); 1047 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1048 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1049 if (!R.empty()) 1050 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1051 return QualType(); 1052 } 1053 1054 return S.Context.getTypeDeclType(TD); 1055 } 1056 1057 namespace { 1058 struct BindingDiagnosticTrap { 1059 Sema &S; 1060 DiagnosticErrorTrap Trap; 1061 BindingDecl *BD; 1062 1063 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1064 : S(S), Trap(S.Diags), BD(BD) {} 1065 ~BindingDiagnosticTrap() { 1066 if (Trap.hasErrorOccurred()) 1067 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1068 } 1069 }; 1070 } 1071 1072 static bool checkTupleLikeDecomposition(Sema &S, 1073 ArrayRef<BindingDecl *> Bindings, 1074 VarDecl *Src, QualType DecompType, 1075 const llvm::APSInt &TupleSize) { 1076 if ((int64_t)Bindings.size() != TupleSize) { 1077 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1078 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1079 << (TupleSize < Bindings.size()); 1080 return true; 1081 } 1082 1083 if (Bindings.empty()) 1084 return false; 1085 1086 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1087 1088 // [dcl.decomp]p3: 1089 // The unqualified-id get is looked up in the scope of E by class member 1090 // access lookup 1091 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1092 bool UseMemberGet = false; 1093 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1094 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1095 S.LookupQualifiedName(MemberGet, RD); 1096 if (MemberGet.isAmbiguous()) 1097 return true; 1098 UseMemberGet = !MemberGet.empty(); 1099 S.FilterAcceptableTemplateNames(MemberGet); 1100 } 1101 1102 unsigned I = 0; 1103 for (auto *B : Bindings) { 1104 BindingDiagnosticTrap Trap(S, B); 1105 SourceLocation Loc = B->getLocation(); 1106 1107 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1108 if (E.isInvalid()) 1109 return true; 1110 1111 // e is an lvalue if the type of the entity is an lvalue reference and 1112 // an xvalue otherwise 1113 if (!Src->getType()->isLValueReferenceType()) 1114 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1115 E.get(), nullptr, VK_XValue); 1116 1117 TemplateArgumentListInfo Args(Loc, Loc); 1118 Args.addArgument( 1119 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1120 1121 if (UseMemberGet) { 1122 // if [lookup of member get] finds at least one declaration, the 1123 // initializer is e.get<i-1>(). 1124 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1125 CXXScopeSpec(), SourceLocation(), nullptr, 1126 MemberGet, &Args, nullptr); 1127 if (E.isInvalid()) 1128 return true; 1129 1130 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1131 } else { 1132 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1133 // in the associated namespaces. 1134 Expr *Get = UnresolvedLookupExpr::Create( 1135 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1136 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1137 UnresolvedSetIterator(), UnresolvedSetIterator()); 1138 1139 Expr *Arg = E.get(); 1140 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1141 } 1142 if (E.isInvalid()) 1143 return true; 1144 Expr *Init = E.get(); 1145 1146 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1147 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1148 if (T.isNull()) 1149 return true; 1150 1151 // each vi is a variable of type "reference to T" initialized with the 1152 // initializer, where the reference is an lvalue reference if the 1153 // initializer is an lvalue and an rvalue reference otherwise 1154 QualType RefType = 1155 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1156 if (RefType.isNull()) 1157 return true; 1158 auto *RefVD = VarDecl::Create( 1159 S.Context, Src->getDeclContext(), Loc, Loc, 1160 B->getDeclName().getAsIdentifierInfo(), RefType, 1161 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1162 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1163 RefVD->setTSCSpec(Src->getTSCSpec()); 1164 RefVD->setImplicit(); 1165 if (Src->isInlineSpecified()) 1166 RefVD->setInlineSpecified(); 1167 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1168 1169 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1170 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1171 InitializationSequence Seq(S, Entity, Kind, Init); 1172 E = Seq.Perform(S, Entity, Kind, Init); 1173 if (E.isInvalid()) 1174 return true; 1175 E = S.ActOnFinishFullExpr(E.get(), Loc); 1176 if (E.isInvalid()) 1177 return true; 1178 RefVD->setInit(E.get()); 1179 RefVD->checkInitIsICE(); 1180 1181 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1182 DeclarationNameInfo(B->getDeclName(), Loc), 1183 RefVD); 1184 if (E.isInvalid()) 1185 return true; 1186 1187 B->setBinding(T, E.get()); 1188 I++; 1189 } 1190 1191 return false; 1192 } 1193 1194 /// Find the base class to decompose in a built-in decomposition of a class type. 1195 /// This base class search is, unfortunately, not quite like any other that we 1196 /// perform anywhere else in C++. 1197 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1198 SourceLocation Loc, 1199 const CXXRecordDecl *RD, 1200 CXXCastPath &BasePath) { 1201 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1202 CXXBasePath &Path) { 1203 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1204 }; 1205 1206 const CXXRecordDecl *ClassWithFields = nullptr; 1207 if (RD->hasDirectFields()) 1208 // [dcl.decomp]p4: 1209 // Otherwise, all of E's non-static data members shall be public direct 1210 // members of E ... 1211 ClassWithFields = RD; 1212 else { 1213 // ... or of ... 1214 CXXBasePaths Paths; 1215 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1216 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1217 // If no classes have fields, just decompose RD itself. (This will work 1218 // if and only if zero bindings were provided.) 1219 return RD; 1220 } 1221 1222 CXXBasePath *BestPath = nullptr; 1223 for (auto &P : Paths) { 1224 if (!BestPath) 1225 BestPath = &P; 1226 else if (!S.Context.hasSameType(P.back().Base->getType(), 1227 BestPath->back().Base->getType())) { 1228 // ... the same ... 1229 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1230 << false << RD << BestPath->back().Base->getType() 1231 << P.back().Base->getType(); 1232 return nullptr; 1233 } else if (P.Access < BestPath->Access) { 1234 BestPath = &P; 1235 } 1236 } 1237 1238 // ... unambiguous ... 1239 QualType BaseType = BestPath->back().Base->getType(); 1240 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1241 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1242 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1243 return nullptr; 1244 } 1245 1246 // ... public base class of E. 1247 if (BestPath->Access != AS_public) { 1248 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1249 << RD << BaseType; 1250 for (auto &BS : *BestPath) { 1251 if (BS.Base->getAccessSpecifier() != AS_public) { 1252 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1253 << (BS.Base->getAccessSpecifier() == AS_protected) 1254 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1255 break; 1256 } 1257 } 1258 return nullptr; 1259 } 1260 1261 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1262 S.BuildBasePathArray(Paths, BasePath); 1263 } 1264 1265 // The above search did not check whether the selected class itself has base 1266 // classes with fields, so check that now. 1267 CXXBasePaths Paths; 1268 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1269 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1270 << (ClassWithFields == RD) << RD << ClassWithFields 1271 << Paths.front().back().Base->getType(); 1272 return nullptr; 1273 } 1274 1275 return ClassWithFields; 1276 } 1277 1278 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1279 ValueDecl *Src, QualType DecompType, 1280 const CXXRecordDecl *RD) { 1281 CXXCastPath BasePath; 1282 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1283 if (!RD) 1284 return true; 1285 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1286 DecompType.getQualifiers()); 1287 1288 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1289 unsigned NumFields = 1290 std::count_if(RD->field_begin(), RD->field_end(), 1291 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1292 assert(Bindings.size() != NumFields); 1293 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1294 << DecompType << (unsigned)Bindings.size() << NumFields 1295 << (NumFields < Bindings.size()); 1296 return true; 1297 }; 1298 1299 // all of E's non-static data members shall be public [...] members, 1300 // E shall not have an anonymous union member, ... 1301 unsigned I = 0; 1302 for (auto *FD : RD->fields()) { 1303 if (FD->isUnnamedBitfield()) 1304 continue; 1305 1306 if (FD->isAnonymousStructOrUnion()) { 1307 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1308 << DecompType << FD->getType()->isUnionType(); 1309 S.Diag(FD->getLocation(), diag::note_declared_at); 1310 return true; 1311 } 1312 1313 // We have a real field to bind. 1314 if (I >= Bindings.size()) 1315 return DiagnoseBadNumberOfBindings(); 1316 auto *B = Bindings[I++]; 1317 1318 SourceLocation Loc = B->getLocation(); 1319 if (FD->getAccess() != AS_public) { 1320 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1321 1322 // Determine whether the access specifier was explicit. 1323 bool Implicit = true; 1324 for (const auto *D : RD->decls()) { 1325 if (declaresSameEntity(D, FD)) 1326 break; 1327 if (isa<AccessSpecDecl>(D)) { 1328 Implicit = false; 1329 break; 1330 } 1331 } 1332 1333 S.Diag(FD->getLocation(), diag::note_access_natural) 1334 << (FD->getAccess() == AS_protected) << Implicit; 1335 return true; 1336 } 1337 1338 // Initialize the binding to Src.FD. 1339 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1340 if (E.isInvalid()) 1341 return true; 1342 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1343 VK_LValue, &BasePath); 1344 if (E.isInvalid()) 1345 return true; 1346 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1347 CXXScopeSpec(), FD, 1348 DeclAccessPair::make(FD, FD->getAccess()), 1349 DeclarationNameInfo(FD->getDeclName(), Loc)); 1350 if (E.isInvalid()) 1351 return true; 1352 1353 // If the type of the member is T, the referenced type is cv T, where cv is 1354 // the cv-qualification of the decomposition expression. 1355 // 1356 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1357 // 'const' to the type of the field. 1358 Qualifiers Q = DecompType.getQualifiers(); 1359 if (FD->isMutable()) 1360 Q.removeConst(); 1361 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1362 } 1363 1364 if (I != Bindings.size()) 1365 return DiagnoseBadNumberOfBindings(); 1366 1367 return false; 1368 } 1369 1370 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1371 QualType DecompType = DD->getType(); 1372 1373 // If the type of the decomposition is dependent, then so is the type of 1374 // each binding. 1375 if (DecompType->isDependentType()) { 1376 for (auto *B : DD->bindings()) 1377 B->setType(Context.DependentTy); 1378 return; 1379 } 1380 1381 DecompType = DecompType.getNonReferenceType(); 1382 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1383 1384 // C++1z [dcl.decomp]/2: 1385 // If E is an array type [...] 1386 // As an extension, we also support decomposition of built-in complex and 1387 // vector types. 1388 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1389 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1390 DD->setInvalidDecl(); 1391 return; 1392 } 1393 if (auto *VT = DecompType->getAs<VectorType>()) { 1394 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1395 DD->setInvalidDecl(); 1396 return; 1397 } 1398 if (auto *CT = DecompType->getAs<ComplexType>()) { 1399 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1400 DD->setInvalidDecl(); 1401 return; 1402 } 1403 1404 // C++1z [dcl.decomp]/3: 1405 // if the expression std::tuple_size<E>::value is a well-formed integral 1406 // constant expression, [...] 1407 llvm::APSInt TupleSize(32); 1408 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1409 case IsTupleLike::Error: 1410 DD->setInvalidDecl(); 1411 return; 1412 1413 case IsTupleLike::TupleLike: 1414 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1415 DD->setInvalidDecl(); 1416 return; 1417 1418 case IsTupleLike::NotTupleLike: 1419 break; 1420 } 1421 1422 // C++1z [dcl.dcl]/8: 1423 // [E shall be of array or non-union class type] 1424 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1425 if (!RD || RD->isUnion()) { 1426 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1427 << DD << !RD << DecompType; 1428 DD->setInvalidDecl(); 1429 return; 1430 } 1431 1432 // C++1z [dcl.decomp]/4: 1433 // all of E's non-static data members shall be [...] direct members of 1434 // E or of the same unambiguous public base class of E, ... 1435 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1436 DD->setInvalidDecl(); 1437 } 1438 1439 /// \brief Merge the exception specifications of two variable declarations. 1440 /// 1441 /// This is called when there's a redeclaration of a VarDecl. The function 1442 /// checks if the redeclaration might have an exception specification and 1443 /// validates compatibility and merges the specs if necessary. 1444 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1445 // Shortcut if exceptions are disabled. 1446 if (!getLangOpts().CXXExceptions) 1447 return; 1448 1449 assert(Context.hasSameType(New->getType(), Old->getType()) && 1450 "Should only be called if types are otherwise the same."); 1451 1452 QualType NewType = New->getType(); 1453 QualType OldType = Old->getType(); 1454 1455 // We're only interested in pointers and references to functions, as well 1456 // as pointers to member functions. 1457 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1458 NewType = R->getPointeeType(); 1459 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1460 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1461 NewType = P->getPointeeType(); 1462 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1463 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1464 NewType = M->getPointeeType(); 1465 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1466 } 1467 1468 if (!NewType->isFunctionProtoType()) 1469 return; 1470 1471 // There's lots of special cases for functions. For function pointers, system 1472 // libraries are hopefully not as broken so that we don't need these 1473 // workarounds. 1474 if (CheckEquivalentExceptionSpec( 1475 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1476 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1477 New->setInvalidDecl(); 1478 } 1479 } 1480 1481 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1482 /// function declaration are well-formed according to C++ 1483 /// [dcl.fct.default]. 1484 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1485 unsigned NumParams = FD->getNumParams(); 1486 unsigned p; 1487 1488 // Find first parameter with a default argument 1489 for (p = 0; p < NumParams; ++p) { 1490 ParmVarDecl *Param = FD->getParamDecl(p); 1491 if (Param->hasDefaultArg()) 1492 break; 1493 } 1494 1495 // C++11 [dcl.fct.default]p4: 1496 // In a given function declaration, each parameter subsequent to a parameter 1497 // with a default argument shall have a default argument supplied in this or 1498 // a previous declaration or shall be a function parameter pack. A default 1499 // argument shall not be redefined by a later declaration (not even to the 1500 // same value). 1501 unsigned LastMissingDefaultArg = 0; 1502 for (; p < NumParams; ++p) { 1503 ParmVarDecl *Param = FD->getParamDecl(p); 1504 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1505 if (Param->isInvalidDecl()) 1506 /* We already complained about this parameter. */; 1507 else if (Param->getIdentifier()) 1508 Diag(Param->getLocation(), 1509 diag::err_param_default_argument_missing_name) 1510 << Param->getIdentifier(); 1511 else 1512 Diag(Param->getLocation(), 1513 diag::err_param_default_argument_missing); 1514 1515 LastMissingDefaultArg = p; 1516 } 1517 } 1518 1519 if (LastMissingDefaultArg > 0) { 1520 // Some default arguments were missing. Clear out all of the 1521 // default arguments up to (and including) the last missing 1522 // default argument, so that we leave the function parameters 1523 // in a semantically valid state. 1524 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1525 ParmVarDecl *Param = FD->getParamDecl(p); 1526 if (Param->hasDefaultArg()) { 1527 Param->setDefaultArg(nullptr); 1528 } 1529 } 1530 } 1531 } 1532 1533 // CheckConstexprParameterTypes - Check whether a function's parameter types 1534 // are all literal types. If so, return true. If not, produce a suitable 1535 // diagnostic and return false. 1536 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1537 const FunctionDecl *FD) { 1538 unsigned ArgIndex = 0; 1539 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1540 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1541 e = FT->param_type_end(); 1542 i != e; ++i, ++ArgIndex) { 1543 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1544 SourceLocation ParamLoc = PD->getLocation(); 1545 if (!(*i)->isDependentType() && 1546 SemaRef.RequireLiteralType(ParamLoc, *i, 1547 diag::err_constexpr_non_literal_param, 1548 ArgIndex+1, PD->getSourceRange(), 1549 isa<CXXConstructorDecl>(FD))) 1550 return false; 1551 } 1552 return true; 1553 } 1554 1555 /// \brief Get diagnostic %select index for tag kind for 1556 /// record diagnostic message. 1557 /// WARNING: Indexes apply to particular diagnostics only! 1558 /// 1559 /// \returns diagnostic %select index. 1560 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1561 switch (Tag) { 1562 case TTK_Struct: return 0; 1563 case TTK_Interface: return 1; 1564 case TTK_Class: return 2; 1565 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1566 } 1567 } 1568 1569 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1570 // the requirements of a constexpr function definition or a constexpr 1571 // constructor definition. If so, return true. If not, produce appropriate 1572 // diagnostics and return false. 1573 // 1574 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1575 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1576 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1577 if (MD && MD->isInstance()) { 1578 // C++11 [dcl.constexpr]p4: 1579 // The definition of a constexpr constructor shall satisfy the following 1580 // constraints: 1581 // - the class shall not have any virtual base classes; 1582 const CXXRecordDecl *RD = MD->getParent(); 1583 if (RD->getNumVBases()) { 1584 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1585 << isa<CXXConstructorDecl>(NewFD) 1586 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1587 for (const auto &I : RD->vbases()) 1588 Diag(I.getLocStart(), 1589 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1590 return false; 1591 } 1592 } 1593 1594 if (!isa<CXXConstructorDecl>(NewFD)) { 1595 // C++11 [dcl.constexpr]p3: 1596 // The definition of a constexpr function shall satisfy the following 1597 // constraints: 1598 // - it shall not be virtual; 1599 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1600 if (Method && Method->isVirtual()) { 1601 Method = Method->getCanonicalDecl(); 1602 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1603 1604 // If it's not obvious why this function is virtual, find an overridden 1605 // function which uses the 'virtual' keyword. 1606 const CXXMethodDecl *WrittenVirtual = Method; 1607 while (!WrittenVirtual->isVirtualAsWritten()) 1608 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1609 if (WrittenVirtual != Method) 1610 Diag(WrittenVirtual->getLocation(), 1611 diag::note_overridden_virtual_function); 1612 return false; 1613 } 1614 1615 // - its return type shall be a literal type; 1616 QualType RT = NewFD->getReturnType(); 1617 if (!RT->isDependentType() && 1618 RequireLiteralType(NewFD->getLocation(), RT, 1619 diag::err_constexpr_non_literal_return)) 1620 return false; 1621 } 1622 1623 // - each of its parameter types shall be a literal type; 1624 if (!CheckConstexprParameterTypes(*this, NewFD)) 1625 return false; 1626 1627 return true; 1628 } 1629 1630 /// Check the given declaration statement is legal within a constexpr function 1631 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1632 /// 1633 /// \return true if the body is OK (maybe only as an extension), false if we 1634 /// have diagnosed a problem. 1635 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1636 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1637 // C++11 [dcl.constexpr]p3 and p4: 1638 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1639 // contain only 1640 for (const auto *DclIt : DS->decls()) { 1641 switch (DclIt->getKind()) { 1642 case Decl::StaticAssert: 1643 case Decl::Using: 1644 case Decl::UsingShadow: 1645 case Decl::UsingDirective: 1646 case Decl::UnresolvedUsingTypename: 1647 case Decl::UnresolvedUsingValue: 1648 // - static_assert-declarations 1649 // - using-declarations, 1650 // - using-directives, 1651 continue; 1652 1653 case Decl::Typedef: 1654 case Decl::TypeAlias: { 1655 // - typedef declarations and alias-declarations that do not define 1656 // classes or enumerations, 1657 const auto *TN = cast<TypedefNameDecl>(DclIt); 1658 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1659 // Don't allow variably-modified types in constexpr functions. 1660 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1661 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1662 << TL.getSourceRange() << TL.getType() 1663 << isa<CXXConstructorDecl>(Dcl); 1664 return false; 1665 } 1666 continue; 1667 } 1668 1669 case Decl::Enum: 1670 case Decl::CXXRecord: 1671 // C++1y allows types to be defined, not just declared. 1672 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1673 SemaRef.Diag(DS->getLocStart(), 1674 SemaRef.getLangOpts().CPlusPlus14 1675 ? diag::warn_cxx11_compat_constexpr_type_definition 1676 : diag::ext_constexpr_type_definition) 1677 << isa<CXXConstructorDecl>(Dcl); 1678 continue; 1679 1680 case Decl::EnumConstant: 1681 case Decl::IndirectField: 1682 case Decl::ParmVar: 1683 // These can only appear with other declarations which are banned in 1684 // C++11 and permitted in C++1y, so ignore them. 1685 continue; 1686 1687 case Decl::Var: 1688 case Decl::Decomposition: { 1689 // C++1y [dcl.constexpr]p3 allows anything except: 1690 // a definition of a variable of non-literal type or of static or 1691 // thread storage duration or for which no initialization is performed. 1692 const auto *VD = cast<VarDecl>(DclIt); 1693 if (VD->isThisDeclarationADefinition()) { 1694 if (VD->isStaticLocal()) { 1695 SemaRef.Diag(VD->getLocation(), 1696 diag::err_constexpr_local_var_static) 1697 << isa<CXXConstructorDecl>(Dcl) 1698 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1699 return false; 1700 } 1701 if (!VD->getType()->isDependentType() && 1702 SemaRef.RequireLiteralType( 1703 VD->getLocation(), VD->getType(), 1704 diag::err_constexpr_local_var_non_literal_type, 1705 isa<CXXConstructorDecl>(Dcl))) 1706 return false; 1707 if (!VD->getType()->isDependentType() && 1708 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1709 SemaRef.Diag(VD->getLocation(), 1710 diag::err_constexpr_local_var_no_init) 1711 << isa<CXXConstructorDecl>(Dcl); 1712 return false; 1713 } 1714 } 1715 SemaRef.Diag(VD->getLocation(), 1716 SemaRef.getLangOpts().CPlusPlus14 1717 ? diag::warn_cxx11_compat_constexpr_local_var 1718 : diag::ext_constexpr_local_var) 1719 << isa<CXXConstructorDecl>(Dcl); 1720 continue; 1721 } 1722 1723 case Decl::NamespaceAlias: 1724 case Decl::Function: 1725 // These are disallowed in C++11 and permitted in C++1y. Allow them 1726 // everywhere as an extension. 1727 if (!Cxx1yLoc.isValid()) 1728 Cxx1yLoc = DS->getLocStart(); 1729 continue; 1730 1731 default: 1732 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1733 << isa<CXXConstructorDecl>(Dcl); 1734 return false; 1735 } 1736 } 1737 1738 return true; 1739 } 1740 1741 /// Check that the given field is initialized within a constexpr constructor. 1742 /// 1743 /// \param Dcl The constexpr constructor being checked. 1744 /// \param Field The field being checked. This may be a member of an anonymous 1745 /// struct or union nested within the class being checked. 1746 /// \param Inits All declarations, including anonymous struct/union members and 1747 /// indirect members, for which any initialization was provided. 1748 /// \param Diagnosed Set to true if an error is produced. 1749 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1750 const FunctionDecl *Dcl, 1751 FieldDecl *Field, 1752 llvm::SmallSet<Decl*, 16> &Inits, 1753 bool &Diagnosed) { 1754 if (Field->isInvalidDecl()) 1755 return; 1756 1757 if (Field->isUnnamedBitfield()) 1758 return; 1759 1760 // Anonymous unions with no variant members and empty anonymous structs do not 1761 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1762 // indirect fields don't need initializing. 1763 if (Field->isAnonymousStructOrUnion() && 1764 (Field->getType()->isUnionType() 1765 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1766 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1767 return; 1768 1769 if (!Inits.count(Field)) { 1770 if (!Diagnosed) { 1771 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1772 Diagnosed = true; 1773 } 1774 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1775 } else if (Field->isAnonymousStructOrUnion()) { 1776 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1777 for (auto *I : RD->fields()) 1778 // If an anonymous union contains an anonymous struct of which any member 1779 // is initialized, all members must be initialized. 1780 if (!RD->isUnion() || Inits.count(I)) 1781 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1782 } 1783 } 1784 1785 /// Check the provided statement is allowed in a constexpr function 1786 /// definition. 1787 static bool 1788 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1789 SmallVectorImpl<SourceLocation> &ReturnStmts, 1790 SourceLocation &Cxx1yLoc) { 1791 // - its function-body shall be [...] a compound-statement that contains only 1792 switch (S->getStmtClass()) { 1793 case Stmt::NullStmtClass: 1794 // - null statements, 1795 return true; 1796 1797 case Stmt::DeclStmtClass: 1798 // - static_assert-declarations 1799 // - using-declarations, 1800 // - using-directives, 1801 // - typedef declarations and alias-declarations that do not define 1802 // classes or enumerations, 1803 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1804 return false; 1805 return true; 1806 1807 case Stmt::ReturnStmtClass: 1808 // - and exactly one return statement; 1809 if (isa<CXXConstructorDecl>(Dcl)) { 1810 // C++1y allows return statements in constexpr constructors. 1811 if (!Cxx1yLoc.isValid()) 1812 Cxx1yLoc = S->getLocStart(); 1813 return true; 1814 } 1815 1816 ReturnStmts.push_back(S->getLocStart()); 1817 return true; 1818 1819 case Stmt::CompoundStmtClass: { 1820 // C++1y allows compound-statements. 1821 if (!Cxx1yLoc.isValid()) 1822 Cxx1yLoc = S->getLocStart(); 1823 1824 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1825 for (auto *BodyIt : CompStmt->body()) { 1826 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1827 Cxx1yLoc)) 1828 return false; 1829 } 1830 return true; 1831 } 1832 1833 case Stmt::AttributedStmtClass: 1834 if (!Cxx1yLoc.isValid()) 1835 Cxx1yLoc = S->getLocStart(); 1836 return true; 1837 1838 case Stmt::IfStmtClass: { 1839 // C++1y allows if-statements. 1840 if (!Cxx1yLoc.isValid()) 1841 Cxx1yLoc = S->getLocStart(); 1842 1843 IfStmt *If = cast<IfStmt>(S); 1844 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1845 Cxx1yLoc)) 1846 return false; 1847 if (If->getElse() && 1848 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1849 Cxx1yLoc)) 1850 return false; 1851 return true; 1852 } 1853 1854 case Stmt::WhileStmtClass: 1855 case Stmt::DoStmtClass: 1856 case Stmt::ForStmtClass: 1857 case Stmt::CXXForRangeStmtClass: 1858 case Stmt::ContinueStmtClass: 1859 // C++1y allows all of these. We don't allow them as extensions in C++11, 1860 // because they don't make sense without variable mutation. 1861 if (!SemaRef.getLangOpts().CPlusPlus14) 1862 break; 1863 if (!Cxx1yLoc.isValid()) 1864 Cxx1yLoc = S->getLocStart(); 1865 for (Stmt *SubStmt : S->children()) 1866 if (SubStmt && 1867 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1868 Cxx1yLoc)) 1869 return false; 1870 return true; 1871 1872 case Stmt::SwitchStmtClass: 1873 case Stmt::CaseStmtClass: 1874 case Stmt::DefaultStmtClass: 1875 case Stmt::BreakStmtClass: 1876 // C++1y allows switch-statements, and since they don't need variable 1877 // mutation, we can reasonably allow them in C++11 as an extension. 1878 if (!Cxx1yLoc.isValid()) 1879 Cxx1yLoc = S->getLocStart(); 1880 for (Stmt *SubStmt : S->children()) 1881 if (SubStmt && 1882 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1883 Cxx1yLoc)) 1884 return false; 1885 return true; 1886 1887 default: 1888 if (!isa<Expr>(S)) 1889 break; 1890 1891 // C++1y allows expression-statements. 1892 if (!Cxx1yLoc.isValid()) 1893 Cxx1yLoc = S->getLocStart(); 1894 return true; 1895 } 1896 1897 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1898 << isa<CXXConstructorDecl>(Dcl); 1899 return false; 1900 } 1901 1902 /// Check the body for the given constexpr function declaration only contains 1903 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1904 /// 1905 /// \return true if the body is OK, false if we have diagnosed a problem. 1906 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1907 if (isa<CXXTryStmt>(Body)) { 1908 // C++11 [dcl.constexpr]p3: 1909 // The definition of a constexpr function shall satisfy the following 1910 // constraints: [...] 1911 // - its function-body shall be = delete, = default, or a 1912 // compound-statement 1913 // 1914 // C++11 [dcl.constexpr]p4: 1915 // In the definition of a constexpr constructor, [...] 1916 // - its function-body shall not be a function-try-block; 1917 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1918 << isa<CXXConstructorDecl>(Dcl); 1919 return false; 1920 } 1921 1922 SmallVector<SourceLocation, 4> ReturnStmts; 1923 1924 // - its function-body shall be [...] a compound-statement that contains only 1925 // [... list of cases ...] 1926 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1927 SourceLocation Cxx1yLoc; 1928 for (auto *BodyIt : CompBody->body()) { 1929 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1930 return false; 1931 } 1932 1933 if (Cxx1yLoc.isValid()) 1934 Diag(Cxx1yLoc, 1935 getLangOpts().CPlusPlus14 1936 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1937 : diag::ext_constexpr_body_invalid_stmt) 1938 << isa<CXXConstructorDecl>(Dcl); 1939 1940 if (const CXXConstructorDecl *Constructor 1941 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1942 const CXXRecordDecl *RD = Constructor->getParent(); 1943 // DR1359: 1944 // - every non-variant non-static data member and base class sub-object 1945 // shall be initialized; 1946 // DR1460: 1947 // - if the class is a union having variant members, exactly one of them 1948 // shall be initialized; 1949 if (RD->isUnion()) { 1950 if (Constructor->getNumCtorInitializers() == 0 && 1951 RD->hasVariantMembers()) { 1952 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1953 return false; 1954 } 1955 } else if (!Constructor->isDependentContext() && 1956 !Constructor->isDelegatingConstructor()) { 1957 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1958 1959 // Skip detailed checking if we have enough initializers, and we would 1960 // allow at most one initializer per member. 1961 bool AnyAnonStructUnionMembers = false; 1962 unsigned Fields = 0; 1963 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1964 E = RD->field_end(); I != E; ++I, ++Fields) { 1965 if (I->isAnonymousStructOrUnion()) { 1966 AnyAnonStructUnionMembers = true; 1967 break; 1968 } 1969 } 1970 // DR1460: 1971 // - if the class is a union-like class, but is not a union, for each of 1972 // its anonymous union members having variant members, exactly one of 1973 // them shall be initialized; 1974 if (AnyAnonStructUnionMembers || 1975 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1976 // Check initialization of non-static data members. Base classes are 1977 // always initialized so do not need to be checked. Dependent bases 1978 // might not have initializers in the member initializer list. 1979 llvm::SmallSet<Decl*, 16> Inits; 1980 for (const auto *I: Constructor->inits()) { 1981 if (FieldDecl *FD = I->getMember()) 1982 Inits.insert(FD); 1983 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1984 Inits.insert(ID->chain_begin(), ID->chain_end()); 1985 } 1986 1987 bool Diagnosed = false; 1988 for (auto *I : RD->fields()) 1989 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1990 if (Diagnosed) 1991 return false; 1992 } 1993 } 1994 } else { 1995 if (ReturnStmts.empty()) { 1996 // C++1y doesn't require constexpr functions to contain a 'return' 1997 // statement. We still do, unless the return type might be void, because 1998 // otherwise if there's no return statement, the function cannot 1999 // be used in a core constant expression. 2000 bool OK = getLangOpts().CPlusPlus14 && 2001 (Dcl->getReturnType()->isVoidType() || 2002 Dcl->getReturnType()->isDependentType()); 2003 Diag(Dcl->getLocation(), 2004 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2005 : diag::err_constexpr_body_no_return); 2006 if (!OK) 2007 return false; 2008 } else if (ReturnStmts.size() > 1) { 2009 Diag(ReturnStmts.back(), 2010 getLangOpts().CPlusPlus14 2011 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2012 : diag::ext_constexpr_body_multiple_return); 2013 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2014 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2015 } 2016 } 2017 2018 // C++11 [dcl.constexpr]p5: 2019 // if no function argument values exist such that the function invocation 2020 // substitution would produce a constant expression, the program is 2021 // ill-formed; no diagnostic required. 2022 // C++11 [dcl.constexpr]p3: 2023 // - every constructor call and implicit conversion used in initializing the 2024 // return value shall be one of those allowed in a constant expression. 2025 // C++11 [dcl.constexpr]p4: 2026 // - every constructor involved in initializing non-static data members and 2027 // base class sub-objects shall be a constexpr constructor. 2028 SmallVector<PartialDiagnosticAt, 8> Diags; 2029 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2030 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2031 << isa<CXXConstructorDecl>(Dcl); 2032 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2033 Diag(Diags[I].first, Diags[I].second); 2034 // Don't return false here: we allow this for compatibility in 2035 // system headers. 2036 } 2037 2038 return true; 2039 } 2040 2041 /// isCurrentClassName - Determine whether the identifier II is the 2042 /// name of the class type currently being defined. In the case of 2043 /// nested classes, this will only return true if II is the name of 2044 /// the innermost class. 2045 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2046 const CXXScopeSpec *SS) { 2047 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2048 2049 CXXRecordDecl *CurDecl; 2050 if (SS && SS->isSet() && !SS->isInvalid()) { 2051 DeclContext *DC = computeDeclContext(*SS, true); 2052 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2053 } else 2054 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2055 2056 if (CurDecl && CurDecl->getIdentifier()) 2057 return &II == CurDecl->getIdentifier(); 2058 return false; 2059 } 2060 2061 /// \brief Determine whether the identifier II is a typo for the name of 2062 /// the class type currently being defined. If so, update it to the identifier 2063 /// that should have been used. 2064 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2065 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2066 2067 if (!getLangOpts().SpellChecking) 2068 return false; 2069 2070 CXXRecordDecl *CurDecl; 2071 if (SS && SS->isSet() && !SS->isInvalid()) { 2072 DeclContext *DC = computeDeclContext(*SS, true); 2073 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2074 } else 2075 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2076 2077 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2078 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2079 < II->getLength()) { 2080 II = CurDecl->getIdentifier(); 2081 return true; 2082 } 2083 2084 return false; 2085 } 2086 2087 /// \brief Determine whether the given class is a base class of the given 2088 /// class, including looking at dependent bases. 2089 static bool findCircularInheritance(const CXXRecordDecl *Class, 2090 const CXXRecordDecl *Current) { 2091 SmallVector<const CXXRecordDecl*, 8> Queue; 2092 2093 Class = Class->getCanonicalDecl(); 2094 while (true) { 2095 for (const auto &I : Current->bases()) { 2096 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2097 if (!Base) 2098 continue; 2099 2100 Base = Base->getDefinition(); 2101 if (!Base) 2102 continue; 2103 2104 if (Base->getCanonicalDecl() == Class) 2105 return true; 2106 2107 Queue.push_back(Base); 2108 } 2109 2110 if (Queue.empty()) 2111 return false; 2112 2113 Current = Queue.pop_back_val(); 2114 } 2115 2116 return false; 2117 } 2118 2119 /// \brief Check the validity of a C++ base class specifier. 2120 /// 2121 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2122 /// and returns NULL otherwise. 2123 CXXBaseSpecifier * 2124 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2125 SourceRange SpecifierRange, 2126 bool Virtual, AccessSpecifier Access, 2127 TypeSourceInfo *TInfo, 2128 SourceLocation EllipsisLoc) { 2129 QualType BaseType = TInfo->getType(); 2130 2131 // C++ [class.union]p1: 2132 // A union shall not have base classes. 2133 if (Class->isUnion()) { 2134 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2135 << SpecifierRange; 2136 return nullptr; 2137 } 2138 2139 if (EllipsisLoc.isValid() && 2140 !TInfo->getType()->containsUnexpandedParameterPack()) { 2141 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2142 << TInfo->getTypeLoc().getSourceRange(); 2143 EllipsisLoc = SourceLocation(); 2144 } 2145 2146 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2147 2148 if (BaseType->isDependentType()) { 2149 // Make sure that we don't have circular inheritance among our dependent 2150 // bases. For non-dependent bases, the check for completeness below handles 2151 // this. 2152 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2153 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2154 ((BaseDecl = BaseDecl->getDefinition()) && 2155 findCircularInheritance(Class, BaseDecl))) { 2156 Diag(BaseLoc, diag::err_circular_inheritance) 2157 << BaseType << Context.getTypeDeclType(Class); 2158 2159 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2160 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2161 << BaseType; 2162 2163 return nullptr; 2164 } 2165 } 2166 2167 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2168 Class->getTagKind() == TTK_Class, 2169 Access, TInfo, EllipsisLoc); 2170 } 2171 2172 // Base specifiers must be record types. 2173 if (!BaseType->isRecordType()) { 2174 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2175 return nullptr; 2176 } 2177 2178 // C++ [class.union]p1: 2179 // A union shall not be used as a base class. 2180 if (BaseType->isUnionType()) { 2181 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2182 return nullptr; 2183 } 2184 2185 // For the MS ABI, propagate DLL attributes to base class templates. 2186 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2187 if (Attr *ClassAttr = getDLLAttr(Class)) { 2188 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2189 BaseType->getAsCXXRecordDecl())) { 2190 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2191 BaseLoc); 2192 } 2193 } 2194 } 2195 2196 // C++ [class.derived]p2: 2197 // The class-name in a base-specifier shall not be an incompletely 2198 // defined class. 2199 if (RequireCompleteType(BaseLoc, BaseType, 2200 diag::err_incomplete_base_class, SpecifierRange)) { 2201 Class->setInvalidDecl(); 2202 return nullptr; 2203 } 2204 2205 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2206 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2207 assert(BaseDecl && "Record type has no declaration"); 2208 BaseDecl = BaseDecl->getDefinition(); 2209 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2210 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2211 assert(CXXBaseDecl && "Base type is not a C++ type"); 2212 2213 // A class which contains a flexible array member is not suitable for use as a 2214 // base class: 2215 // - If the layout determines that a base comes before another base, 2216 // the flexible array member would index into the subsequent base. 2217 // - If the layout determines that base comes before the derived class, 2218 // the flexible array member would index into the derived class. 2219 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2220 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2221 << CXXBaseDecl->getDeclName(); 2222 return nullptr; 2223 } 2224 2225 // C++ [class]p3: 2226 // If a class is marked final and it appears as a base-type-specifier in 2227 // base-clause, the program is ill-formed. 2228 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2229 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2230 << CXXBaseDecl->getDeclName() 2231 << FA->isSpelledAsSealed(); 2232 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2233 << CXXBaseDecl->getDeclName() << FA->getRange(); 2234 return nullptr; 2235 } 2236 2237 if (BaseDecl->isInvalidDecl()) 2238 Class->setInvalidDecl(); 2239 2240 // Create the base specifier. 2241 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2242 Class->getTagKind() == TTK_Class, 2243 Access, TInfo, EllipsisLoc); 2244 } 2245 2246 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2247 /// one entry in the base class list of a class specifier, for 2248 /// example: 2249 /// class foo : public bar, virtual private baz { 2250 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2251 BaseResult 2252 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2253 ParsedAttributes &Attributes, 2254 bool Virtual, AccessSpecifier Access, 2255 ParsedType basetype, SourceLocation BaseLoc, 2256 SourceLocation EllipsisLoc) { 2257 if (!classdecl) 2258 return true; 2259 2260 AdjustDeclIfTemplate(classdecl); 2261 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2262 if (!Class) 2263 return true; 2264 2265 // We haven't yet attached the base specifiers. 2266 Class->setIsParsingBaseSpecifiers(); 2267 2268 // We do not support any C++11 attributes on base-specifiers yet. 2269 // Diagnose any attributes we see. 2270 if (!Attributes.empty()) { 2271 for (AttributeList *Attr = Attributes.getList(); Attr; 2272 Attr = Attr->getNext()) { 2273 if (Attr->isInvalid() || 2274 Attr->getKind() == AttributeList::IgnoredAttribute) 2275 continue; 2276 Diag(Attr->getLoc(), 2277 Attr->getKind() == AttributeList::UnknownAttribute 2278 ? diag::warn_unknown_attribute_ignored 2279 : diag::err_base_specifier_attribute) 2280 << Attr->getName(); 2281 } 2282 } 2283 2284 TypeSourceInfo *TInfo = nullptr; 2285 GetTypeFromParser(basetype, &TInfo); 2286 2287 if (EllipsisLoc.isInvalid() && 2288 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2289 UPPC_BaseType)) 2290 return true; 2291 2292 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2293 Virtual, Access, TInfo, 2294 EllipsisLoc)) 2295 return BaseSpec; 2296 else 2297 Class->setInvalidDecl(); 2298 2299 return true; 2300 } 2301 2302 /// Use small set to collect indirect bases. As this is only used 2303 /// locally, there's no need to abstract the small size parameter. 2304 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2305 2306 /// \brief Recursively add the bases of Type. Don't add Type itself. 2307 static void 2308 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2309 const QualType &Type) 2310 { 2311 // Even though the incoming type is a base, it might not be 2312 // a class -- it could be a template parm, for instance. 2313 if (auto Rec = Type->getAs<RecordType>()) { 2314 auto Decl = Rec->getAsCXXRecordDecl(); 2315 2316 // Iterate over its bases. 2317 for (const auto &BaseSpec : Decl->bases()) { 2318 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2319 .getUnqualifiedType(); 2320 if (Set.insert(Base).second) 2321 // If we've not already seen it, recurse. 2322 NoteIndirectBases(Context, Set, Base); 2323 } 2324 } 2325 } 2326 2327 /// \brief Performs the actual work of attaching the given base class 2328 /// specifiers to a C++ class. 2329 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2330 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2331 if (Bases.empty()) 2332 return false; 2333 2334 // Used to keep track of which base types we have already seen, so 2335 // that we can properly diagnose redundant direct base types. Note 2336 // that the key is always the unqualified canonical type of the base 2337 // class. 2338 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2339 2340 // Used to track indirect bases so we can see if a direct base is 2341 // ambiguous. 2342 IndirectBaseSet IndirectBaseTypes; 2343 2344 // Copy non-redundant base specifiers into permanent storage. 2345 unsigned NumGoodBases = 0; 2346 bool Invalid = false; 2347 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2348 QualType NewBaseType 2349 = Context.getCanonicalType(Bases[idx]->getType()); 2350 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2351 2352 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2353 if (KnownBase) { 2354 // C++ [class.mi]p3: 2355 // A class shall not be specified as a direct base class of a 2356 // derived class more than once. 2357 Diag(Bases[idx]->getLocStart(), 2358 diag::err_duplicate_base_class) 2359 << KnownBase->getType() 2360 << Bases[idx]->getSourceRange(); 2361 2362 // Delete the duplicate base class specifier; we're going to 2363 // overwrite its pointer later. 2364 Context.Deallocate(Bases[idx]); 2365 2366 Invalid = true; 2367 } else { 2368 // Okay, add this new base class. 2369 KnownBase = Bases[idx]; 2370 Bases[NumGoodBases++] = Bases[idx]; 2371 2372 // Note this base's direct & indirect bases, if there could be ambiguity. 2373 if (Bases.size() > 1) 2374 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2375 2376 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2377 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2378 if (Class->isInterface() && 2379 (!RD->isInterface() || 2380 KnownBase->getAccessSpecifier() != AS_public)) { 2381 // The Microsoft extension __interface does not permit bases that 2382 // are not themselves public interfaces. 2383 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2384 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 2385 << RD->getSourceRange(); 2386 Invalid = true; 2387 } 2388 if (RD->hasAttr<WeakAttr>()) 2389 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2390 } 2391 } 2392 } 2393 2394 // Attach the remaining base class specifiers to the derived class. 2395 Class->setBases(Bases.data(), NumGoodBases); 2396 2397 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2398 // Check whether this direct base is inaccessible due to ambiguity. 2399 QualType BaseType = Bases[idx]->getType(); 2400 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2401 .getUnqualifiedType(); 2402 2403 if (IndirectBaseTypes.count(CanonicalBase)) { 2404 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2405 /*DetectVirtual=*/true); 2406 bool found 2407 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2408 assert(found); 2409 (void)found; 2410 2411 if (Paths.isAmbiguous(CanonicalBase)) 2412 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2413 << BaseType << getAmbiguousPathsDisplayString(Paths) 2414 << Bases[idx]->getSourceRange(); 2415 else 2416 assert(Bases[idx]->isVirtual()); 2417 } 2418 2419 // Delete the base class specifier, since its data has been copied 2420 // into the CXXRecordDecl. 2421 Context.Deallocate(Bases[idx]); 2422 } 2423 2424 return Invalid; 2425 } 2426 2427 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2428 /// class, after checking whether there are any duplicate base 2429 /// classes. 2430 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2431 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2432 if (!ClassDecl || Bases.empty()) 2433 return; 2434 2435 AdjustDeclIfTemplate(ClassDecl); 2436 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2437 } 2438 2439 /// \brief Determine whether the type \p Derived is a C++ class that is 2440 /// derived from the type \p Base. 2441 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2442 if (!getLangOpts().CPlusPlus) 2443 return false; 2444 2445 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2446 if (!DerivedRD) 2447 return false; 2448 2449 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2450 if (!BaseRD) 2451 return false; 2452 2453 // If either the base or the derived type is invalid, don't try to 2454 // check whether one is derived from the other. 2455 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2456 return false; 2457 2458 // FIXME: In a modules build, do we need the entire path to be visible for us 2459 // to be able to use the inheritance relationship? 2460 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2461 return false; 2462 2463 return DerivedRD->isDerivedFrom(BaseRD); 2464 } 2465 2466 /// \brief Determine whether the type \p Derived is a C++ class that is 2467 /// derived from the type \p Base. 2468 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2469 CXXBasePaths &Paths) { 2470 if (!getLangOpts().CPlusPlus) 2471 return false; 2472 2473 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2474 if (!DerivedRD) 2475 return false; 2476 2477 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2478 if (!BaseRD) 2479 return false; 2480 2481 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2482 return false; 2483 2484 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2485 } 2486 2487 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2488 CXXCastPath &BasePathArray) { 2489 assert(BasePathArray.empty() && "Base path array must be empty!"); 2490 assert(Paths.isRecordingPaths() && "Must record paths!"); 2491 2492 const CXXBasePath &Path = Paths.front(); 2493 2494 // We first go backward and check if we have a virtual base. 2495 // FIXME: It would be better if CXXBasePath had the base specifier for 2496 // the nearest virtual base. 2497 unsigned Start = 0; 2498 for (unsigned I = Path.size(); I != 0; --I) { 2499 if (Path[I - 1].Base->isVirtual()) { 2500 Start = I - 1; 2501 break; 2502 } 2503 } 2504 2505 // Now add all bases. 2506 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2507 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2508 } 2509 2510 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2511 /// conversion (where Derived and Base are class types) is 2512 /// well-formed, meaning that the conversion is unambiguous (and 2513 /// that all of the base classes are accessible). Returns true 2514 /// and emits a diagnostic if the code is ill-formed, returns false 2515 /// otherwise. Loc is the location where this routine should point to 2516 /// if there is an error, and Range is the source range to highlight 2517 /// if there is an error. 2518 /// 2519 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2520 /// diagnostic for the respective type of error will be suppressed, but the 2521 /// check for ill-formed code will still be performed. 2522 bool 2523 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2524 unsigned InaccessibleBaseID, 2525 unsigned AmbigiousBaseConvID, 2526 SourceLocation Loc, SourceRange Range, 2527 DeclarationName Name, 2528 CXXCastPath *BasePath, 2529 bool IgnoreAccess) { 2530 // First, determine whether the path from Derived to Base is 2531 // ambiguous. This is slightly more expensive than checking whether 2532 // the Derived to Base conversion exists, because here we need to 2533 // explore multiple paths to determine if there is an ambiguity. 2534 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2535 /*DetectVirtual=*/false); 2536 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2537 assert(DerivationOkay && 2538 "Can only be used with a derived-to-base conversion"); 2539 (void)DerivationOkay; 2540 2541 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 2542 if (!IgnoreAccess) { 2543 // Check that the base class can be accessed. 2544 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 2545 InaccessibleBaseID)) { 2546 case AR_inaccessible: 2547 return true; 2548 case AR_accessible: 2549 case AR_dependent: 2550 case AR_delayed: 2551 break; 2552 } 2553 } 2554 2555 // Build a base path if necessary. 2556 if (BasePath) 2557 BuildBasePathArray(Paths, *BasePath); 2558 return false; 2559 } 2560 2561 if (AmbigiousBaseConvID) { 2562 // We know that the derived-to-base conversion is ambiguous, and 2563 // we're going to produce a diagnostic. Perform the derived-to-base 2564 // search just one more time to compute all of the possible paths so 2565 // that we can print them out. This is more expensive than any of 2566 // the previous derived-to-base checks we've done, but at this point 2567 // performance isn't as much of an issue. 2568 Paths.clear(); 2569 Paths.setRecordingPaths(true); 2570 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2571 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2572 (void)StillOkay; 2573 2574 // Build up a textual representation of the ambiguous paths, e.g., 2575 // D -> B -> A, that will be used to illustrate the ambiguous 2576 // conversions in the diagnostic. We only print one of the paths 2577 // to each base class subobject. 2578 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2579 2580 Diag(Loc, AmbigiousBaseConvID) 2581 << Derived << Base << PathDisplayStr << Range << Name; 2582 } 2583 return true; 2584 } 2585 2586 bool 2587 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2588 SourceLocation Loc, SourceRange Range, 2589 CXXCastPath *BasePath, 2590 bool IgnoreAccess) { 2591 return CheckDerivedToBaseConversion( 2592 Derived, Base, diag::err_upcast_to_inaccessible_base, 2593 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2594 BasePath, IgnoreAccess); 2595 } 2596 2597 2598 /// @brief Builds a string representing ambiguous paths from a 2599 /// specific derived class to different subobjects of the same base 2600 /// class. 2601 /// 2602 /// This function builds a string that can be used in error messages 2603 /// to show the different paths that one can take through the 2604 /// inheritance hierarchy to go from the derived class to different 2605 /// subobjects of a base class. The result looks something like this: 2606 /// @code 2607 /// struct D -> struct B -> struct A 2608 /// struct D -> struct C -> struct A 2609 /// @endcode 2610 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2611 std::string PathDisplayStr; 2612 std::set<unsigned> DisplayedPaths; 2613 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2614 Path != Paths.end(); ++Path) { 2615 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2616 // We haven't displayed a path to this particular base 2617 // class subobject yet. 2618 PathDisplayStr += "\n "; 2619 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2620 for (CXXBasePath::const_iterator Element = Path->begin(); 2621 Element != Path->end(); ++Element) 2622 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2623 } 2624 } 2625 2626 return PathDisplayStr; 2627 } 2628 2629 //===----------------------------------------------------------------------===// 2630 // C++ class member Handling 2631 //===----------------------------------------------------------------------===// 2632 2633 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2634 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2635 SourceLocation ASLoc, 2636 SourceLocation ColonLoc, 2637 AttributeList *Attrs) { 2638 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2639 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2640 ASLoc, ColonLoc); 2641 CurContext->addHiddenDecl(ASDecl); 2642 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2643 } 2644 2645 /// CheckOverrideControl - Check C++11 override control semantics. 2646 void Sema::CheckOverrideControl(NamedDecl *D) { 2647 if (D->isInvalidDecl()) 2648 return; 2649 2650 // We only care about "override" and "final" declarations. 2651 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2652 return; 2653 2654 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2655 2656 // We can't check dependent instance methods. 2657 if (MD && MD->isInstance() && 2658 (MD->getParent()->hasAnyDependentBases() || 2659 MD->getType()->isDependentType())) 2660 return; 2661 2662 if (MD && !MD->isVirtual()) { 2663 // If we have a non-virtual method, check if if hides a virtual method. 2664 // (In that case, it's most likely the method has the wrong type.) 2665 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2666 FindHiddenVirtualMethods(MD, OverloadedMethods); 2667 2668 if (!OverloadedMethods.empty()) { 2669 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2670 Diag(OA->getLocation(), 2671 diag::override_keyword_hides_virtual_member_function) 2672 << "override" << (OverloadedMethods.size() > 1); 2673 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2674 Diag(FA->getLocation(), 2675 diag::override_keyword_hides_virtual_member_function) 2676 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2677 << (OverloadedMethods.size() > 1); 2678 } 2679 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2680 MD->setInvalidDecl(); 2681 return; 2682 } 2683 // Fall through into the general case diagnostic. 2684 // FIXME: We might want to attempt typo correction here. 2685 } 2686 2687 if (!MD || !MD->isVirtual()) { 2688 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2689 Diag(OA->getLocation(), 2690 diag::override_keyword_only_allowed_on_virtual_member_functions) 2691 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2692 D->dropAttr<OverrideAttr>(); 2693 } 2694 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2695 Diag(FA->getLocation(), 2696 diag::override_keyword_only_allowed_on_virtual_member_functions) 2697 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2698 << FixItHint::CreateRemoval(FA->getLocation()); 2699 D->dropAttr<FinalAttr>(); 2700 } 2701 return; 2702 } 2703 2704 // C++11 [class.virtual]p5: 2705 // If a function is marked with the virt-specifier override and 2706 // does not override a member function of a base class, the program is 2707 // ill-formed. 2708 bool HasOverriddenMethods = 2709 MD->begin_overridden_methods() != MD->end_overridden_methods(); 2710 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2711 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2712 << MD->getDeclName(); 2713 } 2714 2715 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2716 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2717 return; 2718 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2719 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2720 return; 2721 2722 SourceLocation Loc = MD->getLocation(); 2723 SourceLocation SpellingLoc = Loc; 2724 if (getSourceManager().isMacroArgExpansion(Loc)) 2725 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 2726 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2727 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2728 return; 2729 2730 if (MD->size_overridden_methods() > 0) { 2731 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2732 ? diag::warn_destructor_marked_not_override_overriding 2733 : diag::warn_function_marked_not_override_overriding; 2734 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2735 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2736 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2737 } 2738 } 2739 2740 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2741 /// function overrides a virtual member function marked 'final', according to 2742 /// C++11 [class.virtual]p4. 2743 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2744 const CXXMethodDecl *Old) { 2745 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2746 if (!FA) 2747 return false; 2748 2749 Diag(New->getLocation(), diag::err_final_function_overridden) 2750 << New->getDeclName() 2751 << FA->isSpelledAsSealed(); 2752 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2753 return true; 2754 } 2755 2756 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2757 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2758 // FIXME: Destruction of ObjC lifetime types has side-effects. 2759 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2760 return !RD->isCompleteDefinition() || 2761 !RD->hasTrivialDefaultConstructor() || 2762 !RD->hasTrivialDestructor(); 2763 return false; 2764 } 2765 2766 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2767 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2768 if (it->isDeclspecPropertyAttribute()) 2769 return it; 2770 return nullptr; 2771 } 2772 2773 // Check if there is a field shadowing. 2774 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2775 DeclarationName FieldName, 2776 const CXXRecordDecl *RD) { 2777 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2778 return; 2779 2780 // To record a shadowed field in a base 2781 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2782 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2783 CXXBasePath &Path) { 2784 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2785 // Record an ambiguous path directly 2786 if (Bases.find(Base) != Bases.end()) 2787 return true; 2788 for (const auto Field : Base->lookup(FieldName)) { 2789 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2790 Field->getAccess() != AS_private) { 2791 assert(Field->getAccess() != AS_none); 2792 assert(Bases.find(Base) == Bases.end()); 2793 Bases[Base] = Field; 2794 return true; 2795 } 2796 } 2797 return false; 2798 }; 2799 2800 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2801 /*DetectVirtual=*/true); 2802 if (!RD->lookupInBases(FieldShadowed, Paths)) 2803 return; 2804 2805 for (const auto &P : Paths) { 2806 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2807 auto It = Bases.find(Base); 2808 // Skip duplicated bases 2809 if (It == Bases.end()) 2810 continue; 2811 auto BaseField = It->second; 2812 assert(BaseField->getAccess() != AS_private); 2813 if (AS_none != 2814 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2815 Diag(Loc, diag::warn_shadow_field) 2816 << FieldName.getAsString() << RD->getName() << Base->getName(); 2817 Diag(BaseField->getLocation(), diag::note_shadow_field); 2818 Bases.erase(It); 2819 } 2820 } 2821 } 2822 2823 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2824 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2825 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2826 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2827 /// present (but parsing it has been deferred). 2828 NamedDecl * 2829 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2830 MultiTemplateParamsArg TemplateParameterLists, 2831 Expr *BW, const VirtSpecifiers &VS, 2832 InClassInitStyle InitStyle) { 2833 const DeclSpec &DS = D.getDeclSpec(); 2834 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2835 DeclarationName Name = NameInfo.getName(); 2836 SourceLocation Loc = NameInfo.getLoc(); 2837 2838 // For anonymous bitfields, the location should point to the type. 2839 if (Loc.isInvalid()) 2840 Loc = D.getLocStart(); 2841 2842 Expr *BitWidth = static_cast<Expr*>(BW); 2843 2844 assert(isa<CXXRecordDecl>(CurContext)); 2845 assert(!DS.isFriendSpecified()); 2846 2847 bool isFunc = D.isDeclarationOfFunction(); 2848 2849 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2850 // The Microsoft extension __interface only permits public member functions 2851 // and prohibits constructors, destructors, operators, non-public member 2852 // functions, static methods and data members. 2853 unsigned InvalidDecl; 2854 bool ShowDeclName = true; 2855 if (!isFunc) 2856 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2857 else if (AS != AS_public) 2858 InvalidDecl = 2; 2859 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2860 InvalidDecl = 3; 2861 else switch (Name.getNameKind()) { 2862 case DeclarationName::CXXConstructorName: 2863 InvalidDecl = 4; 2864 ShowDeclName = false; 2865 break; 2866 2867 case DeclarationName::CXXDestructorName: 2868 InvalidDecl = 5; 2869 ShowDeclName = false; 2870 break; 2871 2872 case DeclarationName::CXXOperatorName: 2873 case DeclarationName::CXXConversionFunctionName: 2874 InvalidDecl = 6; 2875 break; 2876 2877 default: 2878 InvalidDecl = 0; 2879 break; 2880 } 2881 2882 if (InvalidDecl) { 2883 if (ShowDeclName) 2884 Diag(Loc, diag::err_invalid_member_in_interface) 2885 << (InvalidDecl-1) << Name; 2886 else 2887 Diag(Loc, diag::err_invalid_member_in_interface) 2888 << (InvalidDecl-1) << ""; 2889 return nullptr; 2890 } 2891 } 2892 2893 // C++ 9.2p6: A member shall not be declared to have automatic storage 2894 // duration (auto, register) or with the extern storage-class-specifier. 2895 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2896 // data members and cannot be applied to names declared const or static, 2897 // and cannot be applied to reference members. 2898 switch (DS.getStorageClassSpec()) { 2899 case DeclSpec::SCS_unspecified: 2900 case DeclSpec::SCS_typedef: 2901 case DeclSpec::SCS_static: 2902 break; 2903 case DeclSpec::SCS_mutable: 2904 if (isFunc) { 2905 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2906 2907 // FIXME: It would be nicer if the keyword was ignored only for this 2908 // declarator. Otherwise we could get follow-up errors. 2909 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2910 } 2911 break; 2912 default: 2913 Diag(DS.getStorageClassSpecLoc(), 2914 diag::err_storageclass_invalid_for_member); 2915 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2916 break; 2917 } 2918 2919 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2920 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2921 !isFunc); 2922 2923 if (DS.isConstexprSpecified() && isInstField) { 2924 SemaDiagnosticBuilder B = 2925 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2926 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2927 if (InitStyle == ICIS_NoInit) { 2928 B << 0 << 0; 2929 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2930 B << FixItHint::CreateRemoval(ConstexprLoc); 2931 else { 2932 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2933 D.getMutableDeclSpec().ClearConstexprSpec(); 2934 const char *PrevSpec; 2935 unsigned DiagID; 2936 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2937 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2938 (void)Failed; 2939 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2940 } 2941 } else { 2942 B << 1; 2943 const char *PrevSpec; 2944 unsigned DiagID; 2945 if (D.getMutableDeclSpec().SetStorageClassSpec( 2946 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2947 Context.getPrintingPolicy())) { 2948 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2949 "This is the only DeclSpec that should fail to be applied"); 2950 B << 1; 2951 } else { 2952 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2953 isInstField = false; 2954 } 2955 } 2956 } 2957 2958 NamedDecl *Member; 2959 if (isInstField) { 2960 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2961 2962 // Data members must have identifiers for names. 2963 if (!Name.isIdentifier()) { 2964 Diag(Loc, diag::err_bad_variable_name) 2965 << Name; 2966 return nullptr; 2967 } 2968 2969 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2970 2971 // Member field could not be with "template" keyword. 2972 // So TemplateParameterLists should be empty in this case. 2973 if (TemplateParameterLists.size()) { 2974 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2975 if (TemplateParams->size()) { 2976 // There is no such thing as a member field template. 2977 Diag(D.getIdentifierLoc(), diag::err_template_member) 2978 << II 2979 << SourceRange(TemplateParams->getTemplateLoc(), 2980 TemplateParams->getRAngleLoc()); 2981 } else { 2982 // There is an extraneous 'template<>' for this member. 2983 Diag(TemplateParams->getTemplateLoc(), 2984 diag::err_template_member_noparams) 2985 << II 2986 << SourceRange(TemplateParams->getTemplateLoc(), 2987 TemplateParams->getRAngleLoc()); 2988 } 2989 return nullptr; 2990 } 2991 2992 if (SS.isSet() && !SS.isInvalid()) { 2993 // The user provided a superfluous scope specifier inside a class 2994 // definition: 2995 // 2996 // class X { 2997 // int X::member; 2998 // }; 2999 if (DeclContext *DC = computeDeclContext(SS, false)) 3000 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 3001 else 3002 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3003 << Name << SS.getRange(); 3004 3005 SS.clear(); 3006 } 3007 3008 AttributeList *MSPropertyAttr = 3009 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 3010 if (MSPropertyAttr) { 3011 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3012 BitWidth, InitStyle, AS, MSPropertyAttr); 3013 if (!Member) 3014 return nullptr; 3015 isInstField = false; 3016 } else { 3017 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3018 BitWidth, InitStyle, AS); 3019 if (!Member) 3020 return nullptr; 3021 } 3022 3023 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3024 } else { 3025 Member = HandleDeclarator(S, D, TemplateParameterLists); 3026 if (!Member) 3027 return nullptr; 3028 3029 // Non-instance-fields can't have a bitfield. 3030 if (BitWidth) { 3031 if (Member->isInvalidDecl()) { 3032 // don't emit another diagnostic. 3033 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3034 // C++ 9.6p3: A bit-field shall not be a static member. 3035 // "static member 'A' cannot be a bit-field" 3036 Diag(Loc, diag::err_static_not_bitfield) 3037 << Name << BitWidth->getSourceRange(); 3038 } else if (isa<TypedefDecl>(Member)) { 3039 // "typedef member 'x' cannot be a bit-field" 3040 Diag(Loc, diag::err_typedef_not_bitfield) 3041 << Name << BitWidth->getSourceRange(); 3042 } else { 3043 // A function typedef ("typedef int f(); f a;"). 3044 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3045 Diag(Loc, diag::err_not_integral_type_bitfield) 3046 << Name << cast<ValueDecl>(Member)->getType() 3047 << BitWidth->getSourceRange(); 3048 } 3049 3050 BitWidth = nullptr; 3051 Member->setInvalidDecl(); 3052 } 3053 3054 Member->setAccess(AS); 3055 3056 // If we have declared a member function template or static data member 3057 // template, set the access of the templated declaration as well. 3058 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3059 FunTmpl->getTemplatedDecl()->setAccess(AS); 3060 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3061 VarTmpl->getTemplatedDecl()->setAccess(AS); 3062 } 3063 3064 if (VS.isOverrideSpecified()) 3065 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3066 if (VS.isFinalSpecified()) 3067 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3068 VS.isFinalSpelledSealed())); 3069 3070 if (VS.getLastLocation().isValid()) { 3071 // Update the end location of a method that has a virt-specifiers. 3072 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3073 MD->setRangeEnd(VS.getLastLocation()); 3074 } 3075 3076 CheckOverrideControl(Member); 3077 3078 assert((Name || isInstField) && "No identifier for non-field ?"); 3079 3080 if (isInstField) { 3081 FieldDecl *FD = cast<FieldDecl>(Member); 3082 FieldCollector->Add(FD); 3083 3084 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3085 // Remember all explicit private FieldDecls that have a name, no side 3086 // effects and are not part of a dependent type declaration. 3087 if (!FD->isImplicit() && FD->getDeclName() && 3088 FD->getAccess() == AS_private && 3089 !FD->hasAttr<UnusedAttr>() && 3090 !FD->getParent()->isDependentContext() && 3091 !InitializationHasSideEffects(*FD)) 3092 UnusedPrivateFields.insert(FD); 3093 } 3094 } 3095 3096 return Member; 3097 } 3098 3099 namespace { 3100 class UninitializedFieldVisitor 3101 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3102 Sema &S; 3103 // List of Decls to generate a warning on. Also remove Decls that become 3104 // initialized. 3105 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3106 // List of base classes of the record. Classes are removed after their 3107 // initializers. 3108 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3109 // Vector of decls to be removed from the Decl set prior to visiting the 3110 // nodes. These Decls may have been initialized in the prior initializer. 3111 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3112 // If non-null, add a note to the warning pointing back to the constructor. 3113 const CXXConstructorDecl *Constructor; 3114 // Variables to hold state when processing an initializer list. When 3115 // InitList is true, special case initialization of FieldDecls matching 3116 // InitListFieldDecl. 3117 bool InitList; 3118 FieldDecl *InitListFieldDecl; 3119 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3120 3121 public: 3122 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3123 UninitializedFieldVisitor(Sema &S, 3124 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3125 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3126 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3127 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3128 3129 // Returns true if the use of ME is not an uninitialized use. 3130 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3131 bool CheckReferenceOnly) { 3132 llvm::SmallVector<FieldDecl*, 4> Fields; 3133 bool ReferenceField = false; 3134 while (ME) { 3135 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3136 if (!FD) 3137 return false; 3138 Fields.push_back(FD); 3139 if (FD->getType()->isReferenceType()) 3140 ReferenceField = true; 3141 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3142 } 3143 3144 // Binding a reference to an unintialized field is not an 3145 // uninitialized use. 3146 if (CheckReferenceOnly && !ReferenceField) 3147 return true; 3148 3149 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3150 // Discard the first field since it is the field decl that is being 3151 // initialized. 3152 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3153 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3154 } 3155 3156 for (auto UsedIter = UsedFieldIndex.begin(), 3157 UsedEnd = UsedFieldIndex.end(), 3158 OrigIter = InitFieldIndex.begin(), 3159 OrigEnd = InitFieldIndex.end(); 3160 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3161 if (*UsedIter < *OrigIter) 3162 return true; 3163 if (*UsedIter > *OrigIter) 3164 break; 3165 } 3166 3167 return false; 3168 } 3169 3170 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3171 bool AddressOf) { 3172 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3173 return; 3174 3175 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3176 // or union. 3177 MemberExpr *FieldME = ME; 3178 3179 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3180 3181 Expr *Base = ME; 3182 while (MemberExpr *SubME = 3183 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3184 3185 if (isa<VarDecl>(SubME->getMemberDecl())) 3186 return; 3187 3188 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3189 if (!FD->isAnonymousStructOrUnion()) 3190 FieldME = SubME; 3191 3192 if (!FieldME->getType().isPODType(S.Context)) 3193 AllPODFields = false; 3194 3195 Base = SubME->getBase(); 3196 } 3197 3198 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3199 return; 3200 3201 if (AddressOf && AllPODFields) 3202 return; 3203 3204 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3205 3206 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3207 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3208 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3209 } 3210 3211 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3212 QualType T = BaseCast->getType(); 3213 if (T->isPointerType() && 3214 BaseClasses.count(T->getPointeeType())) { 3215 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3216 << T->getPointeeType() << FoundVD; 3217 } 3218 } 3219 } 3220 3221 if (!Decls.count(FoundVD)) 3222 return; 3223 3224 const bool IsReference = FoundVD->getType()->isReferenceType(); 3225 3226 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3227 // Special checking for initializer lists. 3228 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3229 return; 3230 } 3231 } else { 3232 // Prevent double warnings on use of unbounded references. 3233 if (CheckReferenceOnly && !IsReference) 3234 return; 3235 } 3236 3237 unsigned diag = IsReference 3238 ? diag::warn_reference_field_is_uninit 3239 : diag::warn_field_is_uninit; 3240 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3241 if (Constructor) 3242 S.Diag(Constructor->getLocation(), 3243 diag::note_uninit_in_this_constructor) 3244 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3245 3246 } 3247 3248 void HandleValue(Expr *E, bool AddressOf) { 3249 E = E->IgnoreParens(); 3250 3251 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3252 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3253 AddressOf /*AddressOf*/); 3254 return; 3255 } 3256 3257 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3258 Visit(CO->getCond()); 3259 HandleValue(CO->getTrueExpr(), AddressOf); 3260 HandleValue(CO->getFalseExpr(), AddressOf); 3261 return; 3262 } 3263 3264 if (BinaryConditionalOperator *BCO = 3265 dyn_cast<BinaryConditionalOperator>(E)) { 3266 Visit(BCO->getCond()); 3267 HandleValue(BCO->getFalseExpr(), AddressOf); 3268 return; 3269 } 3270 3271 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3272 HandleValue(OVE->getSourceExpr(), AddressOf); 3273 return; 3274 } 3275 3276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3277 switch (BO->getOpcode()) { 3278 default: 3279 break; 3280 case(BO_PtrMemD): 3281 case(BO_PtrMemI): 3282 HandleValue(BO->getLHS(), AddressOf); 3283 Visit(BO->getRHS()); 3284 return; 3285 case(BO_Comma): 3286 Visit(BO->getLHS()); 3287 HandleValue(BO->getRHS(), AddressOf); 3288 return; 3289 } 3290 } 3291 3292 Visit(E); 3293 } 3294 3295 void CheckInitListExpr(InitListExpr *ILE) { 3296 InitFieldIndex.push_back(0); 3297 for (auto Child : ILE->children()) { 3298 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3299 CheckInitListExpr(SubList); 3300 } else { 3301 Visit(Child); 3302 } 3303 ++InitFieldIndex.back(); 3304 } 3305 InitFieldIndex.pop_back(); 3306 } 3307 3308 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3309 FieldDecl *Field, const Type *BaseClass) { 3310 // Remove Decls that may have been initialized in the previous 3311 // initializer. 3312 for (ValueDecl* VD : DeclsToRemove) 3313 Decls.erase(VD); 3314 DeclsToRemove.clear(); 3315 3316 Constructor = FieldConstructor; 3317 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3318 3319 if (ILE && Field) { 3320 InitList = true; 3321 InitListFieldDecl = Field; 3322 InitFieldIndex.clear(); 3323 CheckInitListExpr(ILE); 3324 } else { 3325 InitList = false; 3326 Visit(E); 3327 } 3328 3329 if (Field) 3330 Decls.erase(Field); 3331 if (BaseClass) 3332 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3333 } 3334 3335 void VisitMemberExpr(MemberExpr *ME) { 3336 // All uses of unbounded reference fields will warn. 3337 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3338 } 3339 3340 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3341 if (E->getCastKind() == CK_LValueToRValue) { 3342 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3343 return; 3344 } 3345 3346 Inherited::VisitImplicitCastExpr(E); 3347 } 3348 3349 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3350 if (E->getConstructor()->isCopyConstructor()) { 3351 Expr *ArgExpr = E->getArg(0); 3352 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3353 if (ILE->getNumInits() == 1) 3354 ArgExpr = ILE->getInit(0); 3355 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3356 if (ICE->getCastKind() == CK_NoOp) 3357 ArgExpr = ICE->getSubExpr(); 3358 HandleValue(ArgExpr, false /*AddressOf*/); 3359 return; 3360 } 3361 Inherited::VisitCXXConstructExpr(E); 3362 } 3363 3364 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3365 Expr *Callee = E->getCallee(); 3366 if (isa<MemberExpr>(Callee)) { 3367 HandleValue(Callee, false /*AddressOf*/); 3368 for (auto Arg : E->arguments()) 3369 Visit(Arg); 3370 return; 3371 } 3372 3373 Inherited::VisitCXXMemberCallExpr(E); 3374 } 3375 3376 void VisitCallExpr(CallExpr *E) { 3377 // Treat std::move as a use. 3378 if (E->getNumArgs() == 1) { 3379 if (FunctionDecl *FD = E->getDirectCallee()) { 3380 if (FD->isInStdNamespace() && FD->getIdentifier() && 3381 FD->getIdentifier()->isStr("move")) { 3382 HandleValue(E->getArg(0), false /*AddressOf*/); 3383 return; 3384 } 3385 } 3386 } 3387 3388 Inherited::VisitCallExpr(E); 3389 } 3390 3391 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3392 Expr *Callee = E->getCallee(); 3393 3394 if (isa<UnresolvedLookupExpr>(Callee)) 3395 return Inherited::VisitCXXOperatorCallExpr(E); 3396 3397 Visit(Callee); 3398 for (auto Arg : E->arguments()) 3399 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3400 } 3401 3402 void VisitBinaryOperator(BinaryOperator *E) { 3403 // If a field assignment is detected, remove the field from the 3404 // uninitiailized field set. 3405 if (E->getOpcode() == BO_Assign) 3406 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3407 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3408 if (!FD->getType()->isReferenceType()) 3409 DeclsToRemove.push_back(FD); 3410 3411 if (E->isCompoundAssignmentOp()) { 3412 HandleValue(E->getLHS(), false /*AddressOf*/); 3413 Visit(E->getRHS()); 3414 return; 3415 } 3416 3417 Inherited::VisitBinaryOperator(E); 3418 } 3419 3420 void VisitUnaryOperator(UnaryOperator *E) { 3421 if (E->isIncrementDecrementOp()) { 3422 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3423 return; 3424 } 3425 if (E->getOpcode() == UO_AddrOf) { 3426 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3427 HandleValue(ME->getBase(), true /*AddressOf*/); 3428 return; 3429 } 3430 } 3431 3432 Inherited::VisitUnaryOperator(E); 3433 } 3434 }; 3435 3436 // Diagnose value-uses of fields to initialize themselves, e.g. 3437 // foo(foo) 3438 // where foo is not also a parameter to the constructor. 3439 // Also diagnose across field uninitialized use such as 3440 // x(y), y(x) 3441 // TODO: implement -Wuninitialized and fold this into that framework. 3442 static void DiagnoseUninitializedFields( 3443 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3444 3445 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3446 Constructor->getLocation())) { 3447 return; 3448 } 3449 3450 if (Constructor->isInvalidDecl()) 3451 return; 3452 3453 const CXXRecordDecl *RD = Constructor->getParent(); 3454 3455 if (RD->getDescribedClassTemplate()) 3456 return; 3457 3458 // Holds fields that are uninitialized. 3459 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3460 3461 // At the beginning, all fields are uninitialized. 3462 for (auto *I : RD->decls()) { 3463 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3464 UninitializedFields.insert(FD); 3465 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3466 UninitializedFields.insert(IFD->getAnonField()); 3467 } 3468 } 3469 3470 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3471 for (auto I : RD->bases()) 3472 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3473 3474 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3475 return; 3476 3477 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3478 UninitializedFields, 3479 UninitializedBaseClasses); 3480 3481 for (const auto *FieldInit : Constructor->inits()) { 3482 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3483 break; 3484 3485 Expr *InitExpr = FieldInit->getInit(); 3486 if (!InitExpr) 3487 continue; 3488 3489 if (CXXDefaultInitExpr *Default = 3490 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3491 InitExpr = Default->getExpr(); 3492 if (!InitExpr) 3493 continue; 3494 // In class initializers will point to the constructor. 3495 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3496 FieldInit->getAnyMember(), 3497 FieldInit->getBaseClass()); 3498 } else { 3499 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3500 FieldInit->getAnyMember(), 3501 FieldInit->getBaseClass()); 3502 } 3503 } 3504 } 3505 } // namespace 3506 3507 /// \brief Enter a new C++ default initializer scope. After calling this, the 3508 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3509 /// parsing or instantiating the initializer failed. 3510 void Sema::ActOnStartCXXInClassMemberInitializer() { 3511 // Create a synthetic function scope to represent the call to the constructor 3512 // that notionally surrounds a use of this initializer. 3513 PushFunctionScope(); 3514 } 3515 3516 /// \brief This is invoked after parsing an in-class initializer for a 3517 /// non-static C++ class member, and after instantiating an in-class initializer 3518 /// in a class template. Such actions are deferred until the class is complete. 3519 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3520 SourceLocation InitLoc, 3521 Expr *InitExpr) { 3522 // Pop the notional constructor scope we created earlier. 3523 PopFunctionScopeInfo(nullptr, D); 3524 3525 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3526 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3527 "must set init style when field is created"); 3528 3529 if (!InitExpr) { 3530 D->setInvalidDecl(); 3531 if (FD) 3532 FD->removeInClassInitializer(); 3533 return; 3534 } 3535 3536 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3537 FD->setInvalidDecl(); 3538 FD->removeInClassInitializer(); 3539 return; 3540 } 3541 3542 ExprResult Init = InitExpr; 3543 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3544 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3545 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 3546 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 3547 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3548 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3549 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3550 if (Init.isInvalid()) { 3551 FD->setInvalidDecl(); 3552 return; 3553 } 3554 } 3555 3556 // C++11 [class.base.init]p7: 3557 // The initialization of each base and member constitutes a 3558 // full-expression. 3559 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3560 if (Init.isInvalid()) { 3561 FD->setInvalidDecl(); 3562 return; 3563 } 3564 3565 InitExpr = Init.get(); 3566 3567 FD->setInClassInitializer(InitExpr); 3568 } 3569 3570 /// \brief Find the direct and/or virtual base specifiers that 3571 /// correspond to the given base type, for use in base initialization 3572 /// within a constructor. 3573 static bool FindBaseInitializer(Sema &SemaRef, 3574 CXXRecordDecl *ClassDecl, 3575 QualType BaseType, 3576 const CXXBaseSpecifier *&DirectBaseSpec, 3577 const CXXBaseSpecifier *&VirtualBaseSpec) { 3578 // First, check for a direct base class. 3579 DirectBaseSpec = nullptr; 3580 for (const auto &Base : ClassDecl->bases()) { 3581 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3582 // We found a direct base of this type. That's what we're 3583 // initializing. 3584 DirectBaseSpec = &Base; 3585 break; 3586 } 3587 } 3588 3589 // Check for a virtual base class. 3590 // FIXME: We might be able to short-circuit this if we know in advance that 3591 // there are no virtual bases. 3592 VirtualBaseSpec = nullptr; 3593 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3594 // We haven't found a base yet; search the class hierarchy for a 3595 // virtual base class. 3596 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3597 /*DetectVirtual=*/false); 3598 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3599 SemaRef.Context.getTypeDeclType(ClassDecl), 3600 BaseType, Paths)) { 3601 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3602 Path != Paths.end(); ++Path) { 3603 if (Path->back().Base->isVirtual()) { 3604 VirtualBaseSpec = Path->back().Base; 3605 break; 3606 } 3607 } 3608 } 3609 } 3610 3611 return DirectBaseSpec || VirtualBaseSpec; 3612 } 3613 3614 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3615 MemInitResult 3616 Sema::ActOnMemInitializer(Decl *ConstructorD, 3617 Scope *S, 3618 CXXScopeSpec &SS, 3619 IdentifierInfo *MemberOrBase, 3620 ParsedType TemplateTypeTy, 3621 const DeclSpec &DS, 3622 SourceLocation IdLoc, 3623 Expr *InitList, 3624 SourceLocation EllipsisLoc) { 3625 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3626 DS, IdLoc, InitList, 3627 EllipsisLoc); 3628 } 3629 3630 /// \brief Handle a C++ member initializer using parentheses syntax. 3631 MemInitResult 3632 Sema::ActOnMemInitializer(Decl *ConstructorD, 3633 Scope *S, 3634 CXXScopeSpec &SS, 3635 IdentifierInfo *MemberOrBase, 3636 ParsedType TemplateTypeTy, 3637 const DeclSpec &DS, 3638 SourceLocation IdLoc, 3639 SourceLocation LParenLoc, 3640 ArrayRef<Expr *> Args, 3641 SourceLocation RParenLoc, 3642 SourceLocation EllipsisLoc) { 3643 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3644 Args, RParenLoc); 3645 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3646 DS, IdLoc, List, EllipsisLoc); 3647 } 3648 3649 namespace { 3650 3651 // Callback to only accept typo corrections that can be a valid C++ member 3652 // intializer: either a non-static field member or a base class. 3653 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3654 public: 3655 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3656 : ClassDecl(ClassDecl) {} 3657 3658 bool ValidateCandidate(const TypoCorrection &candidate) override { 3659 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3660 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3661 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3662 return isa<TypeDecl>(ND); 3663 } 3664 return false; 3665 } 3666 3667 private: 3668 CXXRecordDecl *ClassDecl; 3669 }; 3670 3671 } 3672 3673 /// \brief Handle a C++ member initializer. 3674 MemInitResult 3675 Sema::BuildMemInitializer(Decl *ConstructorD, 3676 Scope *S, 3677 CXXScopeSpec &SS, 3678 IdentifierInfo *MemberOrBase, 3679 ParsedType TemplateTypeTy, 3680 const DeclSpec &DS, 3681 SourceLocation IdLoc, 3682 Expr *Init, 3683 SourceLocation EllipsisLoc) { 3684 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3685 if (!Res.isUsable()) 3686 return true; 3687 Init = Res.get(); 3688 3689 if (!ConstructorD) 3690 return true; 3691 3692 AdjustDeclIfTemplate(ConstructorD); 3693 3694 CXXConstructorDecl *Constructor 3695 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3696 if (!Constructor) { 3697 // The user wrote a constructor initializer on a function that is 3698 // not a C++ constructor. Ignore the error for now, because we may 3699 // have more member initializers coming; we'll diagnose it just 3700 // once in ActOnMemInitializers. 3701 return true; 3702 } 3703 3704 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3705 3706 // C++ [class.base.init]p2: 3707 // Names in a mem-initializer-id are looked up in the scope of the 3708 // constructor's class and, if not found in that scope, are looked 3709 // up in the scope containing the constructor's definition. 3710 // [Note: if the constructor's class contains a member with the 3711 // same name as a direct or virtual base class of the class, a 3712 // mem-initializer-id naming the member or base class and composed 3713 // of a single identifier refers to the class member. A 3714 // mem-initializer-id for the hidden base class may be specified 3715 // using a qualified name. ] 3716 if (!SS.getScopeRep() && !TemplateTypeTy) { 3717 // Look for a member, first. 3718 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3719 if (!Result.empty()) { 3720 ValueDecl *Member; 3721 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3722 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3723 if (EllipsisLoc.isValid()) 3724 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3725 << MemberOrBase 3726 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3727 3728 return BuildMemberInitializer(Member, Init, IdLoc); 3729 } 3730 } 3731 } 3732 // It didn't name a member, so see if it names a class. 3733 QualType BaseType; 3734 TypeSourceInfo *TInfo = nullptr; 3735 3736 if (TemplateTypeTy) { 3737 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3738 } else if (DS.getTypeSpecType() == TST_decltype) { 3739 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3740 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3741 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3742 return true; 3743 } else { 3744 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3745 LookupParsedName(R, S, &SS); 3746 3747 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3748 if (!TyD) { 3749 if (R.isAmbiguous()) return true; 3750 3751 // We don't want access-control diagnostics here. 3752 R.suppressDiagnostics(); 3753 3754 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3755 bool NotUnknownSpecialization = false; 3756 DeclContext *DC = computeDeclContext(SS, false); 3757 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3758 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3759 3760 if (!NotUnknownSpecialization) { 3761 // When the scope specifier can refer to a member of an unknown 3762 // specialization, we take it as a type name. 3763 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3764 SS.getWithLocInContext(Context), 3765 *MemberOrBase, IdLoc); 3766 if (BaseType.isNull()) 3767 return true; 3768 3769 R.clear(); 3770 R.setLookupName(MemberOrBase); 3771 } 3772 } 3773 3774 // If no results were found, try to correct typos. 3775 TypoCorrection Corr; 3776 if (R.empty() && BaseType.isNull() && 3777 (Corr = CorrectTypo( 3778 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3779 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3780 CTK_ErrorRecovery, ClassDecl))) { 3781 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3782 // We have found a non-static data member with a similar 3783 // name to what was typed; complain and initialize that 3784 // member. 3785 diagnoseTypo(Corr, 3786 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3787 << MemberOrBase << true); 3788 return BuildMemberInitializer(Member, Init, IdLoc); 3789 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3790 const CXXBaseSpecifier *DirectBaseSpec; 3791 const CXXBaseSpecifier *VirtualBaseSpec; 3792 if (FindBaseInitializer(*this, ClassDecl, 3793 Context.getTypeDeclType(Type), 3794 DirectBaseSpec, VirtualBaseSpec)) { 3795 // We have found a direct or virtual base class with a 3796 // similar name to what was typed; complain and initialize 3797 // that base class. 3798 diagnoseTypo(Corr, 3799 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3800 << MemberOrBase << false, 3801 PDiag() /*Suppress note, we provide our own.*/); 3802 3803 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3804 : VirtualBaseSpec; 3805 Diag(BaseSpec->getLocStart(), 3806 diag::note_base_class_specified_here) 3807 << BaseSpec->getType() 3808 << BaseSpec->getSourceRange(); 3809 3810 TyD = Type; 3811 } 3812 } 3813 } 3814 3815 if (!TyD && BaseType.isNull()) { 3816 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3817 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3818 return true; 3819 } 3820 } 3821 3822 if (BaseType.isNull()) { 3823 BaseType = Context.getTypeDeclType(TyD); 3824 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3825 if (SS.isSet()) { 3826 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3827 BaseType); 3828 TInfo = Context.CreateTypeSourceInfo(BaseType); 3829 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3830 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3831 TL.setElaboratedKeywordLoc(SourceLocation()); 3832 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3833 } 3834 } 3835 } 3836 3837 if (!TInfo) 3838 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3839 3840 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3841 } 3842 3843 /// Checks a member initializer expression for cases where reference (or 3844 /// pointer) members are bound to by-value parameters (or their addresses). 3845 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3846 Expr *Init, 3847 SourceLocation IdLoc) { 3848 QualType MemberTy = Member->getType(); 3849 3850 // We only handle pointers and references currently. 3851 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3852 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3853 return; 3854 3855 const bool IsPointer = MemberTy->isPointerType(); 3856 if (IsPointer) { 3857 if (const UnaryOperator *Op 3858 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3859 // The only case we're worried about with pointers requires taking the 3860 // address. 3861 if (Op->getOpcode() != UO_AddrOf) 3862 return; 3863 3864 Init = Op->getSubExpr(); 3865 } else { 3866 // We only handle address-of expression initializers for pointers. 3867 return; 3868 } 3869 } 3870 3871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3872 // We only warn when referring to a non-reference parameter declaration. 3873 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3874 if (!Parameter || Parameter->getType()->isReferenceType()) 3875 return; 3876 3877 S.Diag(Init->getExprLoc(), 3878 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3879 : diag::warn_bind_ref_member_to_parameter) 3880 << Member << Parameter << Init->getSourceRange(); 3881 } else { 3882 // Other initializers are fine. 3883 return; 3884 } 3885 3886 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3887 << (unsigned)IsPointer; 3888 } 3889 3890 MemInitResult 3891 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3892 SourceLocation IdLoc) { 3893 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3894 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3895 assert((DirectMember || IndirectMember) && 3896 "Member must be a FieldDecl or IndirectFieldDecl"); 3897 3898 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3899 return true; 3900 3901 if (Member->isInvalidDecl()) 3902 return true; 3903 3904 MultiExprArg Args; 3905 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3906 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3907 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3908 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3909 } else { 3910 // Template instantiation doesn't reconstruct ParenListExprs for us. 3911 Args = Init; 3912 } 3913 3914 SourceRange InitRange = Init->getSourceRange(); 3915 3916 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3917 // Can't check initialization for a member of dependent type or when 3918 // any of the arguments are type-dependent expressions. 3919 DiscardCleanupsInEvaluationContext(); 3920 } else { 3921 bool InitList = false; 3922 if (isa<InitListExpr>(Init)) { 3923 InitList = true; 3924 Args = Init; 3925 } 3926 3927 // Initialize the member. 3928 InitializedEntity MemberEntity = 3929 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3930 : InitializedEntity::InitializeMember(IndirectMember, 3931 nullptr); 3932 InitializationKind Kind = 3933 InitList ? InitializationKind::CreateDirectList(IdLoc) 3934 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3935 InitRange.getEnd()); 3936 3937 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3938 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3939 nullptr); 3940 if (MemberInit.isInvalid()) 3941 return true; 3942 3943 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3944 3945 // C++11 [class.base.init]p7: 3946 // The initialization of each base and member constitutes a 3947 // full-expression. 3948 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3949 if (MemberInit.isInvalid()) 3950 return true; 3951 3952 Init = MemberInit.get(); 3953 } 3954 3955 if (DirectMember) { 3956 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3957 InitRange.getBegin(), Init, 3958 InitRange.getEnd()); 3959 } else { 3960 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3961 InitRange.getBegin(), Init, 3962 InitRange.getEnd()); 3963 } 3964 } 3965 3966 MemInitResult 3967 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3968 CXXRecordDecl *ClassDecl) { 3969 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3970 if (!LangOpts.CPlusPlus11) 3971 return Diag(NameLoc, diag::err_delegating_ctor) 3972 << TInfo->getTypeLoc().getLocalSourceRange(); 3973 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3974 3975 bool InitList = true; 3976 MultiExprArg Args = Init; 3977 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3978 InitList = false; 3979 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3980 } 3981 3982 SourceRange InitRange = Init->getSourceRange(); 3983 // Initialize the object. 3984 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3985 QualType(ClassDecl->getTypeForDecl(), 0)); 3986 InitializationKind Kind = 3987 InitList ? InitializationKind::CreateDirectList(NameLoc) 3988 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3989 InitRange.getEnd()); 3990 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3991 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3992 Args, nullptr); 3993 if (DelegationInit.isInvalid()) 3994 return true; 3995 3996 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3997 "Delegating constructor with no target?"); 3998 3999 // C++11 [class.base.init]p7: 4000 // The initialization of each base and member constitutes a 4001 // full-expression. 4002 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4003 InitRange.getBegin()); 4004 if (DelegationInit.isInvalid()) 4005 return true; 4006 4007 // If we are in a dependent context, template instantiation will 4008 // perform this type-checking again. Just save the arguments that we 4009 // received in a ParenListExpr. 4010 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4011 // of the information that we have about the base 4012 // initializer. However, deconstructing the ASTs is a dicey process, 4013 // and this approach is far more likely to get the corner cases right. 4014 if (CurContext->isDependentContext()) 4015 DelegationInit = Init; 4016 4017 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4018 DelegationInit.getAs<Expr>(), 4019 InitRange.getEnd()); 4020 } 4021 4022 MemInitResult 4023 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4024 Expr *Init, CXXRecordDecl *ClassDecl, 4025 SourceLocation EllipsisLoc) { 4026 SourceLocation BaseLoc 4027 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4028 4029 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4030 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4031 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4032 4033 // C++ [class.base.init]p2: 4034 // [...] Unless the mem-initializer-id names a nonstatic data 4035 // member of the constructor's class or a direct or virtual base 4036 // of that class, the mem-initializer is ill-formed. A 4037 // mem-initializer-list can initialize a base class using any 4038 // name that denotes that base class type. 4039 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4040 4041 SourceRange InitRange = Init->getSourceRange(); 4042 if (EllipsisLoc.isValid()) { 4043 // This is a pack expansion. 4044 if (!BaseType->containsUnexpandedParameterPack()) { 4045 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4046 << SourceRange(BaseLoc, InitRange.getEnd()); 4047 4048 EllipsisLoc = SourceLocation(); 4049 } 4050 } else { 4051 // Check for any unexpanded parameter packs. 4052 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4053 return true; 4054 4055 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4056 return true; 4057 } 4058 4059 // Check for direct and virtual base classes. 4060 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4061 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4062 if (!Dependent) { 4063 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4064 BaseType)) 4065 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4066 4067 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4068 VirtualBaseSpec); 4069 4070 // C++ [base.class.init]p2: 4071 // Unless the mem-initializer-id names a nonstatic data member of the 4072 // constructor's class or a direct or virtual base of that class, the 4073 // mem-initializer is ill-formed. 4074 if (!DirectBaseSpec && !VirtualBaseSpec) { 4075 // If the class has any dependent bases, then it's possible that 4076 // one of those types will resolve to the same type as 4077 // BaseType. Therefore, just treat this as a dependent base 4078 // class initialization. FIXME: Should we try to check the 4079 // initialization anyway? It seems odd. 4080 if (ClassDecl->hasAnyDependentBases()) 4081 Dependent = true; 4082 else 4083 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4084 << BaseType << Context.getTypeDeclType(ClassDecl) 4085 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4086 } 4087 } 4088 4089 if (Dependent) { 4090 DiscardCleanupsInEvaluationContext(); 4091 4092 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4093 /*IsVirtual=*/false, 4094 InitRange.getBegin(), Init, 4095 InitRange.getEnd(), EllipsisLoc); 4096 } 4097 4098 // C++ [base.class.init]p2: 4099 // If a mem-initializer-id is ambiguous because it designates both 4100 // a direct non-virtual base class and an inherited virtual base 4101 // class, the mem-initializer is ill-formed. 4102 if (DirectBaseSpec && VirtualBaseSpec) 4103 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4104 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4105 4106 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4107 if (!BaseSpec) 4108 BaseSpec = VirtualBaseSpec; 4109 4110 // Initialize the base. 4111 bool InitList = true; 4112 MultiExprArg Args = Init; 4113 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4114 InitList = false; 4115 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4116 } 4117 4118 InitializedEntity BaseEntity = 4119 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4120 InitializationKind Kind = 4121 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4122 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4123 InitRange.getEnd()); 4124 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4125 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4126 if (BaseInit.isInvalid()) 4127 return true; 4128 4129 // C++11 [class.base.init]p7: 4130 // The initialization of each base and member constitutes a 4131 // full-expression. 4132 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4133 if (BaseInit.isInvalid()) 4134 return true; 4135 4136 // If we are in a dependent context, template instantiation will 4137 // perform this type-checking again. Just save the arguments that we 4138 // received in a ParenListExpr. 4139 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4140 // of the information that we have about the base 4141 // initializer. However, deconstructing the ASTs is a dicey process, 4142 // and this approach is far more likely to get the corner cases right. 4143 if (CurContext->isDependentContext()) 4144 BaseInit = Init; 4145 4146 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4147 BaseSpec->isVirtual(), 4148 InitRange.getBegin(), 4149 BaseInit.getAs<Expr>(), 4150 InitRange.getEnd(), EllipsisLoc); 4151 } 4152 4153 // Create a static_cast\<T&&>(expr). 4154 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4155 if (T.isNull()) T = E->getType(); 4156 QualType TargetType = SemaRef.BuildReferenceType( 4157 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4158 SourceLocation ExprLoc = E->getLocStart(); 4159 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4160 TargetType, ExprLoc); 4161 4162 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4163 SourceRange(ExprLoc, ExprLoc), 4164 E->getSourceRange()).get(); 4165 } 4166 4167 /// ImplicitInitializerKind - How an implicit base or member initializer should 4168 /// initialize its base or member. 4169 enum ImplicitInitializerKind { 4170 IIK_Default, 4171 IIK_Copy, 4172 IIK_Move, 4173 IIK_Inherit 4174 }; 4175 4176 static bool 4177 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4178 ImplicitInitializerKind ImplicitInitKind, 4179 CXXBaseSpecifier *BaseSpec, 4180 bool IsInheritedVirtualBase, 4181 CXXCtorInitializer *&CXXBaseInit) { 4182 InitializedEntity InitEntity 4183 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4184 IsInheritedVirtualBase); 4185 4186 ExprResult BaseInit; 4187 4188 switch (ImplicitInitKind) { 4189 case IIK_Inherit: 4190 case IIK_Default: { 4191 InitializationKind InitKind 4192 = InitializationKind::CreateDefault(Constructor->getLocation()); 4193 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4194 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4195 break; 4196 } 4197 4198 case IIK_Move: 4199 case IIK_Copy: { 4200 bool Moving = ImplicitInitKind == IIK_Move; 4201 ParmVarDecl *Param = Constructor->getParamDecl(0); 4202 QualType ParamType = Param->getType().getNonReferenceType(); 4203 4204 Expr *CopyCtorArg = 4205 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4206 SourceLocation(), Param, false, 4207 Constructor->getLocation(), ParamType, 4208 VK_LValue, nullptr); 4209 4210 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4211 4212 // Cast to the base class to avoid ambiguities. 4213 QualType ArgTy = 4214 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4215 ParamType.getQualifiers()); 4216 4217 if (Moving) { 4218 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4219 } 4220 4221 CXXCastPath BasePath; 4222 BasePath.push_back(BaseSpec); 4223 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4224 CK_UncheckedDerivedToBase, 4225 Moving ? VK_XValue : VK_LValue, 4226 &BasePath).get(); 4227 4228 InitializationKind InitKind 4229 = InitializationKind::CreateDirect(Constructor->getLocation(), 4230 SourceLocation(), SourceLocation()); 4231 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4232 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4233 break; 4234 } 4235 } 4236 4237 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4238 if (BaseInit.isInvalid()) 4239 return true; 4240 4241 CXXBaseInit = 4242 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4243 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4244 SourceLocation()), 4245 BaseSpec->isVirtual(), 4246 SourceLocation(), 4247 BaseInit.getAs<Expr>(), 4248 SourceLocation(), 4249 SourceLocation()); 4250 4251 return false; 4252 } 4253 4254 static bool RefersToRValueRef(Expr *MemRef) { 4255 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4256 return Referenced->getType()->isRValueReferenceType(); 4257 } 4258 4259 static bool 4260 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4261 ImplicitInitializerKind ImplicitInitKind, 4262 FieldDecl *Field, IndirectFieldDecl *Indirect, 4263 CXXCtorInitializer *&CXXMemberInit) { 4264 if (Field->isInvalidDecl()) 4265 return true; 4266 4267 SourceLocation Loc = Constructor->getLocation(); 4268 4269 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4270 bool Moving = ImplicitInitKind == IIK_Move; 4271 ParmVarDecl *Param = Constructor->getParamDecl(0); 4272 QualType ParamType = Param->getType().getNonReferenceType(); 4273 4274 // Suppress copying zero-width bitfields. 4275 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4276 return false; 4277 4278 Expr *MemberExprBase = 4279 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4280 SourceLocation(), Param, false, 4281 Loc, ParamType, VK_LValue, nullptr); 4282 4283 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4284 4285 if (Moving) { 4286 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4287 } 4288 4289 // Build a reference to this field within the parameter. 4290 CXXScopeSpec SS; 4291 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4292 Sema::LookupMemberName); 4293 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4294 : cast<ValueDecl>(Field), AS_public); 4295 MemberLookup.resolveKind(); 4296 ExprResult CtorArg 4297 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4298 ParamType, Loc, 4299 /*IsArrow=*/false, 4300 SS, 4301 /*TemplateKWLoc=*/SourceLocation(), 4302 /*FirstQualifierInScope=*/nullptr, 4303 MemberLookup, 4304 /*TemplateArgs=*/nullptr, 4305 /*S*/nullptr); 4306 if (CtorArg.isInvalid()) 4307 return true; 4308 4309 // C++11 [class.copy]p15: 4310 // - if a member m has rvalue reference type T&&, it is direct-initialized 4311 // with static_cast<T&&>(x.m); 4312 if (RefersToRValueRef(CtorArg.get())) { 4313 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4314 } 4315 4316 InitializedEntity Entity = 4317 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4318 /*Implicit*/ true) 4319 : InitializedEntity::InitializeMember(Field, nullptr, 4320 /*Implicit*/ true); 4321 4322 // Direct-initialize to use the copy constructor. 4323 InitializationKind InitKind = 4324 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4325 4326 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4327 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4328 ExprResult MemberInit = 4329 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4330 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4331 if (MemberInit.isInvalid()) 4332 return true; 4333 4334 if (Indirect) 4335 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4336 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4337 else 4338 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4339 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4340 return false; 4341 } 4342 4343 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4344 "Unhandled implicit init kind!"); 4345 4346 QualType FieldBaseElementType = 4347 SemaRef.Context.getBaseElementType(Field->getType()); 4348 4349 if (FieldBaseElementType->isRecordType()) { 4350 InitializedEntity InitEntity = 4351 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4352 /*Implicit*/ true) 4353 : InitializedEntity::InitializeMember(Field, nullptr, 4354 /*Implicit*/ true); 4355 InitializationKind InitKind = 4356 InitializationKind::CreateDefault(Loc); 4357 4358 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4359 ExprResult MemberInit = 4360 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4361 4362 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4363 if (MemberInit.isInvalid()) 4364 return true; 4365 4366 if (Indirect) 4367 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4368 Indirect, Loc, 4369 Loc, 4370 MemberInit.get(), 4371 Loc); 4372 else 4373 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4374 Field, Loc, Loc, 4375 MemberInit.get(), 4376 Loc); 4377 return false; 4378 } 4379 4380 if (!Field->getParent()->isUnion()) { 4381 if (FieldBaseElementType->isReferenceType()) { 4382 SemaRef.Diag(Constructor->getLocation(), 4383 diag::err_uninitialized_member_in_ctor) 4384 << (int)Constructor->isImplicit() 4385 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4386 << 0 << Field->getDeclName(); 4387 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4388 return true; 4389 } 4390 4391 if (FieldBaseElementType.isConstQualified()) { 4392 SemaRef.Diag(Constructor->getLocation(), 4393 diag::err_uninitialized_member_in_ctor) 4394 << (int)Constructor->isImplicit() 4395 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4396 << 1 << Field->getDeclName(); 4397 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4398 return true; 4399 } 4400 } 4401 4402 if (SemaRef.getLangOpts().ObjCAutoRefCount && 4403 FieldBaseElementType->isObjCRetainableType() && 4404 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 4405 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 4406 // ARC: 4407 // Default-initialize Objective-C pointers to NULL. 4408 CXXMemberInit 4409 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4410 Loc, Loc, 4411 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4412 Loc); 4413 return false; 4414 } 4415 4416 // Nothing to initialize. 4417 CXXMemberInit = nullptr; 4418 return false; 4419 } 4420 4421 namespace { 4422 struct BaseAndFieldInfo { 4423 Sema &S; 4424 CXXConstructorDecl *Ctor; 4425 bool AnyErrorsInInits; 4426 ImplicitInitializerKind IIK; 4427 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4428 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4429 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4430 4431 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4432 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4433 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4434 if (Ctor->getInheritedConstructor()) 4435 IIK = IIK_Inherit; 4436 else if (Generated && Ctor->isCopyConstructor()) 4437 IIK = IIK_Copy; 4438 else if (Generated && Ctor->isMoveConstructor()) 4439 IIK = IIK_Move; 4440 else 4441 IIK = IIK_Default; 4442 } 4443 4444 bool isImplicitCopyOrMove() const { 4445 switch (IIK) { 4446 case IIK_Copy: 4447 case IIK_Move: 4448 return true; 4449 4450 case IIK_Default: 4451 case IIK_Inherit: 4452 return false; 4453 } 4454 4455 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4456 } 4457 4458 bool addFieldInitializer(CXXCtorInitializer *Init) { 4459 AllToInit.push_back(Init); 4460 4461 // Check whether this initializer makes the field "used". 4462 if (Init->getInit()->HasSideEffects(S.Context)) 4463 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4464 4465 return false; 4466 } 4467 4468 bool isInactiveUnionMember(FieldDecl *Field) { 4469 RecordDecl *Record = Field->getParent(); 4470 if (!Record->isUnion()) 4471 return false; 4472 4473 if (FieldDecl *Active = 4474 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4475 return Active != Field->getCanonicalDecl(); 4476 4477 // In an implicit copy or move constructor, ignore any in-class initializer. 4478 if (isImplicitCopyOrMove()) 4479 return true; 4480 4481 // If there's no explicit initialization, the field is active only if it 4482 // has an in-class initializer... 4483 if (Field->hasInClassInitializer()) 4484 return false; 4485 // ... or it's an anonymous struct or union whose class has an in-class 4486 // initializer. 4487 if (!Field->isAnonymousStructOrUnion()) 4488 return true; 4489 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4490 return !FieldRD->hasInClassInitializer(); 4491 } 4492 4493 /// \brief Determine whether the given field is, or is within, a union member 4494 /// that is inactive (because there was an initializer given for a different 4495 /// member of the union, or because the union was not initialized at all). 4496 bool isWithinInactiveUnionMember(FieldDecl *Field, 4497 IndirectFieldDecl *Indirect) { 4498 if (!Indirect) 4499 return isInactiveUnionMember(Field); 4500 4501 for (auto *C : Indirect->chain()) { 4502 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4503 if (Field && isInactiveUnionMember(Field)) 4504 return true; 4505 } 4506 return false; 4507 } 4508 }; 4509 } 4510 4511 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4512 /// array type. 4513 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4514 if (T->isIncompleteArrayType()) 4515 return true; 4516 4517 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4518 if (!ArrayT->getSize()) 4519 return true; 4520 4521 T = ArrayT->getElementType(); 4522 } 4523 4524 return false; 4525 } 4526 4527 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4528 FieldDecl *Field, 4529 IndirectFieldDecl *Indirect = nullptr) { 4530 if (Field->isInvalidDecl()) 4531 return false; 4532 4533 // Overwhelmingly common case: we have a direct initializer for this field. 4534 if (CXXCtorInitializer *Init = 4535 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4536 return Info.addFieldInitializer(Init); 4537 4538 // C++11 [class.base.init]p8: 4539 // if the entity is a non-static data member that has a 4540 // brace-or-equal-initializer and either 4541 // -- the constructor's class is a union and no other variant member of that 4542 // union is designated by a mem-initializer-id or 4543 // -- the constructor's class is not a union, and, if the entity is a member 4544 // of an anonymous union, no other member of that union is designated by 4545 // a mem-initializer-id, 4546 // the entity is initialized as specified in [dcl.init]. 4547 // 4548 // We also apply the same rules to handle anonymous structs within anonymous 4549 // unions. 4550 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4551 return false; 4552 4553 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4554 ExprResult DIE = 4555 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4556 if (DIE.isInvalid()) 4557 return true; 4558 CXXCtorInitializer *Init; 4559 if (Indirect) 4560 Init = new (SemaRef.Context) 4561 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4562 SourceLocation(), DIE.get(), SourceLocation()); 4563 else 4564 Init = new (SemaRef.Context) 4565 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4566 SourceLocation(), DIE.get(), SourceLocation()); 4567 return Info.addFieldInitializer(Init); 4568 } 4569 4570 // Don't initialize incomplete or zero-length arrays. 4571 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4572 return false; 4573 4574 // Don't try to build an implicit initializer if there were semantic 4575 // errors in any of the initializers (and therefore we might be 4576 // missing some that the user actually wrote). 4577 if (Info.AnyErrorsInInits) 4578 return false; 4579 4580 CXXCtorInitializer *Init = nullptr; 4581 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4582 Indirect, Init)) 4583 return true; 4584 4585 if (!Init) 4586 return false; 4587 4588 return Info.addFieldInitializer(Init); 4589 } 4590 4591 bool 4592 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4593 CXXCtorInitializer *Initializer) { 4594 assert(Initializer->isDelegatingInitializer()); 4595 Constructor->setNumCtorInitializers(1); 4596 CXXCtorInitializer **initializer = 4597 new (Context) CXXCtorInitializer*[1]; 4598 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4599 Constructor->setCtorInitializers(initializer); 4600 4601 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4602 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4603 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4604 } 4605 4606 DelegatingCtorDecls.push_back(Constructor); 4607 4608 DiagnoseUninitializedFields(*this, Constructor); 4609 4610 return false; 4611 } 4612 4613 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4614 ArrayRef<CXXCtorInitializer *> Initializers) { 4615 if (Constructor->isDependentContext()) { 4616 // Just store the initializers as written, they will be checked during 4617 // instantiation. 4618 if (!Initializers.empty()) { 4619 Constructor->setNumCtorInitializers(Initializers.size()); 4620 CXXCtorInitializer **baseOrMemberInitializers = 4621 new (Context) CXXCtorInitializer*[Initializers.size()]; 4622 memcpy(baseOrMemberInitializers, Initializers.data(), 4623 Initializers.size() * sizeof(CXXCtorInitializer*)); 4624 Constructor->setCtorInitializers(baseOrMemberInitializers); 4625 } 4626 4627 // Let template instantiation know whether we had errors. 4628 if (AnyErrors) 4629 Constructor->setInvalidDecl(); 4630 4631 return false; 4632 } 4633 4634 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4635 4636 // We need to build the initializer AST according to order of construction 4637 // and not what user specified in the Initializers list. 4638 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4639 if (!ClassDecl) 4640 return true; 4641 4642 bool HadError = false; 4643 4644 for (unsigned i = 0; i < Initializers.size(); i++) { 4645 CXXCtorInitializer *Member = Initializers[i]; 4646 4647 if (Member->isBaseInitializer()) 4648 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4649 else { 4650 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4651 4652 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4653 for (auto *C : F->chain()) { 4654 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4655 if (FD && FD->getParent()->isUnion()) 4656 Info.ActiveUnionMember.insert(std::make_pair( 4657 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4658 } 4659 } else if (FieldDecl *FD = Member->getMember()) { 4660 if (FD->getParent()->isUnion()) 4661 Info.ActiveUnionMember.insert(std::make_pair( 4662 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4663 } 4664 } 4665 } 4666 4667 // Keep track of the direct virtual bases. 4668 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4669 for (auto &I : ClassDecl->bases()) { 4670 if (I.isVirtual()) 4671 DirectVBases.insert(&I); 4672 } 4673 4674 // Push virtual bases before others. 4675 for (auto &VBase : ClassDecl->vbases()) { 4676 if (CXXCtorInitializer *Value 4677 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4678 // [class.base.init]p7, per DR257: 4679 // A mem-initializer where the mem-initializer-id names a virtual base 4680 // class is ignored during execution of a constructor of any class that 4681 // is not the most derived class. 4682 if (ClassDecl->isAbstract()) { 4683 // FIXME: Provide a fixit to remove the base specifier. This requires 4684 // tracking the location of the associated comma for a base specifier. 4685 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4686 << VBase.getType() << ClassDecl; 4687 DiagnoseAbstractType(ClassDecl); 4688 } 4689 4690 Info.AllToInit.push_back(Value); 4691 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4692 // [class.base.init]p8, per DR257: 4693 // If a given [...] base class is not named by a mem-initializer-id 4694 // [...] and the entity is not a virtual base class of an abstract 4695 // class, then [...] the entity is default-initialized. 4696 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4697 CXXCtorInitializer *CXXBaseInit; 4698 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4699 &VBase, IsInheritedVirtualBase, 4700 CXXBaseInit)) { 4701 HadError = true; 4702 continue; 4703 } 4704 4705 Info.AllToInit.push_back(CXXBaseInit); 4706 } 4707 } 4708 4709 // Non-virtual bases. 4710 for (auto &Base : ClassDecl->bases()) { 4711 // Virtuals are in the virtual base list and already constructed. 4712 if (Base.isVirtual()) 4713 continue; 4714 4715 if (CXXCtorInitializer *Value 4716 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4717 Info.AllToInit.push_back(Value); 4718 } else if (!AnyErrors) { 4719 CXXCtorInitializer *CXXBaseInit; 4720 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4721 &Base, /*IsInheritedVirtualBase=*/false, 4722 CXXBaseInit)) { 4723 HadError = true; 4724 continue; 4725 } 4726 4727 Info.AllToInit.push_back(CXXBaseInit); 4728 } 4729 } 4730 4731 // Fields. 4732 for (auto *Mem : ClassDecl->decls()) { 4733 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4734 // C++ [class.bit]p2: 4735 // A declaration for a bit-field that omits the identifier declares an 4736 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4737 // initialized. 4738 if (F->isUnnamedBitfield()) 4739 continue; 4740 4741 // If we're not generating the implicit copy/move constructor, then we'll 4742 // handle anonymous struct/union fields based on their individual 4743 // indirect fields. 4744 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4745 continue; 4746 4747 if (CollectFieldInitializer(*this, Info, F)) 4748 HadError = true; 4749 continue; 4750 } 4751 4752 // Beyond this point, we only consider default initialization. 4753 if (Info.isImplicitCopyOrMove()) 4754 continue; 4755 4756 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4757 if (F->getType()->isIncompleteArrayType()) { 4758 assert(ClassDecl->hasFlexibleArrayMember() && 4759 "Incomplete array type is not valid"); 4760 continue; 4761 } 4762 4763 // Initialize each field of an anonymous struct individually. 4764 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4765 HadError = true; 4766 4767 continue; 4768 } 4769 } 4770 4771 unsigned NumInitializers = Info.AllToInit.size(); 4772 if (NumInitializers > 0) { 4773 Constructor->setNumCtorInitializers(NumInitializers); 4774 CXXCtorInitializer **baseOrMemberInitializers = 4775 new (Context) CXXCtorInitializer*[NumInitializers]; 4776 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4777 NumInitializers * sizeof(CXXCtorInitializer*)); 4778 Constructor->setCtorInitializers(baseOrMemberInitializers); 4779 4780 // Constructors implicitly reference the base and member 4781 // destructors. 4782 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4783 Constructor->getParent()); 4784 } 4785 4786 return HadError; 4787 } 4788 4789 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4790 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4791 const RecordDecl *RD = RT->getDecl(); 4792 if (RD->isAnonymousStructOrUnion()) { 4793 for (auto *Field : RD->fields()) 4794 PopulateKeysForFields(Field, IdealInits); 4795 return; 4796 } 4797 } 4798 IdealInits.push_back(Field->getCanonicalDecl()); 4799 } 4800 4801 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4802 return Context.getCanonicalType(BaseType).getTypePtr(); 4803 } 4804 4805 static const void *GetKeyForMember(ASTContext &Context, 4806 CXXCtorInitializer *Member) { 4807 if (!Member->isAnyMemberInitializer()) 4808 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4809 4810 return Member->getAnyMember()->getCanonicalDecl(); 4811 } 4812 4813 static void DiagnoseBaseOrMemInitializerOrder( 4814 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4815 ArrayRef<CXXCtorInitializer *> Inits) { 4816 if (Constructor->getDeclContext()->isDependentContext()) 4817 return; 4818 4819 // Don't check initializers order unless the warning is enabled at the 4820 // location of at least one initializer. 4821 bool ShouldCheckOrder = false; 4822 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4823 CXXCtorInitializer *Init = Inits[InitIndex]; 4824 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4825 Init->getSourceLocation())) { 4826 ShouldCheckOrder = true; 4827 break; 4828 } 4829 } 4830 if (!ShouldCheckOrder) 4831 return; 4832 4833 // Build the list of bases and members in the order that they'll 4834 // actually be initialized. The explicit initializers should be in 4835 // this same order but may be missing things. 4836 SmallVector<const void*, 32> IdealInitKeys; 4837 4838 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4839 4840 // 1. Virtual bases. 4841 for (const auto &VBase : ClassDecl->vbases()) 4842 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4843 4844 // 2. Non-virtual bases. 4845 for (const auto &Base : ClassDecl->bases()) { 4846 if (Base.isVirtual()) 4847 continue; 4848 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4849 } 4850 4851 // 3. Direct fields. 4852 for (auto *Field : ClassDecl->fields()) { 4853 if (Field->isUnnamedBitfield()) 4854 continue; 4855 4856 PopulateKeysForFields(Field, IdealInitKeys); 4857 } 4858 4859 unsigned NumIdealInits = IdealInitKeys.size(); 4860 unsigned IdealIndex = 0; 4861 4862 CXXCtorInitializer *PrevInit = nullptr; 4863 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4864 CXXCtorInitializer *Init = Inits[InitIndex]; 4865 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4866 4867 // Scan forward to try to find this initializer in the idealized 4868 // initializers list. 4869 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4870 if (InitKey == IdealInitKeys[IdealIndex]) 4871 break; 4872 4873 // If we didn't find this initializer, it must be because we 4874 // scanned past it on a previous iteration. That can only 4875 // happen if we're out of order; emit a warning. 4876 if (IdealIndex == NumIdealInits && PrevInit) { 4877 Sema::SemaDiagnosticBuilder D = 4878 SemaRef.Diag(PrevInit->getSourceLocation(), 4879 diag::warn_initializer_out_of_order); 4880 4881 if (PrevInit->isAnyMemberInitializer()) 4882 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4883 else 4884 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4885 4886 if (Init->isAnyMemberInitializer()) 4887 D << 0 << Init->getAnyMember()->getDeclName(); 4888 else 4889 D << 1 << Init->getTypeSourceInfo()->getType(); 4890 4891 // Move back to the initializer's location in the ideal list. 4892 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4893 if (InitKey == IdealInitKeys[IdealIndex]) 4894 break; 4895 4896 assert(IdealIndex < NumIdealInits && 4897 "initializer not found in initializer list"); 4898 } 4899 4900 PrevInit = Init; 4901 } 4902 } 4903 4904 namespace { 4905 bool CheckRedundantInit(Sema &S, 4906 CXXCtorInitializer *Init, 4907 CXXCtorInitializer *&PrevInit) { 4908 if (!PrevInit) { 4909 PrevInit = Init; 4910 return false; 4911 } 4912 4913 if (FieldDecl *Field = Init->getAnyMember()) 4914 S.Diag(Init->getSourceLocation(), 4915 diag::err_multiple_mem_initialization) 4916 << Field->getDeclName() 4917 << Init->getSourceRange(); 4918 else { 4919 const Type *BaseClass = Init->getBaseClass(); 4920 assert(BaseClass && "neither field nor base"); 4921 S.Diag(Init->getSourceLocation(), 4922 diag::err_multiple_base_initialization) 4923 << QualType(BaseClass, 0) 4924 << Init->getSourceRange(); 4925 } 4926 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4927 << 0 << PrevInit->getSourceRange(); 4928 4929 return true; 4930 } 4931 4932 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4933 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4934 4935 bool CheckRedundantUnionInit(Sema &S, 4936 CXXCtorInitializer *Init, 4937 RedundantUnionMap &Unions) { 4938 FieldDecl *Field = Init->getAnyMember(); 4939 RecordDecl *Parent = Field->getParent(); 4940 NamedDecl *Child = Field; 4941 4942 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4943 if (Parent->isUnion()) { 4944 UnionEntry &En = Unions[Parent]; 4945 if (En.first && En.first != Child) { 4946 S.Diag(Init->getSourceLocation(), 4947 diag::err_multiple_mem_union_initialization) 4948 << Field->getDeclName() 4949 << Init->getSourceRange(); 4950 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4951 << 0 << En.second->getSourceRange(); 4952 return true; 4953 } 4954 if (!En.first) { 4955 En.first = Child; 4956 En.second = Init; 4957 } 4958 if (!Parent->isAnonymousStructOrUnion()) 4959 return false; 4960 } 4961 4962 Child = Parent; 4963 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4964 } 4965 4966 return false; 4967 } 4968 } 4969 4970 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4971 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4972 SourceLocation ColonLoc, 4973 ArrayRef<CXXCtorInitializer*> MemInits, 4974 bool AnyErrors) { 4975 if (!ConstructorDecl) 4976 return; 4977 4978 AdjustDeclIfTemplate(ConstructorDecl); 4979 4980 CXXConstructorDecl *Constructor 4981 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4982 4983 if (!Constructor) { 4984 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4985 return; 4986 } 4987 4988 // Mapping for the duplicate initializers check. 4989 // For member initializers, this is keyed with a FieldDecl*. 4990 // For base initializers, this is keyed with a Type*. 4991 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4992 4993 // Mapping for the inconsistent anonymous-union initializers check. 4994 RedundantUnionMap MemberUnions; 4995 4996 bool HadError = false; 4997 for (unsigned i = 0; i < MemInits.size(); i++) { 4998 CXXCtorInitializer *Init = MemInits[i]; 4999 5000 // Set the source order index. 5001 Init->setSourceOrder(i); 5002 5003 if (Init->isAnyMemberInitializer()) { 5004 const void *Key = GetKeyForMember(Context, Init); 5005 if (CheckRedundantInit(*this, Init, Members[Key]) || 5006 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5007 HadError = true; 5008 } else if (Init->isBaseInitializer()) { 5009 const void *Key = GetKeyForMember(Context, Init); 5010 if (CheckRedundantInit(*this, Init, Members[Key])) 5011 HadError = true; 5012 } else { 5013 assert(Init->isDelegatingInitializer()); 5014 // This must be the only initializer 5015 if (MemInits.size() != 1) { 5016 Diag(Init->getSourceLocation(), 5017 diag::err_delegating_initializer_alone) 5018 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5019 // We will treat this as being the only initializer. 5020 } 5021 SetDelegatingInitializer(Constructor, MemInits[i]); 5022 // Return immediately as the initializer is set. 5023 return; 5024 } 5025 } 5026 5027 if (HadError) 5028 return; 5029 5030 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5031 5032 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5033 5034 DiagnoseUninitializedFields(*this, Constructor); 5035 } 5036 5037 void 5038 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5039 CXXRecordDecl *ClassDecl) { 5040 // Ignore dependent contexts. Also ignore unions, since their members never 5041 // have destructors implicitly called. 5042 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5043 return; 5044 5045 // FIXME: all the access-control diagnostics are positioned on the 5046 // field/base declaration. That's probably good; that said, the 5047 // user might reasonably want to know why the destructor is being 5048 // emitted, and we currently don't say. 5049 5050 // Non-static data members. 5051 for (auto *Field : ClassDecl->fields()) { 5052 if (Field->isInvalidDecl()) 5053 continue; 5054 5055 // Don't destroy incomplete or zero-length arrays. 5056 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5057 continue; 5058 5059 QualType FieldType = Context.getBaseElementType(Field->getType()); 5060 5061 const RecordType* RT = FieldType->getAs<RecordType>(); 5062 if (!RT) 5063 continue; 5064 5065 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5066 if (FieldClassDecl->isInvalidDecl()) 5067 continue; 5068 if (FieldClassDecl->hasIrrelevantDestructor()) 5069 continue; 5070 // The destructor for an implicit anonymous union member is never invoked. 5071 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5072 continue; 5073 5074 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5075 assert(Dtor && "No dtor found for FieldClassDecl!"); 5076 CheckDestructorAccess(Field->getLocation(), Dtor, 5077 PDiag(diag::err_access_dtor_field) 5078 << Field->getDeclName() 5079 << FieldType); 5080 5081 MarkFunctionReferenced(Location, Dtor); 5082 DiagnoseUseOfDecl(Dtor, Location); 5083 } 5084 5085 // We only potentially invoke the destructors of potentially constructed 5086 // subobjects. 5087 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5088 5089 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5090 5091 // Bases. 5092 for (const auto &Base : ClassDecl->bases()) { 5093 // Bases are always records in a well-formed non-dependent class. 5094 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5095 5096 // Remember direct virtual bases. 5097 if (Base.isVirtual()) { 5098 if (!VisitVirtualBases) 5099 continue; 5100 DirectVirtualBases.insert(RT); 5101 } 5102 5103 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5104 // If our base class is invalid, we probably can't get its dtor anyway. 5105 if (BaseClassDecl->isInvalidDecl()) 5106 continue; 5107 if (BaseClassDecl->hasIrrelevantDestructor()) 5108 continue; 5109 5110 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5111 assert(Dtor && "No dtor found for BaseClassDecl!"); 5112 5113 // FIXME: caret should be on the start of the class name 5114 CheckDestructorAccess(Base.getLocStart(), Dtor, 5115 PDiag(diag::err_access_dtor_base) 5116 << Base.getType() 5117 << Base.getSourceRange(), 5118 Context.getTypeDeclType(ClassDecl)); 5119 5120 MarkFunctionReferenced(Location, Dtor); 5121 DiagnoseUseOfDecl(Dtor, Location); 5122 } 5123 5124 if (!VisitVirtualBases) 5125 return; 5126 5127 // Virtual bases. 5128 for (const auto &VBase : ClassDecl->vbases()) { 5129 // Bases are always records in a well-formed non-dependent class. 5130 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5131 5132 // Ignore direct virtual bases. 5133 if (DirectVirtualBases.count(RT)) 5134 continue; 5135 5136 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5137 // If our base class is invalid, we probably can't get its dtor anyway. 5138 if (BaseClassDecl->isInvalidDecl()) 5139 continue; 5140 if (BaseClassDecl->hasIrrelevantDestructor()) 5141 continue; 5142 5143 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5144 assert(Dtor && "No dtor found for BaseClassDecl!"); 5145 if (CheckDestructorAccess( 5146 ClassDecl->getLocation(), Dtor, 5147 PDiag(diag::err_access_dtor_vbase) 5148 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5149 Context.getTypeDeclType(ClassDecl)) == 5150 AR_accessible) { 5151 CheckDerivedToBaseConversion( 5152 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5153 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5154 SourceRange(), DeclarationName(), nullptr); 5155 } 5156 5157 MarkFunctionReferenced(Location, Dtor); 5158 DiagnoseUseOfDecl(Dtor, Location); 5159 } 5160 } 5161 5162 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5163 if (!CDtorDecl) 5164 return; 5165 5166 if (CXXConstructorDecl *Constructor 5167 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5168 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5169 DiagnoseUninitializedFields(*this, Constructor); 5170 } 5171 } 5172 5173 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5174 if (!getLangOpts().CPlusPlus) 5175 return false; 5176 5177 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5178 if (!RD) 5179 return false; 5180 5181 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5182 // class template specialization here, but doing so breaks a lot of code. 5183 5184 // We can't answer whether something is abstract until it has a 5185 // definition. If it's currently being defined, we'll walk back 5186 // over all the declarations when we have a full definition. 5187 const CXXRecordDecl *Def = RD->getDefinition(); 5188 if (!Def || Def->isBeingDefined()) 5189 return false; 5190 5191 return RD->isAbstract(); 5192 } 5193 5194 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5195 TypeDiagnoser &Diagnoser) { 5196 if (!isAbstractType(Loc, T)) 5197 return false; 5198 5199 T = Context.getBaseElementType(T); 5200 Diagnoser.diagnose(*this, Loc, T); 5201 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5202 return true; 5203 } 5204 5205 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5206 // Check if we've already emitted the list of pure virtual functions 5207 // for this class. 5208 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5209 return; 5210 5211 // If the diagnostic is suppressed, don't emit the notes. We're only 5212 // going to emit them once, so try to attach them to a diagnostic we're 5213 // actually going to show. 5214 if (Diags.isLastDiagnosticIgnored()) 5215 return; 5216 5217 CXXFinalOverriderMap FinalOverriders; 5218 RD->getFinalOverriders(FinalOverriders); 5219 5220 // Keep a set of seen pure methods so we won't diagnose the same method 5221 // more than once. 5222 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5223 5224 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5225 MEnd = FinalOverriders.end(); 5226 M != MEnd; 5227 ++M) { 5228 for (OverridingMethods::iterator SO = M->second.begin(), 5229 SOEnd = M->second.end(); 5230 SO != SOEnd; ++SO) { 5231 // C++ [class.abstract]p4: 5232 // A class is abstract if it contains or inherits at least one 5233 // pure virtual function for which the final overrider is pure 5234 // virtual. 5235 5236 // 5237 if (SO->second.size() != 1) 5238 continue; 5239 5240 if (!SO->second.front().Method->isPure()) 5241 continue; 5242 5243 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5244 continue; 5245 5246 Diag(SO->second.front().Method->getLocation(), 5247 diag::note_pure_virtual_function) 5248 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5249 } 5250 } 5251 5252 if (!PureVirtualClassDiagSet) 5253 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5254 PureVirtualClassDiagSet->insert(RD); 5255 } 5256 5257 namespace { 5258 struct AbstractUsageInfo { 5259 Sema &S; 5260 CXXRecordDecl *Record; 5261 CanQualType AbstractType; 5262 bool Invalid; 5263 5264 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5265 : S(S), Record(Record), 5266 AbstractType(S.Context.getCanonicalType( 5267 S.Context.getTypeDeclType(Record))), 5268 Invalid(false) {} 5269 5270 void DiagnoseAbstractType() { 5271 if (Invalid) return; 5272 S.DiagnoseAbstractType(Record); 5273 Invalid = true; 5274 } 5275 5276 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5277 }; 5278 5279 struct CheckAbstractUsage { 5280 AbstractUsageInfo &Info; 5281 const NamedDecl *Ctx; 5282 5283 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5284 : Info(Info), Ctx(Ctx) {} 5285 5286 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5287 switch (TL.getTypeLocClass()) { 5288 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5289 #define TYPELOC(CLASS, PARENT) \ 5290 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5291 #include "clang/AST/TypeLocNodes.def" 5292 } 5293 } 5294 5295 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5296 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5297 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5298 if (!TL.getParam(I)) 5299 continue; 5300 5301 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5302 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5303 } 5304 } 5305 5306 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5307 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5308 } 5309 5310 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5311 // Visit the type parameters from a permissive context. 5312 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5313 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5314 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5315 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5316 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5317 // TODO: other template argument types? 5318 } 5319 } 5320 5321 // Visit pointee types from a permissive context. 5322 #define CheckPolymorphic(Type) \ 5323 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5324 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5325 } 5326 CheckPolymorphic(PointerTypeLoc) 5327 CheckPolymorphic(ReferenceTypeLoc) 5328 CheckPolymorphic(MemberPointerTypeLoc) 5329 CheckPolymorphic(BlockPointerTypeLoc) 5330 CheckPolymorphic(AtomicTypeLoc) 5331 5332 /// Handle all the types we haven't given a more specific 5333 /// implementation for above. 5334 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5335 // Every other kind of type that we haven't called out already 5336 // that has an inner type is either (1) sugar or (2) contains that 5337 // inner type in some way as a subobject. 5338 if (TypeLoc Next = TL.getNextTypeLoc()) 5339 return Visit(Next, Sel); 5340 5341 // If there's no inner type and we're in a permissive context, 5342 // don't diagnose. 5343 if (Sel == Sema::AbstractNone) return; 5344 5345 // Check whether the type matches the abstract type. 5346 QualType T = TL.getType(); 5347 if (T->isArrayType()) { 5348 Sel = Sema::AbstractArrayType; 5349 T = Info.S.Context.getBaseElementType(T); 5350 } 5351 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5352 if (CT != Info.AbstractType) return; 5353 5354 // It matched; do some magic. 5355 if (Sel == Sema::AbstractArrayType) { 5356 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5357 << T << TL.getSourceRange(); 5358 } else { 5359 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5360 << Sel << T << TL.getSourceRange(); 5361 } 5362 Info.DiagnoseAbstractType(); 5363 } 5364 }; 5365 5366 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5367 Sema::AbstractDiagSelID Sel) { 5368 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5369 } 5370 5371 } 5372 5373 /// Check for invalid uses of an abstract type in a method declaration. 5374 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5375 CXXMethodDecl *MD) { 5376 // No need to do the check on definitions, which require that 5377 // the return/param types be complete. 5378 if (MD->doesThisDeclarationHaveABody()) 5379 return; 5380 5381 // For safety's sake, just ignore it if we don't have type source 5382 // information. This should never happen for non-implicit methods, 5383 // but... 5384 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5385 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5386 } 5387 5388 /// Check for invalid uses of an abstract type within a class definition. 5389 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5390 CXXRecordDecl *RD) { 5391 for (auto *D : RD->decls()) { 5392 if (D->isImplicit()) continue; 5393 5394 // Methods and method templates. 5395 if (isa<CXXMethodDecl>(D)) { 5396 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5397 } else if (isa<FunctionTemplateDecl>(D)) { 5398 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5399 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5400 5401 // Fields and static variables. 5402 } else if (isa<FieldDecl>(D)) { 5403 FieldDecl *FD = cast<FieldDecl>(D); 5404 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5405 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5406 } else if (isa<VarDecl>(D)) { 5407 VarDecl *VD = cast<VarDecl>(D); 5408 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5409 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5410 5411 // Nested classes and class templates. 5412 } else if (isa<CXXRecordDecl>(D)) { 5413 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5414 } else if (isa<ClassTemplateDecl>(D)) { 5415 CheckAbstractClassUsage(Info, 5416 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5417 } 5418 } 5419 } 5420 5421 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 5422 Attr *ClassAttr = getDLLAttr(Class); 5423 if (!ClassAttr) 5424 return; 5425 5426 assert(ClassAttr->getKind() == attr::DLLExport); 5427 5428 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5429 5430 if (TSK == TSK_ExplicitInstantiationDeclaration) 5431 // Don't go any further if this is just an explicit instantiation 5432 // declaration. 5433 return; 5434 5435 for (Decl *Member : Class->decls()) { 5436 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5437 if (!MD) 5438 continue; 5439 5440 if (Member->getAttr<DLLExportAttr>()) { 5441 if (MD->isUserProvided()) { 5442 // Instantiate non-default class member functions ... 5443 5444 // .. except for certain kinds of template specializations. 5445 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5446 continue; 5447 5448 S.MarkFunctionReferenced(Class->getLocation(), MD); 5449 5450 // The function will be passed to the consumer when its definition is 5451 // encountered. 5452 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5453 MD->isCopyAssignmentOperator() || 5454 MD->isMoveAssignmentOperator()) { 5455 // Synthesize and instantiate non-trivial implicit methods, explicitly 5456 // defaulted methods, and the copy and move assignment operators. The 5457 // latter are exported even if they are trivial, because the address of 5458 // an operator can be taken and should compare equal accross libraries. 5459 DiagnosticErrorTrap Trap(S.Diags); 5460 S.MarkFunctionReferenced(Class->getLocation(), MD); 5461 if (Trap.hasErrorOccurred()) { 5462 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5463 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5464 break; 5465 } 5466 5467 // There is no later point when we will see the definition of this 5468 // function, so pass it to the consumer now. 5469 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5470 } 5471 } 5472 } 5473 } 5474 5475 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5476 CXXRecordDecl *Class) { 5477 // Only the MS ABI has default constructor closures, so we don't need to do 5478 // this semantic checking anywhere else. 5479 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5480 return; 5481 5482 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5483 for (Decl *Member : Class->decls()) { 5484 // Look for exported default constructors. 5485 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5486 if (!CD || !CD->isDefaultConstructor()) 5487 continue; 5488 auto *Attr = CD->getAttr<DLLExportAttr>(); 5489 if (!Attr) 5490 continue; 5491 5492 // If the class is non-dependent, mark the default arguments as ODR-used so 5493 // that we can properly codegen the constructor closure. 5494 if (!Class->isDependentContext()) { 5495 for (ParmVarDecl *PD : CD->parameters()) { 5496 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5497 S.DiscardCleanupsInEvaluationContext(); 5498 } 5499 } 5500 5501 if (LastExportedDefaultCtor) { 5502 S.Diag(LastExportedDefaultCtor->getLocation(), 5503 diag::err_attribute_dll_ambiguous_default_ctor) 5504 << Class; 5505 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5506 << CD->getDeclName(); 5507 return; 5508 } 5509 LastExportedDefaultCtor = CD; 5510 } 5511 } 5512 5513 /// \brief Check class-level dllimport/dllexport attribute. 5514 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5515 Attr *ClassAttr = getDLLAttr(Class); 5516 5517 // MSVC inherits DLL attributes to partial class template specializations. 5518 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5519 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5520 if (Attr *TemplateAttr = 5521 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5522 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5523 A->setInherited(true); 5524 ClassAttr = A; 5525 } 5526 } 5527 } 5528 5529 if (!ClassAttr) 5530 return; 5531 5532 if (!Class->isExternallyVisible()) { 5533 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5534 << Class << ClassAttr; 5535 return; 5536 } 5537 5538 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5539 !ClassAttr->isInherited()) { 5540 // Diagnose dll attributes on members of class with dll attribute. 5541 for (Decl *Member : Class->decls()) { 5542 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5543 continue; 5544 InheritableAttr *MemberAttr = getDLLAttr(Member); 5545 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5546 continue; 5547 5548 Diag(MemberAttr->getLocation(), 5549 diag::err_attribute_dll_member_of_dll_class) 5550 << MemberAttr << ClassAttr; 5551 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5552 Member->setInvalidDecl(); 5553 } 5554 } 5555 5556 if (Class->getDescribedClassTemplate()) 5557 // Don't inherit dll attribute until the template is instantiated. 5558 return; 5559 5560 // The class is either imported or exported. 5561 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5562 5563 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5564 5565 // Ignore explicit dllexport on explicit class template instantiation declarations. 5566 if (ClassExported && !ClassAttr->isInherited() && 5567 TSK == TSK_ExplicitInstantiationDeclaration) { 5568 Class->dropAttr<DLLExportAttr>(); 5569 return; 5570 } 5571 5572 // Force declaration of implicit members so they can inherit the attribute. 5573 ForceDeclarationOfImplicitMembers(Class); 5574 5575 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5576 // seem to be true in practice? 5577 5578 for (Decl *Member : Class->decls()) { 5579 VarDecl *VD = dyn_cast<VarDecl>(Member); 5580 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5581 5582 // Only methods and static fields inherit the attributes. 5583 if (!VD && !MD) 5584 continue; 5585 5586 if (MD) { 5587 // Don't process deleted methods. 5588 if (MD->isDeleted()) 5589 continue; 5590 5591 if (MD->isInlined()) { 5592 // MinGW does not import or export inline methods. 5593 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5594 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5595 continue; 5596 5597 // MSVC versions before 2015 don't export the move assignment operators 5598 // and move constructor, so don't attempt to import/export them if 5599 // we have a definition. 5600 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5601 if ((MD->isMoveAssignmentOperator() || 5602 (Ctor && Ctor->isMoveConstructor())) && 5603 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5604 continue; 5605 5606 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5607 // operator is exported anyway. 5608 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5609 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5610 continue; 5611 } 5612 } 5613 5614 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5615 continue; 5616 5617 if (!getDLLAttr(Member)) { 5618 auto *NewAttr = 5619 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5620 NewAttr->setInherited(true); 5621 Member->addAttr(NewAttr); 5622 } 5623 } 5624 5625 if (ClassExported) 5626 DelayedDllExportClasses.push_back(Class); 5627 } 5628 5629 /// \brief Perform propagation of DLL attributes from a derived class to a 5630 /// templated base class for MS compatibility. 5631 void Sema::propagateDLLAttrToBaseClassTemplate( 5632 CXXRecordDecl *Class, Attr *ClassAttr, 5633 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5634 if (getDLLAttr( 5635 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5636 // If the base class template has a DLL attribute, don't try to change it. 5637 return; 5638 } 5639 5640 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5641 if (!getDLLAttr(BaseTemplateSpec) && 5642 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5643 TSK == TSK_ImplicitInstantiation)) { 5644 // The template hasn't been instantiated yet (or it has, but only as an 5645 // explicit instantiation declaration or implicit instantiation, which means 5646 // we haven't codegenned any members yet), so propagate the attribute. 5647 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5648 NewAttr->setInherited(true); 5649 BaseTemplateSpec->addAttr(NewAttr); 5650 5651 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5652 // needs to be run again to work see the new attribute. Otherwise this will 5653 // get run whenever the template is instantiated. 5654 if (TSK != TSK_Undeclared) 5655 checkClassLevelDLLAttribute(BaseTemplateSpec); 5656 5657 return; 5658 } 5659 5660 if (getDLLAttr(BaseTemplateSpec)) { 5661 // The template has already been specialized or instantiated with an 5662 // attribute, explicitly or through propagation. We should not try to change 5663 // it. 5664 return; 5665 } 5666 5667 // The template was previously instantiated or explicitly specialized without 5668 // a dll attribute, It's too late for us to add an attribute, so warn that 5669 // this is unsupported. 5670 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5671 << BaseTemplateSpec->isExplicitSpecialization(); 5672 Diag(ClassAttr->getLocation(), diag::note_attribute); 5673 if (BaseTemplateSpec->isExplicitSpecialization()) { 5674 Diag(BaseTemplateSpec->getLocation(), 5675 diag::note_template_class_explicit_specialization_was_here) 5676 << BaseTemplateSpec; 5677 } else { 5678 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5679 diag::note_template_class_instantiation_was_here) 5680 << BaseTemplateSpec; 5681 } 5682 } 5683 5684 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5685 SourceLocation DefaultLoc) { 5686 switch (S.getSpecialMember(MD)) { 5687 case Sema::CXXDefaultConstructor: 5688 S.DefineImplicitDefaultConstructor(DefaultLoc, 5689 cast<CXXConstructorDecl>(MD)); 5690 break; 5691 case Sema::CXXCopyConstructor: 5692 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5693 break; 5694 case Sema::CXXCopyAssignment: 5695 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5696 break; 5697 case Sema::CXXDestructor: 5698 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5699 break; 5700 case Sema::CXXMoveConstructor: 5701 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5702 break; 5703 case Sema::CXXMoveAssignment: 5704 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5705 break; 5706 case Sema::CXXInvalid: 5707 llvm_unreachable("Invalid special member."); 5708 } 5709 } 5710 5711 /// \brief Perform semantic checks on a class definition that has been 5712 /// completing, introducing implicitly-declared members, checking for 5713 /// abstract types, etc. 5714 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5715 if (!Record) 5716 return; 5717 5718 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5719 AbstractUsageInfo Info(*this, Record); 5720 CheckAbstractClassUsage(Info, Record); 5721 } 5722 5723 // If this is not an aggregate type and has no user-declared constructor, 5724 // complain about any non-static data members of reference or const scalar 5725 // type, since they will never get initializers. 5726 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5727 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5728 !Record->isLambda()) { 5729 bool Complained = false; 5730 for (const auto *F : Record->fields()) { 5731 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5732 continue; 5733 5734 if (F->getType()->isReferenceType() || 5735 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5736 if (!Complained) { 5737 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5738 << Record->getTagKind() << Record; 5739 Complained = true; 5740 } 5741 5742 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5743 << F->getType()->isReferenceType() 5744 << F->getDeclName(); 5745 } 5746 } 5747 } 5748 5749 if (Record->getIdentifier()) { 5750 // C++ [class.mem]p13: 5751 // If T is the name of a class, then each of the following shall have a 5752 // name different from T: 5753 // - every member of every anonymous union that is a member of class T. 5754 // 5755 // C++ [class.mem]p14: 5756 // In addition, if class T has a user-declared constructor (12.1), every 5757 // non-static data member of class T shall have a name different from T. 5758 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5759 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5760 ++I) { 5761 NamedDecl *D = *I; 5762 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5763 isa<IndirectFieldDecl>(D)) { 5764 Diag(D->getLocation(), diag::err_member_name_of_class) 5765 << D->getDeclName(); 5766 break; 5767 } 5768 } 5769 } 5770 5771 // Warn if the class has virtual methods but non-virtual public destructor. 5772 if (Record->isPolymorphic() && !Record->isDependentType()) { 5773 CXXDestructorDecl *dtor = Record->getDestructor(); 5774 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5775 !Record->hasAttr<FinalAttr>()) 5776 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5777 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5778 } 5779 5780 if (Record->isAbstract()) { 5781 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5782 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5783 << FA->isSpelledAsSealed(); 5784 DiagnoseAbstractType(Record); 5785 } 5786 } 5787 5788 bool HasMethodWithOverrideControl = false, 5789 HasOverridingMethodWithoutOverrideControl = false; 5790 if (!Record->isDependentType()) { 5791 for (auto *M : Record->methods()) { 5792 // See if a method overloads virtual methods in a base 5793 // class without overriding any. 5794 if (!M->isStatic()) 5795 DiagnoseHiddenVirtualMethods(M); 5796 if (M->hasAttr<OverrideAttr>()) 5797 HasMethodWithOverrideControl = true; 5798 else if (M->size_overridden_methods() > 0) 5799 HasOverridingMethodWithoutOverrideControl = true; 5800 // Check whether the explicitly-defaulted special members are valid. 5801 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5802 CheckExplicitlyDefaultedSpecialMember(M); 5803 5804 // For an explicitly defaulted or deleted special member, we defer 5805 // determining triviality until the class is complete. That time is now! 5806 CXXSpecialMember CSM = getSpecialMember(M); 5807 if (!M->isImplicit() && !M->isUserProvided()) { 5808 if (CSM != CXXInvalid) { 5809 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5810 5811 // Inform the class that we've finished declaring this member. 5812 Record->finishedDefaultedOrDeletedMember(M); 5813 } 5814 } 5815 5816 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5817 M->hasAttr<DLLExportAttr>()) { 5818 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5819 M->isTrivial() && 5820 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5821 CSM == CXXDestructor)) 5822 M->dropAttr<DLLExportAttr>(); 5823 5824 if (M->hasAttr<DLLExportAttr>()) { 5825 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5826 ActOnFinishInlineFunctionDef(M); 5827 } 5828 } 5829 } 5830 } 5831 5832 if (HasMethodWithOverrideControl && 5833 HasOverridingMethodWithoutOverrideControl) { 5834 // At least one method has the 'override' control declared. 5835 // Diagnose all other overridden methods which do not have 'override' specified on them. 5836 for (auto *M : Record->methods()) 5837 DiagnoseAbsenceOfOverrideControl(M); 5838 } 5839 5840 // ms_struct is a request to use the same ABI rules as MSVC. Check 5841 // whether this class uses any C++ features that are implemented 5842 // completely differently in MSVC, and if so, emit a diagnostic. 5843 // That diagnostic defaults to an error, but we allow projects to 5844 // map it down to a warning (or ignore it). It's a fairly common 5845 // practice among users of the ms_struct pragma to mass-annotate 5846 // headers, sweeping up a bunch of types that the project doesn't 5847 // really rely on MSVC-compatible layout for. We must therefore 5848 // support "ms_struct except for C++ stuff" as a secondary ABI. 5849 if (Record->isMsStruct(Context) && 5850 (Record->isPolymorphic() || Record->getNumBases())) { 5851 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5852 } 5853 5854 checkClassLevelDLLAttribute(Record); 5855 } 5856 5857 /// Look up the special member function that would be called by a special 5858 /// member function for a subobject of class type. 5859 /// 5860 /// \param Class The class type of the subobject. 5861 /// \param CSM The kind of special member function. 5862 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5863 /// \param ConstRHS True if this is a copy operation with a const object 5864 /// on its RHS, that is, if the argument to the outer special member 5865 /// function is 'const' and this is not a field marked 'mutable'. 5866 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 5867 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5868 unsigned FieldQuals, bool ConstRHS) { 5869 unsigned LHSQuals = 0; 5870 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5871 LHSQuals = FieldQuals; 5872 5873 unsigned RHSQuals = FieldQuals; 5874 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5875 RHSQuals = 0; 5876 else if (ConstRHS) 5877 RHSQuals |= Qualifiers::Const; 5878 5879 return S.LookupSpecialMember(Class, CSM, 5880 RHSQuals & Qualifiers::Const, 5881 RHSQuals & Qualifiers::Volatile, 5882 false, 5883 LHSQuals & Qualifiers::Const, 5884 LHSQuals & Qualifiers::Volatile); 5885 } 5886 5887 class Sema::InheritedConstructorInfo { 5888 Sema &S; 5889 SourceLocation UseLoc; 5890 5891 /// A mapping from the base classes through which the constructor was 5892 /// inherited to the using shadow declaration in that base class (or a null 5893 /// pointer if the constructor was declared in that base class). 5894 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 5895 InheritedFromBases; 5896 5897 public: 5898 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 5899 ConstructorUsingShadowDecl *Shadow) 5900 : S(S), UseLoc(UseLoc) { 5901 bool DiagnosedMultipleConstructedBases = false; 5902 CXXRecordDecl *ConstructedBase = nullptr; 5903 UsingDecl *ConstructedBaseUsing = nullptr; 5904 5905 // Find the set of such base class subobjects and check that there's a 5906 // unique constructed subobject. 5907 for (auto *D : Shadow->redecls()) { 5908 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 5909 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 5910 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 5911 5912 InheritedFromBases.insert( 5913 std::make_pair(DNominatedBase->getCanonicalDecl(), 5914 DShadow->getNominatedBaseClassShadowDecl())); 5915 if (DShadow->constructsVirtualBase()) 5916 InheritedFromBases.insert( 5917 std::make_pair(DConstructedBase->getCanonicalDecl(), 5918 DShadow->getConstructedBaseClassShadowDecl())); 5919 else 5920 assert(DNominatedBase == DConstructedBase); 5921 5922 // [class.inhctor.init]p2: 5923 // If the constructor was inherited from multiple base class subobjects 5924 // of type B, the program is ill-formed. 5925 if (!ConstructedBase) { 5926 ConstructedBase = DConstructedBase; 5927 ConstructedBaseUsing = D->getUsingDecl(); 5928 } else if (ConstructedBase != DConstructedBase && 5929 !Shadow->isInvalidDecl()) { 5930 if (!DiagnosedMultipleConstructedBases) { 5931 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 5932 << Shadow->getTargetDecl(); 5933 S.Diag(ConstructedBaseUsing->getLocation(), 5934 diag::note_ambiguous_inherited_constructor_using) 5935 << ConstructedBase; 5936 DiagnosedMultipleConstructedBases = true; 5937 } 5938 S.Diag(D->getUsingDecl()->getLocation(), 5939 diag::note_ambiguous_inherited_constructor_using) 5940 << DConstructedBase; 5941 } 5942 } 5943 5944 if (DiagnosedMultipleConstructedBases) 5945 Shadow->setInvalidDecl(); 5946 } 5947 5948 /// Find the constructor to use for inherited construction of a base class, 5949 /// and whether that base class constructor inherits the constructor from a 5950 /// virtual base class (in which case it won't actually invoke it). 5951 std::pair<CXXConstructorDecl *, bool> 5952 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 5953 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 5954 if (It == InheritedFromBases.end()) 5955 return std::make_pair(nullptr, false); 5956 5957 // This is an intermediary class. 5958 if (It->second) 5959 return std::make_pair( 5960 S.findInheritingConstructor(UseLoc, Ctor, It->second), 5961 It->second->constructsVirtualBase()); 5962 5963 // This is the base class from which the constructor was inherited. 5964 return std::make_pair(Ctor, false); 5965 } 5966 }; 5967 5968 /// Is the special member function which would be selected to perform the 5969 /// specified operation on the specified class type a constexpr constructor? 5970 static bool 5971 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5972 Sema::CXXSpecialMember CSM, unsigned Quals, 5973 bool ConstRHS, 5974 CXXConstructorDecl *InheritedCtor = nullptr, 5975 Sema::InheritedConstructorInfo *Inherited = nullptr) { 5976 // If we're inheriting a constructor, see if we need to call it for this base 5977 // class. 5978 if (InheritedCtor) { 5979 assert(CSM == Sema::CXXDefaultConstructor); 5980 auto BaseCtor = 5981 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 5982 if (BaseCtor) 5983 return BaseCtor->isConstexpr(); 5984 } 5985 5986 if (CSM == Sema::CXXDefaultConstructor) 5987 return ClassDecl->hasConstexprDefaultConstructor(); 5988 5989 Sema::SpecialMemberOverloadResult SMOR = 5990 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5991 if (!SMOR.getMethod()) 5992 // A constructor we wouldn't select can't be "involved in initializing" 5993 // anything. 5994 return true; 5995 return SMOR.getMethod()->isConstexpr(); 5996 } 5997 5998 /// Determine whether the specified special member function would be constexpr 5999 /// if it were implicitly defined. 6000 static bool defaultedSpecialMemberIsConstexpr( 6001 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6002 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6003 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6004 if (!S.getLangOpts().CPlusPlus11) 6005 return false; 6006 6007 // C++11 [dcl.constexpr]p4: 6008 // In the definition of a constexpr constructor [...] 6009 bool Ctor = true; 6010 switch (CSM) { 6011 case Sema::CXXDefaultConstructor: 6012 if (Inherited) 6013 break; 6014 // Since default constructor lookup is essentially trivial (and cannot 6015 // involve, for instance, template instantiation), we compute whether a 6016 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6017 // 6018 // This is important for performance; we need to know whether the default 6019 // constructor is constexpr to determine whether the type is a literal type. 6020 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6021 6022 case Sema::CXXCopyConstructor: 6023 case Sema::CXXMoveConstructor: 6024 // For copy or move constructors, we need to perform overload resolution. 6025 break; 6026 6027 case Sema::CXXCopyAssignment: 6028 case Sema::CXXMoveAssignment: 6029 if (!S.getLangOpts().CPlusPlus14) 6030 return false; 6031 // In C++1y, we need to perform overload resolution. 6032 Ctor = false; 6033 break; 6034 6035 case Sema::CXXDestructor: 6036 case Sema::CXXInvalid: 6037 return false; 6038 } 6039 6040 // -- if the class is a non-empty union, or for each non-empty anonymous 6041 // union member of a non-union class, exactly one non-static data member 6042 // shall be initialized; [DR1359] 6043 // 6044 // If we squint, this is guaranteed, since exactly one non-static data member 6045 // will be initialized (if the constructor isn't deleted), we just don't know 6046 // which one. 6047 if (Ctor && ClassDecl->isUnion()) 6048 return CSM == Sema::CXXDefaultConstructor 6049 ? ClassDecl->hasInClassInitializer() || 6050 !ClassDecl->hasVariantMembers() 6051 : true; 6052 6053 // -- the class shall not have any virtual base classes; 6054 if (Ctor && ClassDecl->getNumVBases()) 6055 return false; 6056 6057 // C++1y [class.copy]p26: 6058 // -- [the class] is a literal type, and 6059 if (!Ctor && !ClassDecl->isLiteral()) 6060 return false; 6061 6062 // -- every constructor involved in initializing [...] base class 6063 // sub-objects shall be a constexpr constructor; 6064 // -- the assignment operator selected to copy/move each direct base 6065 // class is a constexpr function, and 6066 for (const auto &B : ClassDecl->bases()) { 6067 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6068 if (!BaseType) continue; 6069 6070 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6071 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6072 InheritedCtor, Inherited)) 6073 return false; 6074 } 6075 6076 // -- every constructor involved in initializing non-static data members 6077 // [...] shall be a constexpr constructor; 6078 // -- every non-static data member and base class sub-object shall be 6079 // initialized 6080 // -- for each non-static data member of X that is of class type (or array 6081 // thereof), the assignment operator selected to copy/move that member is 6082 // a constexpr function 6083 for (const auto *F : ClassDecl->fields()) { 6084 if (F->isInvalidDecl()) 6085 continue; 6086 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6087 continue; 6088 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6089 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6090 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6091 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6092 BaseType.getCVRQualifiers(), 6093 ConstArg && !F->isMutable())) 6094 return false; 6095 } else if (CSM == Sema::CXXDefaultConstructor) { 6096 return false; 6097 } 6098 } 6099 6100 // All OK, it's constexpr! 6101 return true; 6102 } 6103 6104 static Sema::ImplicitExceptionSpecification 6105 ComputeDefaultedSpecialMemberExceptionSpec( 6106 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6107 Sema::InheritedConstructorInfo *ICI); 6108 6109 static Sema::ImplicitExceptionSpecification 6110 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6111 auto CSM = S.getSpecialMember(MD); 6112 if (CSM != Sema::CXXInvalid) 6113 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6114 6115 auto *CD = cast<CXXConstructorDecl>(MD); 6116 assert(CD->getInheritedConstructor() && 6117 "only special members have implicit exception specs"); 6118 Sema::InheritedConstructorInfo ICI( 6119 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6120 return ComputeDefaultedSpecialMemberExceptionSpec( 6121 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6122 } 6123 6124 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6125 CXXMethodDecl *MD) { 6126 FunctionProtoType::ExtProtoInfo EPI; 6127 6128 // Build an exception specification pointing back at this member. 6129 EPI.ExceptionSpec.Type = EST_Unevaluated; 6130 EPI.ExceptionSpec.SourceDecl = MD; 6131 6132 // Set the calling convention to the default for C++ instance methods. 6133 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6134 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6135 /*IsCXXMethod=*/true)); 6136 return EPI; 6137 } 6138 6139 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6140 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6141 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6142 return; 6143 6144 // Evaluate the exception specification. 6145 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6146 auto ESI = IES.getExceptionSpec(); 6147 6148 // Update the type of the special member to use it. 6149 UpdateExceptionSpec(MD, ESI); 6150 6151 // A user-provided destructor can be defined outside the class. When that 6152 // happens, be sure to update the exception specification on both 6153 // declarations. 6154 const FunctionProtoType *CanonicalFPT = 6155 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6156 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6157 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6158 } 6159 6160 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6161 CXXRecordDecl *RD = MD->getParent(); 6162 CXXSpecialMember CSM = getSpecialMember(MD); 6163 6164 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6165 "not an explicitly-defaulted special member"); 6166 6167 // Whether this was the first-declared instance of the constructor. 6168 // This affects whether we implicitly add an exception spec and constexpr. 6169 bool First = MD == MD->getCanonicalDecl(); 6170 6171 bool HadError = false; 6172 6173 // C++11 [dcl.fct.def.default]p1: 6174 // A function that is explicitly defaulted shall 6175 // -- be a special member function (checked elsewhere), 6176 // -- have the same type (except for ref-qualifiers, and except that a 6177 // copy operation can take a non-const reference) as an implicit 6178 // declaration, and 6179 // -- not have default arguments. 6180 unsigned ExpectedParams = 1; 6181 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6182 ExpectedParams = 0; 6183 if (MD->getNumParams() != ExpectedParams) { 6184 // This also checks for default arguments: a copy or move constructor with a 6185 // default argument is classified as a default constructor, and assignment 6186 // operations and destructors can't have default arguments. 6187 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6188 << CSM << MD->getSourceRange(); 6189 HadError = true; 6190 } else if (MD->isVariadic()) { 6191 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6192 << CSM << MD->getSourceRange(); 6193 HadError = true; 6194 } 6195 6196 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6197 6198 bool CanHaveConstParam = false; 6199 if (CSM == CXXCopyConstructor) 6200 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6201 else if (CSM == CXXCopyAssignment) 6202 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6203 6204 QualType ReturnType = Context.VoidTy; 6205 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6206 // Check for return type matching. 6207 ReturnType = Type->getReturnType(); 6208 QualType ExpectedReturnType = 6209 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6210 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6211 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6212 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6213 HadError = true; 6214 } 6215 6216 // A defaulted special member cannot have cv-qualifiers. 6217 if (Type->getTypeQuals()) { 6218 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6219 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6220 HadError = true; 6221 } 6222 } 6223 6224 // Check for parameter type matching. 6225 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6226 bool HasConstParam = false; 6227 if (ExpectedParams && ArgType->isReferenceType()) { 6228 // Argument must be reference to possibly-const T. 6229 QualType ReferentType = ArgType->getPointeeType(); 6230 HasConstParam = ReferentType.isConstQualified(); 6231 6232 if (ReferentType.isVolatileQualified()) { 6233 Diag(MD->getLocation(), 6234 diag::err_defaulted_special_member_volatile_param) << CSM; 6235 HadError = true; 6236 } 6237 6238 if (HasConstParam && !CanHaveConstParam) { 6239 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6240 Diag(MD->getLocation(), 6241 diag::err_defaulted_special_member_copy_const_param) 6242 << (CSM == CXXCopyAssignment); 6243 // FIXME: Explain why this special member can't be const. 6244 } else { 6245 Diag(MD->getLocation(), 6246 diag::err_defaulted_special_member_move_const_param) 6247 << (CSM == CXXMoveAssignment); 6248 } 6249 HadError = true; 6250 } 6251 } else if (ExpectedParams) { 6252 // A copy assignment operator can take its argument by value, but a 6253 // defaulted one cannot. 6254 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6255 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6256 HadError = true; 6257 } 6258 6259 // C++11 [dcl.fct.def.default]p2: 6260 // An explicitly-defaulted function may be declared constexpr only if it 6261 // would have been implicitly declared as constexpr, 6262 // Do not apply this rule to members of class templates, since core issue 1358 6263 // makes such functions always instantiate to constexpr functions. For 6264 // functions which cannot be constexpr (for non-constructors in C++11 and for 6265 // destructors in C++1y), this is checked elsewhere. 6266 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6267 HasConstParam); 6268 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6269 : isa<CXXConstructorDecl>(MD)) && 6270 MD->isConstexpr() && !Constexpr && 6271 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6272 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6273 // FIXME: Explain why the special member can't be constexpr. 6274 HadError = true; 6275 } 6276 6277 // and may have an explicit exception-specification only if it is compatible 6278 // with the exception-specification on the implicit declaration. 6279 if (Type->hasExceptionSpec()) { 6280 // Delay the check if this is the first declaration of the special member, 6281 // since we may not have parsed some necessary in-class initializers yet. 6282 if (First) { 6283 // If the exception specification needs to be instantiated, do so now, 6284 // before we clobber it with an EST_Unevaluated specification below. 6285 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6286 InstantiateExceptionSpec(MD->getLocStart(), MD); 6287 Type = MD->getType()->getAs<FunctionProtoType>(); 6288 } 6289 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6290 } else 6291 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6292 } 6293 6294 // If a function is explicitly defaulted on its first declaration, 6295 if (First) { 6296 // -- it is implicitly considered to be constexpr if the implicit 6297 // definition would be, 6298 MD->setConstexpr(Constexpr); 6299 6300 // -- it is implicitly considered to have the same exception-specification 6301 // as if it had been implicitly declared, 6302 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6303 EPI.ExceptionSpec.Type = EST_Unevaluated; 6304 EPI.ExceptionSpec.SourceDecl = MD; 6305 MD->setType(Context.getFunctionType(ReturnType, 6306 llvm::makeArrayRef(&ArgType, 6307 ExpectedParams), 6308 EPI)); 6309 } 6310 6311 if (ShouldDeleteSpecialMember(MD, CSM)) { 6312 if (First) { 6313 SetDeclDeleted(MD, MD->getLocation()); 6314 } else { 6315 // C++11 [dcl.fct.def.default]p4: 6316 // [For a] user-provided explicitly-defaulted function [...] if such a 6317 // function is implicitly defined as deleted, the program is ill-formed. 6318 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6319 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6320 HadError = true; 6321 } 6322 } 6323 6324 if (HadError) 6325 MD->setInvalidDecl(); 6326 } 6327 6328 /// Check whether the exception specification provided for an 6329 /// explicitly-defaulted special member matches the exception specification 6330 /// that would have been generated for an implicit special member, per 6331 /// C++11 [dcl.fct.def.default]p2. 6332 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6333 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6334 // If the exception specification was explicitly specified but hadn't been 6335 // parsed when the method was defaulted, grab it now. 6336 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6337 SpecifiedType = 6338 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6339 6340 // Compute the implicit exception specification. 6341 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6342 /*IsCXXMethod=*/true); 6343 FunctionProtoType::ExtProtoInfo EPI(CC); 6344 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6345 EPI.ExceptionSpec = IES.getExceptionSpec(); 6346 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6347 Context.getFunctionType(Context.VoidTy, None, EPI)); 6348 6349 // Ensure that it matches. 6350 CheckEquivalentExceptionSpec( 6351 PDiag(diag::err_incorrect_defaulted_exception_spec) 6352 << getSpecialMember(MD), PDiag(), 6353 ImplicitType, SourceLocation(), 6354 SpecifiedType, MD->getLocation()); 6355 } 6356 6357 void Sema::CheckDelayedMemberExceptionSpecs() { 6358 decltype(DelayedExceptionSpecChecks) Checks; 6359 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6360 6361 std::swap(Checks, DelayedExceptionSpecChecks); 6362 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6363 6364 // Perform any deferred checking of exception specifications for virtual 6365 // destructors. 6366 for (auto &Check : Checks) 6367 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6368 6369 // Check that any explicitly-defaulted methods have exception specifications 6370 // compatible with their implicit exception specifications. 6371 for (auto &Spec : Specs) 6372 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6373 } 6374 6375 namespace { 6376 /// CRTP base class for visiting operations performed by a special member 6377 /// function (or inherited constructor). 6378 template<typename Derived> 6379 struct SpecialMemberVisitor { 6380 Sema &S; 6381 CXXMethodDecl *MD; 6382 Sema::CXXSpecialMember CSM; 6383 Sema::InheritedConstructorInfo *ICI; 6384 6385 // Properties of the special member, computed for convenience. 6386 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6387 6388 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6389 Sema::InheritedConstructorInfo *ICI) 6390 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6391 switch (CSM) { 6392 case Sema::CXXDefaultConstructor: 6393 case Sema::CXXCopyConstructor: 6394 case Sema::CXXMoveConstructor: 6395 IsConstructor = true; 6396 break; 6397 case Sema::CXXCopyAssignment: 6398 case Sema::CXXMoveAssignment: 6399 IsAssignment = true; 6400 break; 6401 case Sema::CXXDestructor: 6402 break; 6403 case Sema::CXXInvalid: 6404 llvm_unreachable("invalid special member kind"); 6405 } 6406 6407 if (MD->getNumParams()) { 6408 if (const ReferenceType *RT = 6409 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6410 ConstArg = RT->getPointeeType().isConstQualified(); 6411 } 6412 } 6413 6414 Derived &getDerived() { return static_cast<Derived&>(*this); } 6415 6416 /// Is this a "move" special member? 6417 bool isMove() const { 6418 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6419 } 6420 6421 /// Look up the corresponding special member in the given class. 6422 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6423 unsigned Quals, bool IsMutable) { 6424 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6425 ConstArg && !IsMutable); 6426 } 6427 6428 /// Look up the constructor for the specified base class to see if it's 6429 /// overridden due to this being an inherited constructor. 6430 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6431 if (!ICI) 6432 return {}; 6433 assert(CSM == Sema::CXXDefaultConstructor); 6434 auto *BaseCtor = 6435 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6436 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6437 return MD; 6438 return {}; 6439 } 6440 6441 /// A base or member subobject. 6442 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6443 6444 /// Get the location to use for a subobject in diagnostics. 6445 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6446 // FIXME: For an indirect virtual base, the direct base leading to 6447 // the indirect virtual base would be a more useful choice. 6448 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6449 return B->getBaseTypeLoc(); 6450 else 6451 return Subobj.get<FieldDecl*>()->getLocation(); 6452 } 6453 6454 enum BasesToVisit { 6455 /// Visit all non-virtual (direct) bases. 6456 VisitNonVirtualBases, 6457 /// Visit all direct bases, virtual or not. 6458 VisitDirectBases, 6459 /// Visit all non-virtual bases, and all virtual bases if the class 6460 /// is not abstract. 6461 VisitPotentiallyConstructedBases, 6462 /// Visit all direct or virtual bases. 6463 VisitAllBases 6464 }; 6465 6466 // Visit the bases and members of the class. 6467 bool visit(BasesToVisit Bases) { 6468 CXXRecordDecl *RD = MD->getParent(); 6469 6470 if (Bases == VisitPotentiallyConstructedBases) 6471 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6472 6473 for (auto &B : RD->bases()) 6474 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6475 getDerived().visitBase(&B)) 6476 return true; 6477 6478 if (Bases == VisitAllBases) 6479 for (auto &B : RD->vbases()) 6480 if (getDerived().visitBase(&B)) 6481 return true; 6482 6483 for (auto *F : RD->fields()) 6484 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6485 getDerived().visitField(F)) 6486 return true; 6487 6488 return false; 6489 } 6490 }; 6491 } 6492 6493 namespace { 6494 struct SpecialMemberDeletionInfo 6495 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6496 bool Diagnose; 6497 6498 SourceLocation Loc; 6499 6500 bool AllFieldsAreConst; 6501 6502 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6503 Sema::CXXSpecialMember CSM, 6504 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6505 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6506 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6507 6508 bool inUnion() const { return MD->getParent()->isUnion(); } 6509 6510 Sema::CXXSpecialMember getEffectiveCSM() { 6511 return ICI ? Sema::CXXInvalid : CSM; 6512 } 6513 6514 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6515 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6516 6517 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6518 bool shouldDeleteForField(FieldDecl *FD); 6519 bool shouldDeleteForAllConstMembers(); 6520 6521 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6522 unsigned Quals); 6523 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6524 Sema::SpecialMemberOverloadResult SMOR, 6525 bool IsDtorCallInCtor); 6526 6527 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6528 }; 6529 } 6530 6531 /// Is the given special member inaccessible when used on the given 6532 /// sub-object. 6533 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6534 CXXMethodDecl *target) { 6535 /// If we're operating on a base class, the object type is the 6536 /// type of this special member. 6537 QualType objectTy; 6538 AccessSpecifier access = target->getAccess(); 6539 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6540 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6541 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6542 6543 // If we're operating on a field, the object type is the type of the field. 6544 } else { 6545 objectTy = S.Context.getTypeDeclType(target->getParent()); 6546 } 6547 6548 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6549 } 6550 6551 /// Check whether we should delete a special member due to the implicit 6552 /// definition containing a call to a special member of a subobject. 6553 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6554 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6555 bool IsDtorCallInCtor) { 6556 CXXMethodDecl *Decl = SMOR.getMethod(); 6557 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6558 6559 int DiagKind = -1; 6560 6561 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6562 DiagKind = !Decl ? 0 : 1; 6563 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6564 DiagKind = 2; 6565 else if (!isAccessible(Subobj, Decl)) 6566 DiagKind = 3; 6567 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6568 !Decl->isTrivial()) { 6569 // A member of a union must have a trivial corresponding special member. 6570 // As a weird special case, a destructor call from a union's constructor 6571 // must be accessible and non-deleted, but need not be trivial. Such a 6572 // destructor is never actually called, but is semantically checked as 6573 // if it were. 6574 DiagKind = 4; 6575 } 6576 6577 if (DiagKind == -1) 6578 return false; 6579 6580 if (Diagnose) { 6581 if (Field) { 6582 S.Diag(Field->getLocation(), 6583 diag::note_deleted_special_member_class_subobject) 6584 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6585 << Field << DiagKind << IsDtorCallInCtor; 6586 } else { 6587 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6588 S.Diag(Base->getLocStart(), 6589 diag::note_deleted_special_member_class_subobject) 6590 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6591 << Base->getType() << DiagKind << IsDtorCallInCtor; 6592 } 6593 6594 if (DiagKind == 1) 6595 S.NoteDeletedFunction(Decl); 6596 // FIXME: Explain inaccessibility if DiagKind == 3. 6597 } 6598 6599 return true; 6600 } 6601 6602 /// Check whether we should delete a special member function due to having a 6603 /// direct or virtual base class or non-static data member of class type M. 6604 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6605 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6606 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6607 bool IsMutable = Field && Field->isMutable(); 6608 6609 // C++11 [class.ctor]p5: 6610 // -- any direct or virtual base class, or non-static data member with no 6611 // brace-or-equal-initializer, has class type M (or array thereof) and 6612 // either M has no default constructor or overload resolution as applied 6613 // to M's default constructor results in an ambiguity or in a function 6614 // that is deleted or inaccessible 6615 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6616 // -- a direct or virtual base class B that cannot be copied/moved because 6617 // overload resolution, as applied to B's corresponding special member, 6618 // results in an ambiguity or a function that is deleted or inaccessible 6619 // from the defaulted special member 6620 // C++11 [class.dtor]p5: 6621 // -- any direct or virtual base class [...] has a type with a destructor 6622 // that is deleted or inaccessible 6623 if (!(CSM == Sema::CXXDefaultConstructor && 6624 Field && Field->hasInClassInitializer()) && 6625 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6626 false)) 6627 return true; 6628 6629 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6630 // -- any direct or virtual base class or non-static data member has a 6631 // type with a destructor that is deleted or inaccessible 6632 if (IsConstructor) { 6633 Sema::SpecialMemberOverloadResult SMOR = 6634 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6635 false, false, false, false, false); 6636 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6637 return true; 6638 } 6639 6640 return false; 6641 } 6642 6643 /// Check whether we should delete a special member function due to the class 6644 /// having a particular direct or virtual base class. 6645 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6646 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6647 // If program is correct, BaseClass cannot be null, but if it is, the error 6648 // must be reported elsewhere. 6649 if (!BaseClass) 6650 return false; 6651 // If we have an inheriting constructor, check whether we're calling an 6652 // inherited constructor instead of a default constructor. 6653 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6654 if (auto *BaseCtor = SMOR.getMethod()) { 6655 // Note that we do not check access along this path; other than that, 6656 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6657 // FIXME: Check that the base has a usable destructor! Sink this into 6658 // shouldDeleteForClassSubobject. 6659 if (BaseCtor->isDeleted() && Diagnose) { 6660 S.Diag(Base->getLocStart(), 6661 diag::note_deleted_special_member_class_subobject) 6662 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6663 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6664 S.NoteDeletedFunction(BaseCtor); 6665 } 6666 return BaseCtor->isDeleted(); 6667 } 6668 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6669 } 6670 6671 /// Check whether we should delete a special member function due to the class 6672 /// having a particular non-static data member. 6673 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6674 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6675 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6676 6677 if (CSM == Sema::CXXDefaultConstructor) { 6678 // For a default constructor, all references must be initialized in-class 6679 // and, if a union, it must have a non-const member. 6680 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6681 if (Diagnose) 6682 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6683 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6684 return true; 6685 } 6686 // C++11 [class.ctor]p5: any non-variant non-static data member of 6687 // const-qualified type (or array thereof) with no 6688 // brace-or-equal-initializer does not have a user-provided default 6689 // constructor. 6690 if (!inUnion() && FieldType.isConstQualified() && 6691 !FD->hasInClassInitializer() && 6692 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6693 if (Diagnose) 6694 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6695 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6696 return true; 6697 } 6698 6699 if (inUnion() && !FieldType.isConstQualified()) 6700 AllFieldsAreConst = false; 6701 } else if (CSM == Sema::CXXCopyConstructor) { 6702 // For a copy constructor, data members must not be of rvalue reference 6703 // type. 6704 if (FieldType->isRValueReferenceType()) { 6705 if (Diagnose) 6706 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6707 << MD->getParent() << FD << FieldType; 6708 return true; 6709 } 6710 } else if (IsAssignment) { 6711 // For an assignment operator, data members must not be of reference type. 6712 if (FieldType->isReferenceType()) { 6713 if (Diagnose) 6714 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6715 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6716 return true; 6717 } 6718 if (!FieldRecord && FieldType.isConstQualified()) { 6719 // C++11 [class.copy]p23: 6720 // -- a non-static data member of const non-class type (or array thereof) 6721 if (Diagnose) 6722 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6723 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6724 return true; 6725 } 6726 } 6727 6728 if (FieldRecord) { 6729 // Some additional restrictions exist on the variant members. 6730 if (!inUnion() && FieldRecord->isUnion() && 6731 FieldRecord->isAnonymousStructOrUnion()) { 6732 bool AllVariantFieldsAreConst = true; 6733 6734 // FIXME: Handle anonymous unions declared within anonymous unions. 6735 for (auto *UI : FieldRecord->fields()) { 6736 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6737 6738 if (!UnionFieldType.isConstQualified()) 6739 AllVariantFieldsAreConst = false; 6740 6741 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6742 if (UnionFieldRecord && 6743 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6744 UnionFieldType.getCVRQualifiers())) 6745 return true; 6746 } 6747 6748 // At least one member in each anonymous union must be non-const 6749 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6750 !FieldRecord->field_empty()) { 6751 if (Diagnose) 6752 S.Diag(FieldRecord->getLocation(), 6753 diag::note_deleted_default_ctor_all_const) 6754 << !!ICI << MD->getParent() << /*anonymous union*/1; 6755 return true; 6756 } 6757 6758 // Don't check the implicit member of the anonymous union type. 6759 // This is technically non-conformant, but sanity demands it. 6760 return false; 6761 } 6762 6763 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6764 FieldType.getCVRQualifiers())) 6765 return true; 6766 } 6767 6768 return false; 6769 } 6770 6771 /// C++11 [class.ctor] p5: 6772 /// A defaulted default constructor for a class X is defined as deleted if 6773 /// X is a union and all of its variant members are of const-qualified type. 6774 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6775 // This is a silly definition, because it gives an empty union a deleted 6776 // default constructor. Don't do that. 6777 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 6778 bool AnyFields = false; 6779 for (auto *F : MD->getParent()->fields()) 6780 if ((AnyFields = !F->isUnnamedBitfield())) 6781 break; 6782 if (!AnyFields) 6783 return false; 6784 if (Diagnose) 6785 S.Diag(MD->getParent()->getLocation(), 6786 diag::note_deleted_default_ctor_all_const) 6787 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6788 return true; 6789 } 6790 return false; 6791 } 6792 6793 /// Determine whether a defaulted special member function should be defined as 6794 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6795 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6796 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6797 InheritedConstructorInfo *ICI, 6798 bool Diagnose) { 6799 if (MD->isInvalidDecl()) 6800 return false; 6801 CXXRecordDecl *RD = MD->getParent(); 6802 assert(!RD->isDependentType() && "do deletion after instantiation"); 6803 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6804 return false; 6805 6806 // C++11 [expr.lambda.prim]p19: 6807 // The closure type associated with a lambda-expression has a 6808 // deleted (8.4.3) default constructor and a deleted copy 6809 // assignment operator. 6810 if (RD->isLambda() && 6811 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6812 if (Diagnose) 6813 Diag(RD->getLocation(), diag::note_lambda_decl); 6814 return true; 6815 } 6816 6817 // For an anonymous struct or union, the copy and assignment special members 6818 // will never be used, so skip the check. For an anonymous union declared at 6819 // namespace scope, the constructor and destructor are used. 6820 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6821 RD->isAnonymousStructOrUnion()) 6822 return false; 6823 6824 // C++11 [class.copy]p7, p18: 6825 // If the class definition declares a move constructor or move assignment 6826 // operator, an implicitly declared copy constructor or copy assignment 6827 // operator is defined as deleted. 6828 if (MD->isImplicit() && 6829 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6830 CXXMethodDecl *UserDeclaredMove = nullptr; 6831 6832 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 6833 // deletion of the corresponding copy operation, not both copy operations. 6834 // MSVC 2015 has adopted the standards conforming behavior. 6835 bool DeletesOnlyMatchingCopy = 6836 getLangOpts().MSVCCompat && 6837 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 6838 6839 if (RD->hasUserDeclaredMoveConstructor() && 6840 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 6841 if (!Diagnose) return true; 6842 6843 // Find any user-declared move constructor. 6844 for (auto *I : RD->ctors()) { 6845 if (I->isMoveConstructor()) { 6846 UserDeclaredMove = I; 6847 break; 6848 } 6849 } 6850 assert(UserDeclaredMove); 6851 } else if (RD->hasUserDeclaredMoveAssignment() && 6852 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 6853 if (!Diagnose) return true; 6854 6855 // Find any user-declared move assignment operator. 6856 for (auto *I : RD->methods()) { 6857 if (I->isMoveAssignmentOperator()) { 6858 UserDeclaredMove = I; 6859 break; 6860 } 6861 } 6862 assert(UserDeclaredMove); 6863 } 6864 6865 if (UserDeclaredMove) { 6866 Diag(UserDeclaredMove->getLocation(), 6867 diag::note_deleted_copy_user_declared_move) 6868 << (CSM == CXXCopyAssignment) << RD 6869 << UserDeclaredMove->isMoveAssignmentOperator(); 6870 return true; 6871 } 6872 } 6873 6874 // Do access control from the special member function 6875 ContextRAII MethodContext(*this, MD); 6876 6877 // C++11 [class.dtor]p5: 6878 // -- for a virtual destructor, lookup of the non-array deallocation function 6879 // results in an ambiguity or in a function that is deleted or inaccessible 6880 if (CSM == CXXDestructor && MD->isVirtual()) { 6881 FunctionDecl *OperatorDelete = nullptr; 6882 DeclarationName Name = 6883 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6884 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 6885 OperatorDelete, /*Diagnose*/false)) { 6886 if (Diagnose) 6887 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 6888 return true; 6889 } 6890 } 6891 6892 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 6893 6894 // Per DR1611, do not consider virtual bases of constructors of abstract 6895 // classes, since we are not going to construct them. 6896 // Per DR1658, do not consider virtual bases of destructors of abstract 6897 // classes either. 6898 // Per DR2180, for assignment operators we only assign (and thus only 6899 // consider) direct bases. 6900 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 6901 : SMI.VisitPotentiallyConstructedBases)) 6902 return true; 6903 6904 if (SMI.shouldDeleteForAllConstMembers()) 6905 return true; 6906 6907 if (getLangOpts().CUDA) { 6908 // We should delete the special member in CUDA mode if target inference 6909 // failed. 6910 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 6911 Diagnose); 6912 } 6913 6914 return false; 6915 } 6916 6917 /// Perform lookup for a special member of the specified kind, and determine 6918 /// whether it is trivial. If the triviality can be determined without the 6919 /// lookup, skip it. This is intended for use when determining whether a 6920 /// special member of a containing object is trivial, and thus does not ever 6921 /// perform overload resolution for default constructors. 6922 /// 6923 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 6924 /// member that was most likely to be intended to be trivial, if any. 6925 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 6926 Sema::CXXSpecialMember CSM, unsigned Quals, 6927 bool ConstRHS, CXXMethodDecl **Selected) { 6928 if (Selected) 6929 *Selected = nullptr; 6930 6931 switch (CSM) { 6932 case Sema::CXXInvalid: 6933 llvm_unreachable("not a special member"); 6934 6935 case Sema::CXXDefaultConstructor: 6936 // C++11 [class.ctor]p5: 6937 // A default constructor is trivial if: 6938 // - all the [direct subobjects] have trivial default constructors 6939 // 6940 // Note, no overload resolution is performed in this case. 6941 if (RD->hasTrivialDefaultConstructor()) 6942 return true; 6943 6944 if (Selected) { 6945 // If there's a default constructor which could have been trivial, dig it 6946 // out. Otherwise, if there's any user-provided default constructor, point 6947 // to that as an example of why there's not a trivial one. 6948 CXXConstructorDecl *DefCtor = nullptr; 6949 if (RD->needsImplicitDefaultConstructor()) 6950 S.DeclareImplicitDefaultConstructor(RD); 6951 for (auto *CI : RD->ctors()) { 6952 if (!CI->isDefaultConstructor()) 6953 continue; 6954 DefCtor = CI; 6955 if (!DefCtor->isUserProvided()) 6956 break; 6957 } 6958 6959 *Selected = DefCtor; 6960 } 6961 6962 return false; 6963 6964 case Sema::CXXDestructor: 6965 // C++11 [class.dtor]p5: 6966 // A destructor is trivial if: 6967 // - all the direct [subobjects] have trivial destructors 6968 if (RD->hasTrivialDestructor()) 6969 return true; 6970 6971 if (Selected) { 6972 if (RD->needsImplicitDestructor()) 6973 S.DeclareImplicitDestructor(RD); 6974 *Selected = RD->getDestructor(); 6975 } 6976 6977 return false; 6978 6979 case Sema::CXXCopyConstructor: 6980 // C++11 [class.copy]p12: 6981 // A copy constructor is trivial if: 6982 // - the constructor selected to copy each direct [subobject] is trivial 6983 if (RD->hasTrivialCopyConstructor()) { 6984 if (Quals == Qualifiers::Const) 6985 // We must either select the trivial copy constructor or reach an 6986 // ambiguity; no need to actually perform overload resolution. 6987 return true; 6988 } else if (!Selected) { 6989 return false; 6990 } 6991 // In C++98, we are not supposed to perform overload resolution here, but we 6992 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 6993 // cases like B as having a non-trivial copy constructor: 6994 // struct A { template<typename T> A(T&); }; 6995 // struct B { mutable A a; }; 6996 goto NeedOverloadResolution; 6997 6998 case Sema::CXXCopyAssignment: 6999 // C++11 [class.copy]p25: 7000 // A copy assignment operator is trivial if: 7001 // - the assignment operator selected to copy each direct [subobject] is 7002 // trivial 7003 if (RD->hasTrivialCopyAssignment()) { 7004 if (Quals == Qualifiers::Const) 7005 return true; 7006 } else if (!Selected) { 7007 return false; 7008 } 7009 // In C++98, we are not supposed to perform overload resolution here, but we 7010 // treat that as a language defect. 7011 goto NeedOverloadResolution; 7012 7013 case Sema::CXXMoveConstructor: 7014 case Sema::CXXMoveAssignment: 7015 NeedOverloadResolution: 7016 Sema::SpecialMemberOverloadResult SMOR = 7017 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7018 7019 // The standard doesn't describe how to behave if the lookup is ambiguous. 7020 // We treat it as not making the member non-trivial, just like the standard 7021 // mandates for the default constructor. This should rarely matter, because 7022 // the member will also be deleted. 7023 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7024 return true; 7025 7026 if (!SMOR.getMethod()) { 7027 assert(SMOR.getKind() == 7028 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7029 return false; 7030 } 7031 7032 // We deliberately don't check if we found a deleted special member. We're 7033 // not supposed to! 7034 if (Selected) 7035 *Selected = SMOR.getMethod(); 7036 return SMOR.getMethod()->isTrivial(); 7037 } 7038 7039 llvm_unreachable("unknown special method kind"); 7040 } 7041 7042 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7043 for (auto *CI : RD->ctors()) 7044 if (!CI->isImplicit()) 7045 return CI; 7046 7047 // Look for constructor templates. 7048 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7049 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7050 if (CXXConstructorDecl *CD = 7051 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7052 return CD; 7053 } 7054 7055 return nullptr; 7056 } 7057 7058 /// The kind of subobject we are checking for triviality. The values of this 7059 /// enumeration are used in diagnostics. 7060 enum TrivialSubobjectKind { 7061 /// The subobject is a base class. 7062 TSK_BaseClass, 7063 /// The subobject is a non-static data member. 7064 TSK_Field, 7065 /// The object is actually the complete object. 7066 TSK_CompleteObject 7067 }; 7068 7069 /// Check whether the special member selected for a given type would be trivial. 7070 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7071 QualType SubType, bool ConstRHS, 7072 Sema::CXXSpecialMember CSM, 7073 TrivialSubobjectKind Kind, 7074 bool Diagnose) { 7075 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7076 if (!SubRD) 7077 return true; 7078 7079 CXXMethodDecl *Selected; 7080 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7081 ConstRHS, Diagnose ? &Selected : nullptr)) 7082 return true; 7083 7084 if (Diagnose) { 7085 if (ConstRHS) 7086 SubType.addConst(); 7087 7088 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7089 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7090 << Kind << SubType.getUnqualifiedType(); 7091 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7092 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7093 } else if (!Selected) 7094 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7095 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7096 else if (Selected->isUserProvided()) { 7097 if (Kind == TSK_CompleteObject) 7098 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7099 << Kind << SubType.getUnqualifiedType() << CSM; 7100 else { 7101 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7102 << Kind << SubType.getUnqualifiedType() << CSM; 7103 S.Diag(Selected->getLocation(), diag::note_declared_at); 7104 } 7105 } else { 7106 if (Kind != TSK_CompleteObject) 7107 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7108 << Kind << SubType.getUnqualifiedType() << CSM; 7109 7110 // Explain why the defaulted or deleted special member isn't trivial. 7111 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 7112 } 7113 } 7114 7115 return false; 7116 } 7117 7118 /// Check whether the members of a class type allow a special member to be 7119 /// trivial. 7120 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7121 Sema::CXXSpecialMember CSM, 7122 bool ConstArg, bool Diagnose) { 7123 for (const auto *FI : RD->fields()) { 7124 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7125 continue; 7126 7127 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7128 7129 // Pretend anonymous struct or union members are members of this class. 7130 if (FI->isAnonymousStructOrUnion()) { 7131 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7132 CSM, ConstArg, Diagnose)) 7133 return false; 7134 continue; 7135 } 7136 7137 // C++11 [class.ctor]p5: 7138 // A default constructor is trivial if [...] 7139 // -- no non-static data member of its class has a 7140 // brace-or-equal-initializer 7141 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7142 if (Diagnose) 7143 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7144 return false; 7145 } 7146 7147 // Objective C ARC 4.3.5: 7148 // [...] nontrivally ownership-qualified types are [...] not trivially 7149 // default constructible, copy constructible, move constructible, copy 7150 // assignable, move assignable, or destructible [...] 7151 if (S.getLangOpts().ObjCAutoRefCount && 7152 FieldType.hasNonTrivialObjCLifetime()) { 7153 if (Diagnose) 7154 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7155 << RD << FieldType.getObjCLifetime(); 7156 return false; 7157 } 7158 7159 bool ConstRHS = ConstArg && !FI->isMutable(); 7160 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7161 CSM, TSK_Field, Diagnose)) 7162 return false; 7163 } 7164 7165 return true; 7166 } 7167 7168 /// Diagnose why the specified class does not have a trivial special member of 7169 /// the given kind. 7170 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7171 QualType Ty = Context.getRecordType(RD); 7172 7173 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7174 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7175 TSK_CompleteObject, /*Diagnose*/true); 7176 } 7177 7178 /// Determine whether a defaulted or deleted special member function is trivial, 7179 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7180 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7181 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7182 bool Diagnose) { 7183 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7184 7185 CXXRecordDecl *RD = MD->getParent(); 7186 7187 bool ConstArg = false; 7188 7189 // C++11 [class.copy]p12, p25: [DR1593] 7190 // A [special member] is trivial if [...] its parameter-type-list is 7191 // equivalent to the parameter-type-list of an implicit declaration [...] 7192 switch (CSM) { 7193 case CXXDefaultConstructor: 7194 case CXXDestructor: 7195 // Trivial default constructors and destructors cannot have parameters. 7196 break; 7197 7198 case CXXCopyConstructor: 7199 case CXXCopyAssignment: { 7200 // Trivial copy operations always have const, non-volatile parameter types. 7201 ConstArg = true; 7202 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7203 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7204 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7205 if (Diagnose) 7206 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7207 << Param0->getSourceRange() << Param0->getType() 7208 << Context.getLValueReferenceType( 7209 Context.getRecordType(RD).withConst()); 7210 return false; 7211 } 7212 break; 7213 } 7214 7215 case CXXMoveConstructor: 7216 case CXXMoveAssignment: { 7217 // Trivial move operations always have non-cv-qualified parameters. 7218 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7219 const RValueReferenceType *RT = 7220 Param0->getType()->getAs<RValueReferenceType>(); 7221 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7222 if (Diagnose) 7223 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7224 << Param0->getSourceRange() << Param0->getType() 7225 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7226 return false; 7227 } 7228 break; 7229 } 7230 7231 case CXXInvalid: 7232 llvm_unreachable("not a special member"); 7233 } 7234 7235 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7236 if (Diagnose) 7237 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7238 diag::note_nontrivial_default_arg) 7239 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7240 return false; 7241 } 7242 if (MD->isVariadic()) { 7243 if (Diagnose) 7244 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7245 return false; 7246 } 7247 7248 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7249 // A copy/move [constructor or assignment operator] is trivial if 7250 // -- the [member] selected to copy/move each direct base class subobject 7251 // is trivial 7252 // 7253 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7254 // A [default constructor or destructor] is trivial if 7255 // -- all the direct base classes have trivial [default constructors or 7256 // destructors] 7257 for (const auto &BI : RD->bases()) 7258 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7259 ConstArg, CSM, TSK_BaseClass, Diagnose)) 7260 return false; 7261 7262 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7263 // A copy/move [constructor or assignment operator] for a class X is 7264 // trivial if 7265 // -- for each non-static data member of X that is of class type (or array 7266 // thereof), the constructor selected to copy/move that member is 7267 // trivial 7268 // 7269 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7270 // A [default constructor or destructor] is trivial if 7271 // -- for all of the non-static data members of its class that are of class 7272 // type (or array thereof), each such class has a trivial [default 7273 // constructor or destructor] 7274 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 7275 return false; 7276 7277 // C++11 [class.dtor]p5: 7278 // A destructor is trivial if [...] 7279 // -- the destructor is not virtual 7280 if (CSM == CXXDestructor && MD->isVirtual()) { 7281 if (Diagnose) 7282 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7283 return false; 7284 } 7285 7286 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7287 // A [special member] for class X is trivial if [...] 7288 // -- class X has no virtual functions and no virtual base classes 7289 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7290 if (!Diagnose) 7291 return false; 7292 7293 if (RD->getNumVBases()) { 7294 // Check for virtual bases. We already know that the corresponding 7295 // member in all bases is trivial, so vbases must all be direct. 7296 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7297 assert(BS.isVirtual()); 7298 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7299 return false; 7300 } 7301 7302 // Must have a virtual method. 7303 for (const auto *MI : RD->methods()) { 7304 if (MI->isVirtual()) { 7305 SourceLocation MLoc = MI->getLocStart(); 7306 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7307 return false; 7308 } 7309 } 7310 7311 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7312 } 7313 7314 // Looks like it's trivial! 7315 return true; 7316 } 7317 7318 namespace { 7319 struct FindHiddenVirtualMethod { 7320 Sema *S; 7321 CXXMethodDecl *Method; 7322 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7323 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7324 7325 private: 7326 /// Check whether any most overriden method from MD in Methods 7327 static bool CheckMostOverridenMethods( 7328 const CXXMethodDecl *MD, 7329 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7330 if (MD->size_overridden_methods() == 0) 7331 return Methods.count(MD->getCanonicalDecl()); 7332 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7333 E = MD->end_overridden_methods(); 7334 I != E; ++I) 7335 if (CheckMostOverridenMethods(*I, Methods)) 7336 return true; 7337 return false; 7338 } 7339 7340 public: 7341 /// Member lookup function that determines whether a given C++ 7342 /// method overloads virtual methods in a base class without overriding any, 7343 /// to be used with CXXRecordDecl::lookupInBases(). 7344 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7345 RecordDecl *BaseRecord = 7346 Specifier->getType()->getAs<RecordType>()->getDecl(); 7347 7348 DeclarationName Name = Method->getDeclName(); 7349 assert(Name.getNameKind() == DeclarationName::Identifier); 7350 7351 bool foundSameNameMethod = false; 7352 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7353 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7354 Path.Decls = Path.Decls.slice(1)) { 7355 NamedDecl *D = Path.Decls.front(); 7356 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7357 MD = MD->getCanonicalDecl(); 7358 foundSameNameMethod = true; 7359 // Interested only in hidden virtual methods. 7360 if (!MD->isVirtual()) 7361 continue; 7362 // If the method we are checking overrides a method from its base 7363 // don't warn about the other overloaded methods. Clang deviates from 7364 // GCC by only diagnosing overloads of inherited virtual functions that 7365 // do not override any other virtual functions in the base. GCC's 7366 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7367 // function from a base class. These cases may be better served by a 7368 // warning (not specific to virtual functions) on call sites when the 7369 // call would select a different function from the base class, were it 7370 // visible. 7371 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7372 if (!S->IsOverload(Method, MD, false)) 7373 return true; 7374 // Collect the overload only if its hidden. 7375 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7376 overloadedMethods.push_back(MD); 7377 } 7378 } 7379 7380 if (foundSameNameMethod) 7381 OverloadedMethods.append(overloadedMethods.begin(), 7382 overloadedMethods.end()); 7383 return foundSameNameMethod; 7384 } 7385 }; 7386 } // end anonymous namespace 7387 7388 /// \brief Add the most overriden methods from MD to Methods 7389 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7390 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7391 if (MD->size_overridden_methods() == 0) 7392 Methods.insert(MD->getCanonicalDecl()); 7393 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7394 E = MD->end_overridden_methods(); 7395 I != E; ++I) 7396 AddMostOverridenMethods(*I, Methods); 7397 } 7398 7399 /// \brief Check if a method overloads virtual methods in a base class without 7400 /// overriding any. 7401 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7402 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7403 if (!MD->getDeclName().isIdentifier()) 7404 return; 7405 7406 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7407 /*bool RecordPaths=*/false, 7408 /*bool DetectVirtual=*/false); 7409 FindHiddenVirtualMethod FHVM; 7410 FHVM.Method = MD; 7411 FHVM.S = this; 7412 7413 // Keep the base methods that were overriden or introduced in the subclass 7414 // by 'using' in a set. A base method not in this set is hidden. 7415 CXXRecordDecl *DC = MD->getParent(); 7416 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7417 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7418 NamedDecl *ND = *I; 7419 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7420 ND = shad->getTargetDecl(); 7421 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7422 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7423 } 7424 7425 if (DC->lookupInBases(FHVM, Paths)) 7426 OverloadedMethods = FHVM.OverloadedMethods; 7427 } 7428 7429 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7430 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7431 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7432 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7433 PartialDiagnostic PD = PDiag( 7434 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7435 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7436 Diag(overloadedMD->getLocation(), PD); 7437 } 7438 } 7439 7440 /// \brief Diagnose methods which overload virtual methods in a base class 7441 /// without overriding any. 7442 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7443 if (MD->isInvalidDecl()) 7444 return; 7445 7446 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7447 return; 7448 7449 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7450 FindHiddenVirtualMethods(MD, OverloadedMethods); 7451 if (!OverloadedMethods.empty()) { 7452 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7453 << MD << (OverloadedMethods.size() > 1); 7454 7455 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7456 } 7457 } 7458 7459 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7460 Decl *TagDecl, 7461 SourceLocation LBrac, 7462 SourceLocation RBrac, 7463 AttributeList *AttrList) { 7464 if (!TagDecl) 7465 return; 7466 7467 AdjustDeclIfTemplate(TagDecl); 7468 7469 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7470 if (l->getKind() != AttributeList::AT_Visibility) 7471 continue; 7472 l->setInvalid(); 7473 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7474 l->getName(); 7475 } 7476 7477 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7478 // strict aliasing violation! 7479 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7480 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7481 7482 CheckCompletedCXXClass( 7483 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7484 } 7485 7486 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7487 /// special functions, such as the default constructor, copy 7488 /// constructor, or destructor, to the given C++ class (C++ 7489 /// [special]p1). This routine can only be executed just before the 7490 /// definition of the class is complete. 7491 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7492 if (ClassDecl->needsImplicitDefaultConstructor()) { 7493 ++ASTContext::NumImplicitDefaultConstructors; 7494 7495 if (ClassDecl->hasInheritedConstructor()) 7496 DeclareImplicitDefaultConstructor(ClassDecl); 7497 } 7498 7499 if (ClassDecl->needsImplicitCopyConstructor()) { 7500 ++ASTContext::NumImplicitCopyConstructors; 7501 7502 // If the properties or semantics of the copy constructor couldn't be 7503 // determined while the class was being declared, force a declaration 7504 // of it now. 7505 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7506 ClassDecl->hasInheritedConstructor()) 7507 DeclareImplicitCopyConstructor(ClassDecl); 7508 // For the MS ABI we need to know whether the copy ctor is deleted. A 7509 // prerequisite for deleting the implicit copy ctor is that the class has a 7510 // move ctor or move assignment that is either user-declared or whose 7511 // semantics are inherited from a subobject. FIXME: We should provide a more 7512 // direct way for CodeGen to ask whether the constructor was deleted. 7513 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7514 (ClassDecl->hasUserDeclaredMoveConstructor() || 7515 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7516 ClassDecl->hasUserDeclaredMoveAssignment() || 7517 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7518 DeclareImplicitCopyConstructor(ClassDecl); 7519 } 7520 7521 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7522 ++ASTContext::NumImplicitMoveConstructors; 7523 7524 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7525 ClassDecl->hasInheritedConstructor()) 7526 DeclareImplicitMoveConstructor(ClassDecl); 7527 } 7528 7529 if (ClassDecl->needsImplicitCopyAssignment()) { 7530 ++ASTContext::NumImplicitCopyAssignmentOperators; 7531 7532 // If we have a dynamic class, then the copy assignment operator may be 7533 // virtual, so we have to declare it immediately. This ensures that, e.g., 7534 // it shows up in the right place in the vtable and that we diagnose 7535 // problems with the implicit exception specification. 7536 if (ClassDecl->isDynamicClass() || 7537 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7538 ClassDecl->hasInheritedAssignment()) 7539 DeclareImplicitCopyAssignment(ClassDecl); 7540 } 7541 7542 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7543 ++ASTContext::NumImplicitMoveAssignmentOperators; 7544 7545 // Likewise for the move assignment operator. 7546 if (ClassDecl->isDynamicClass() || 7547 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7548 ClassDecl->hasInheritedAssignment()) 7549 DeclareImplicitMoveAssignment(ClassDecl); 7550 } 7551 7552 if (ClassDecl->needsImplicitDestructor()) { 7553 ++ASTContext::NumImplicitDestructors; 7554 7555 // If we have a dynamic class, then the destructor may be virtual, so we 7556 // have to declare the destructor immediately. This ensures that, e.g., it 7557 // shows up in the right place in the vtable and that we diagnose problems 7558 // with the implicit exception specification. 7559 if (ClassDecl->isDynamicClass() || 7560 ClassDecl->needsOverloadResolutionForDestructor()) 7561 DeclareImplicitDestructor(ClassDecl); 7562 } 7563 } 7564 7565 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7566 if (!D) 7567 return 0; 7568 7569 // The order of template parameters is not important here. All names 7570 // get added to the same scope. 7571 SmallVector<TemplateParameterList *, 4> ParameterLists; 7572 7573 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7574 D = TD->getTemplatedDecl(); 7575 7576 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7577 ParameterLists.push_back(PSD->getTemplateParameters()); 7578 7579 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7580 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7581 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7582 7583 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7584 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7585 ParameterLists.push_back(FTD->getTemplateParameters()); 7586 } 7587 } 7588 7589 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7590 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7591 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7592 7593 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7594 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7595 ParameterLists.push_back(CTD->getTemplateParameters()); 7596 } 7597 } 7598 7599 unsigned Count = 0; 7600 for (TemplateParameterList *Params : ParameterLists) { 7601 if (Params->size() > 0) 7602 // Ignore explicit specializations; they don't contribute to the template 7603 // depth. 7604 ++Count; 7605 for (NamedDecl *Param : *Params) { 7606 if (Param->getDeclName()) { 7607 S->AddDecl(Param); 7608 IdResolver.AddDecl(Param); 7609 } 7610 } 7611 } 7612 7613 return Count; 7614 } 7615 7616 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7617 if (!RecordD) return; 7618 AdjustDeclIfTemplate(RecordD); 7619 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7620 PushDeclContext(S, Record); 7621 } 7622 7623 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7624 if (!RecordD) return; 7625 PopDeclContext(); 7626 } 7627 7628 /// This is used to implement the constant expression evaluation part of the 7629 /// attribute enable_if extension. There is nothing in standard C++ which would 7630 /// require reentering parameters. 7631 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7632 if (!Param) 7633 return; 7634 7635 S->AddDecl(Param); 7636 if (Param->getDeclName()) 7637 IdResolver.AddDecl(Param); 7638 } 7639 7640 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7641 /// parsing a top-level (non-nested) C++ class, and we are now 7642 /// parsing those parts of the given Method declaration that could 7643 /// not be parsed earlier (C++ [class.mem]p2), such as default 7644 /// arguments. This action should enter the scope of the given 7645 /// Method declaration as if we had just parsed the qualified method 7646 /// name. However, it should not bring the parameters into scope; 7647 /// that will be performed by ActOnDelayedCXXMethodParameter. 7648 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7649 } 7650 7651 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7652 /// C++ method declaration. We're (re-)introducing the given 7653 /// function parameter into scope for use in parsing later parts of 7654 /// the method declaration. For example, we could see an 7655 /// ActOnParamDefaultArgument event for this parameter. 7656 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7657 if (!ParamD) 7658 return; 7659 7660 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7661 7662 // If this parameter has an unparsed default argument, clear it out 7663 // to make way for the parsed default argument. 7664 if (Param->hasUnparsedDefaultArg()) 7665 Param->setDefaultArg(nullptr); 7666 7667 S->AddDecl(Param); 7668 if (Param->getDeclName()) 7669 IdResolver.AddDecl(Param); 7670 } 7671 7672 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7673 /// processing the delayed method declaration for Method. The method 7674 /// declaration is now considered finished. There may be a separate 7675 /// ActOnStartOfFunctionDef action later (not necessarily 7676 /// immediately!) for this method, if it was also defined inside the 7677 /// class body. 7678 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7679 if (!MethodD) 7680 return; 7681 7682 AdjustDeclIfTemplate(MethodD); 7683 7684 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7685 7686 // Now that we have our default arguments, check the constructor 7687 // again. It could produce additional diagnostics or affect whether 7688 // the class has implicitly-declared destructors, among other 7689 // things. 7690 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7691 CheckConstructor(Constructor); 7692 7693 // Check the default arguments, which we may have added. 7694 if (!Method->isInvalidDecl()) 7695 CheckCXXDefaultArguments(Method); 7696 } 7697 7698 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7699 /// the well-formedness of the constructor declarator @p D with type @p 7700 /// R. If there are any errors in the declarator, this routine will 7701 /// emit diagnostics and set the invalid bit to true. In any case, the type 7702 /// will be updated to reflect a well-formed type for the constructor and 7703 /// returned. 7704 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7705 StorageClass &SC) { 7706 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7707 7708 // C++ [class.ctor]p3: 7709 // A constructor shall not be virtual (10.3) or static (9.4). A 7710 // constructor can be invoked for a const, volatile or const 7711 // volatile object. A constructor shall not be declared const, 7712 // volatile, or const volatile (9.3.2). 7713 if (isVirtual) { 7714 if (!D.isInvalidType()) 7715 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7716 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7717 << SourceRange(D.getIdentifierLoc()); 7718 D.setInvalidType(); 7719 } 7720 if (SC == SC_Static) { 7721 if (!D.isInvalidType()) 7722 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7723 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7724 << SourceRange(D.getIdentifierLoc()); 7725 D.setInvalidType(); 7726 SC = SC_None; 7727 } 7728 7729 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7730 diagnoseIgnoredQualifiers( 7731 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7732 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7733 D.getDeclSpec().getRestrictSpecLoc(), 7734 D.getDeclSpec().getAtomicSpecLoc()); 7735 D.setInvalidType(); 7736 } 7737 7738 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7739 if (FTI.TypeQuals != 0) { 7740 if (FTI.TypeQuals & Qualifiers::Const) 7741 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7742 << "const" << SourceRange(D.getIdentifierLoc()); 7743 if (FTI.TypeQuals & Qualifiers::Volatile) 7744 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7745 << "volatile" << SourceRange(D.getIdentifierLoc()); 7746 if (FTI.TypeQuals & Qualifiers::Restrict) 7747 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7748 << "restrict" << SourceRange(D.getIdentifierLoc()); 7749 D.setInvalidType(); 7750 } 7751 7752 // C++0x [class.ctor]p4: 7753 // A constructor shall not be declared with a ref-qualifier. 7754 if (FTI.hasRefQualifier()) { 7755 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7756 << FTI.RefQualifierIsLValueRef 7757 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7758 D.setInvalidType(); 7759 } 7760 7761 // Rebuild the function type "R" without any type qualifiers (in 7762 // case any of the errors above fired) and with "void" as the 7763 // return type, since constructors don't have return types. 7764 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7765 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7766 return R; 7767 7768 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7769 EPI.TypeQuals = 0; 7770 EPI.RefQualifier = RQ_None; 7771 7772 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7773 } 7774 7775 /// CheckConstructor - Checks a fully-formed constructor for 7776 /// well-formedness, issuing any diagnostics required. Returns true if 7777 /// the constructor declarator is invalid. 7778 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7779 CXXRecordDecl *ClassDecl 7780 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7781 if (!ClassDecl) 7782 return Constructor->setInvalidDecl(); 7783 7784 // C++ [class.copy]p3: 7785 // A declaration of a constructor for a class X is ill-formed if 7786 // its first parameter is of type (optionally cv-qualified) X and 7787 // either there are no other parameters or else all other 7788 // parameters have default arguments. 7789 if (!Constructor->isInvalidDecl() && 7790 ((Constructor->getNumParams() == 1) || 7791 (Constructor->getNumParams() > 1 && 7792 Constructor->getParamDecl(1)->hasDefaultArg())) && 7793 Constructor->getTemplateSpecializationKind() 7794 != TSK_ImplicitInstantiation) { 7795 QualType ParamType = Constructor->getParamDecl(0)->getType(); 7796 QualType ClassTy = Context.getTagDeclType(ClassDecl); 7797 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 7798 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 7799 const char *ConstRef 7800 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 7801 : " const &"; 7802 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 7803 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 7804 7805 // FIXME: Rather that making the constructor invalid, we should endeavor 7806 // to fix the type. 7807 Constructor->setInvalidDecl(); 7808 } 7809 } 7810 } 7811 7812 /// CheckDestructor - Checks a fully-formed destructor definition for 7813 /// well-formedness, issuing any diagnostics required. Returns true 7814 /// on error. 7815 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 7816 CXXRecordDecl *RD = Destructor->getParent(); 7817 7818 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 7819 SourceLocation Loc; 7820 7821 if (!Destructor->isImplicit()) 7822 Loc = Destructor->getLocation(); 7823 else 7824 Loc = RD->getLocation(); 7825 7826 // If we have a virtual destructor, look up the deallocation function 7827 if (FunctionDecl *OperatorDelete = 7828 FindDeallocationFunctionForDestructor(Loc, RD)) { 7829 MarkFunctionReferenced(Loc, OperatorDelete); 7830 Destructor->setOperatorDelete(OperatorDelete); 7831 } 7832 } 7833 7834 return false; 7835 } 7836 7837 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 7838 /// the well-formednes of the destructor declarator @p D with type @p 7839 /// R. If there are any errors in the declarator, this routine will 7840 /// emit diagnostics and set the declarator to invalid. Even if this happens, 7841 /// will be updated to reflect a well-formed type for the destructor and 7842 /// returned. 7843 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 7844 StorageClass& SC) { 7845 // C++ [class.dtor]p1: 7846 // [...] A typedef-name that names a class is a class-name 7847 // (7.1.3); however, a typedef-name that names a class shall not 7848 // be used as the identifier in the declarator for a destructor 7849 // declaration. 7850 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 7851 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 7852 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7853 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 7854 else if (const TemplateSpecializationType *TST = 7855 DeclaratorType->getAs<TemplateSpecializationType>()) 7856 if (TST->isTypeAlias()) 7857 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7858 << DeclaratorType << 1; 7859 7860 // C++ [class.dtor]p2: 7861 // A destructor is used to destroy objects of its class type. A 7862 // destructor takes no parameters, and no return type can be 7863 // specified for it (not even void). The address of a destructor 7864 // shall not be taken. A destructor shall not be static. A 7865 // destructor can be invoked for a const, volatile or const 7866 // volatile object. A destructor shall not be declared const, 7867 // volatile or const volatile (9.3.2). 7868 if (SC == SC_Static) { 7869 if (!D.isInvalidType()) 7870 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 7871 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7872 << SourceRange(D.getIdentifierLoc()) 7873 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7874 7875 SC = SC_None; 7876 } 7877 if (!D.isInvalidType()) { 7878 // Destructors don't have return types, but the parser will 7879 // happily parse something like: 7880 // 7881 // class X { 7882 // float ~X(); 7883 // }; 7884 // 7885 // The return type will be eliminated later. 7886 if (D.getDeclSpec().hasTypeSpecifier()) 7887 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 7888 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7889 << SourceRange(D.getIdentifierLoc()); 7890 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7891 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 7892 SourceLocation(), 7893 D.getDeclSpec().getConstSpecLoc(), 7894 D.getDeclSpec().getVolatileSpecLoc(), 7895 D.getDeclSpec().getRestrictSpecLoc(), 7896 D.getDeclSpec().getAtomicSpecLoc()); 7897 D.setInvalidType(); 7898 } 7899 } 7900 7901 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7902 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 7903 if (FTI.TypeQuals & Qualifiers::Const) 7904 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7905 << "const" << SourceRange(D.getIdentifierLoc()); 7906 if (FTI.TypeQuals & Qualifiers::Volatile) 7907 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7908 << "volatile" << SourceRange(D.getIdentifierLoc()); 7909 if (FTI.TypeQuals & Qualifiers::Restrict) 7910 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7911 << "restrict" << SourceRange(D.getIdentifierLoc()); 7912 D.setInvalidType(); 7913 } 7914 7915 // C++0x [class.dtor]p2: 7916 // A destructor shall not be declared with a ref-qualifier. 7917 if (FTI.hasRefQualifier()) { 7918 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 7919 << FTI.RefQualifierIsLValueRef 7920 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7921 D.setInvalidType(); 7922 } 7923 7924 // Make sure we don't have any parameters. 7925 if (FTIHasNonVoidParameters(FTI)) { 7926 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 7927 7928 // Delete the parameters. 7929 FTI.freeParams(); 7930 D.setInvalidType(); 7931 } 7932 7933 // Make sure the destructor isn't variadic. 7934 if (FTI.isVariadic) { 7935 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 7936 D.setInvalidType(); 7937 } 7938 7939 // Rebuild the function type "R" without any type qualifiers or 7940 // parameters (in case any of the errors above fired) and with 7941 // "void" as the return type, since destructors don't have return 7942 // types. 7943 if (!D.isInvalidType()) 7944 return R; 7945 7946 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7947 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7948 EPI.Variadic = false; 7949 EPI.TypeQuals = 0; 7950 EPI.RefQualifier = RQ_None; 7951 return Context.getFunctionType(Context.VoidTy, None, EPI); 7952 } 7953 7954 static void extendLeft(SourceRange &R, SourceRange Before) { 7955 if (Before.isInvalid()) 7956 return; 7957 R.setBegin(Before.getBegin()); 7958 if (R.getEnd().isInvalid()) 7959 R.setEnd(Before.getEnd()); 7960 } 7961 7962 static void extendRight(SourceRange &R, SourceRange After) { 7963 if (After.isInvalid()) 7964 return; 7965 if (R.getBegin().isInvalid()) 7966 R.setBegin(After.getBegin()); 7967 R.setEnd(After.getEnd()); 7968 } 7969 7970 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 7971 /// well-formednes of the conversion function declarator @p D with 7972 /// type @p R. If there are any errors in the declarator, this routine 7973 /// will emit diagnostics and return true. Otherwise, it will return 7974 /// false. Either way, the type @p R will be updated to reflect a 7975 /// well-formed type for the conversion operator. 7976 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 7977 StorageClass& SC) { 7978 // C++ [class.conv.fct]p1: 7979 // Neither parameter types nor return type can be specified. The 7980 // type of a conversion function (8.3.5) is "function taking no 7981 // parameter returning conversion-type-id." 7982 if (SC == SC_Static) { 7983 if (!D.isInvalidType()) 7984 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 7985 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7986 << D.getName().getSourceRange(); 7987 D.setInvalidType(); 7988 SC = SC_None; 7989 } 7990 7991 TypeSourceInfo *ConvTSI = nullptr; 7992 QualType ConvType = 7993 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 7994 7995 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 7996 // Conversion functions don't have return types, but the parser will 7997 // happily parse something like: 7998 // 7999 // class X { 8000 // float operator bool(); 8001 // }; 8002 // 8003 // The return type will be changed later anyway. 8004 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8005 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8006 << SourceRange(D.getIdentifierLoc()); 8007 D.setInvalidType(); 8008 } 8009 8010 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8011 8012 // Make sure we don't have any parameters. 8013 if (Proto->getNumParams() > 0) { 8014 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8015 8016 // Delete the parameters. 8017 D.getFunctionTypeInfo().freeParams(); 8018 D.setInvalidType(); 8019 } else if (Proto->isVariadic()) { 8020 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8021 D.setInvalidType(); 8022 } 8023 8024 // Diagnose "&operator bool()" and other such nonsense. This 8025 // is actually a gcc extension which we don't support. 8026 if (Proto->getReturnType() != ConvType) { 8027 bool NeedsTypedef = false; 8028 SourceRange Before, After; 8029 8030 // Walk the chunks and extract information on them for our diagnostic. 8031 bool PastFunctionChunk = false; 8032 for (auto &Chunk : D.type_objects()) { 8033 switch (Chunk.Kind) { 8034 case DeclaratorChunk::Function: 8035 if (!PastFunctionChunk) { 8036 if (Chunk.Fun.HasTrailingReturnType) { 8037 TypeSourceInfo *TRT = nullptr; 8038 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8039 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8040 } 8041 PastFunctionChunk = true; 8042 break; 8043 } 8044 // Fall through. 8045 case DeclaratorChunk::Array: 8046 NeedsTypedef = true; 8047 extendRight(After, Chunk.getSourceRange()); 8048 break; 8049 8050 case DeclaratorChunk::Pointer: 8051 case DeclaratorChunk::BlockPointer: 8052 case DeclaratorChunk::Reference: 8053 case DeclaratorChunk::MemberPointer: 8054 case DeclaratorChunk::Pipe: 8055 extendLeft(Before, Chunk.getSourceRange()); 8056 break; 8057 8058 case DeclaratorChunk::Paren: 8059 extendLeft(Before, Chunk.Loc); 8060 extendRight(After, Chunk.EndLoc); 8061 break; 8062 } 8063 } 8064 8065 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8066 After.isValid() ? After.getBegin() : 8067 D.getIdentifierLoc(); 8068 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8069 DB << Before << After; 8070 8071 if (!NeedsTypedef) { 8072 DB << /*don't need a typedef*/0; 8073 8074 // If we can provide a correct fix-it hint, do so. 8075 if (After.isInvalid() && ConvTSI) { 8076 SourceLocation InsertLoc = 8077 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8078 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8079 << FixItHint::CreateInsertionFromRange( 8080 InsertLoc, CharSourceRange::getTokenRange(Before)) 8081 << FixItHint::CreateRemoval(Before); 8082 } 8083 } else if (!Proto->getReturnType()->isDependentType()) { 8084 DB << /*typedef*/1 << Proto->getReturnType(); 8085 } else if (getLangOpts().CPlusPlus11) { 8086 DB << /*alias template*/2 << Proto->getReturnType(); 8087 } else { 8088 DB << /*might not be fixable*/3; 8089 } 8090 8091 // Recover by incorporating the other type chunks into the result type. 8092 // Note, this does *not* change the name of the function. This is compatible 8093 // with the GCC extension: 8094 // struct S { &operator int(); } s; 8095 // int &r = s.operator int(); // ok in GCC 8096 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8097 ConvType = Proto->getReturnType(); 8098 } 8099 8100 // C++ [class.conv.fct]p4: 8101 // The conversion-type-id shall not represent a function type nor 8102 // an array type. 8103 if (ConvType->isArrayType()) { 8104 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8105 ConvType = Context.getPointerType(ConvType); 8106 D.setInvalidType(); 8107 } else if (ConvType->isFunctionType()) { 8108 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8109 ConvType = Context.getPointerType(ConvType); 8110 D.setInvalidType(); 8111 } 8112 8113 // Rebuild the function type "R" without any parameters (in case any 8114 // of the errors above fired) and with the conversion type as the 8115 // return type. 8116 if (D.isInvalidType()) 8117 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8118 8119 // C++0x explicit conversion operators. 8120 if (D.getDeclSpec().isExplicitSpecified()) 8121 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8122 getLangOpts().CPlusPlus11 ? 8123 diag::warn_cxx98_compat_explicit_conversion_functions : 8124 diag::ext_explicit_conversion_functions) 8125 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 8126 } 8127 8128 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8129 /// the declaration of the given C++ conversion function. This routine 8130 /// is responsible for recording the conversion function in the C++ 8131 /// class, if possible. 8132 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8133 assert(Conversion && "Expected to receive a conversion function declaration"); 8134 8135 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8136 8137 // Make sure we aren't redeclaring the conversion function. 8138 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8139 8140 // C++ [class.conv.fct]p1: 8141 // [...] A conversion function is never used to convert a 8142 // (possibly cv-qualified) object to the (possibly cv-qualified) 8143 // same object type (or a reference to it), to a (possibly 8144 // cv-qualified) base class of that type (or a reference to it), 8145 // or to (possibly cv-qualified) void. 8146 // FIXME: Suppress this warning if the conversion function ends up being a 8147 // virtual function that overrides a virtual function in a base class. 8148 QualType ClassType 8149 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8150 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8151 ConvType = ConvTypeRef->getPointeeType(); 8152 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8153 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8154 /* Suppress diagnostics for instantiations. */; 8155 else if (ConvType->isRecordType()) { 8156 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8157 if (ConvType == ClassType) 8158 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8159 << ClassType; 8160 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8161 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8162 << ClassType << ConvType; 8163 } else if (ConvType->isVoidType()) { 8164 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8165 << ClassType << ConvType; 8166 } 8167 8168 if (FunctionTemplateDecl *ConversionTemplate 8169 = Conversion->getDescribedFunctionTemplate()) 8170 return ConversionTemplate; 8171 8172 return Conversion; 8173 } 8174 8175 namespace { 8176 /// Utility class to accumulate and print a diagnostic listing the invalid 8177 /// specifier(s) on a declaration. 8178 struct BadSpecifierDiagnoser { 8179 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8180 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8181 ~BadSpecifierDiagnoser() { 8182 Diagnostic << Specifiers; 8183 } 8184 8185 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8186 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8187 } 8188 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8189 return check(SpecLoc, 8190 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8191 } 8192 void check(SourceLocation SpecLoc, const char *Spec) { 8193 if (SpecLoc.isInvalid()) return; 8194 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8195 if (!Specifiers.empty()) Specifiers += " "; 8196 Specifiers += Spec; 8197 } 8198 8199 Sema &S; 8200 Sema::SemaDiagnosticBuilder Diagnostic; 8201 std::string Specifiers; 8202 }; 8203 } 8204 8205 /// Check the validity of a declarator that we parsed for a deduction-guide. 8206 /// These aren't actually declarators in the grammar, so we need to check that 8207 /// the user didn't specify any pieces that are not part of the deduction-guide 8208 /// grammar. 8209 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8210 StorageClass &SC) { 8211 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8212 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8213 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8214 8215 // C++ [temp.deduct.guide]p3: 8216 // A deduction-gide shall be declared in the same scope as the 8217 // corresponding class template. 8218 if (!CurContext->getRedeclContext()->Equals( 8219 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8220 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8221 << GuidedTemplateDecl; 8222 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8223 } 8224 8225 auto &DS = D.getMutableDeclSpec(); 8226 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8227 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8228 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8229 DS.isNoreturnSpecified() || DS.isConstexprSpecified() || 8230 DS.isConceptSpecified()) { 8231 BadSpecifierDiagnoser Diagnoser( 8232 *this, D.getIdentifierLoc(), 8233 diag::err_deduction_guide_invalid_specifier); 8234 8235 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8236 DS.ClearStorageClassSpecs(); 8237 SC = SC_None; 8238 8239 // 'explicit' is permitted. 8240 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8241 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8242 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8243 Diagnoser.check(DS.getConceptSpecLoc(), "concept"); 8244 DS.ClearConstexprSpec(); 8245 DS.ClearConceptSpec(); 8246 8247 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8248 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8249 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8250 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8251 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8252 DS.ClearTypeQualifiers(); 8253 8254 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8255 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8256 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8257 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8258 DS.ClearTypeSpecType(); 8259 } 8260 8261 if (D.isInvalidType()) 8262 return; 8263 8264 // Check the declarator is simple enough. 8265 bool FoundFunction = false; 8266 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8267 if (Chunk.Kind == DeclaratorChunk::Paren) 8268 continue; 8269 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8270 Diag(D.getDeclSpec().getLocStart(), 8271 diag::err_deduction_guide_with_complex_decl) 8272 << D.getSourceRange(); 8273 break; 8274 } 8275 if (!Chunk.Fun.hasTrailingReturnType()) { 8276 Diag(D.getName().getLocStart(), 8277 diag::err_deduction_guide_no_trailing_return_type); 8278 break; 8279 } 8280 8281 // Check that the return type is written as a specialization of 8282 // the template specified as the deduction-guide's name. 8283 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8284 TypeSourceInfo *TSI = nullptr; 8285 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8286 assert(TSI && "deduction guide has valid type but invalid return type?"); 8287 bool AcceptableReturnType = false; 8288 bool MightInstantiateToSpecialization = false; 8289 if (auto RetTST = 8290 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8291 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8292 bool TemplateMatches = 8293 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8294 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8295 AcceptableReturnType = true; 8296 else { 8297 // This could still instantiate to the right type, unless we know it 8298 // names the wrong class template. 8299 auto *TD = SpecifiedName.getAsTemplateDecl(); 8300 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8301 !TemplateMatches); 8302 } 8303 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8304 MightInstantiateToSpecialization = true; 8305 } 8306 8307 if (!AcceptableReturnType) { 8308 Diag(TSI->getTypeLoc().getLocStart(), 8309 diag::err_deduction_guide_bad_trailing_return_type) 8310 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8311 << TSI->getTypeLoc().getSourceRange(); 8312 } 8313 8314 // Keep going to check that we don't have any inner declarator pieces (we 8315 // could still have a function returning a pointer to a function). 8316 FoundFunction = true; 8317 } 8318 8319 if (D.isFunctionDefinition()) 8320 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8321 } 8322 8323 //===----------------------------------------------------------------------===// 8324 // Namespace Handling 8325 //===----------------------------------------------------------------------===// 8326 8327 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8328 /// reopened. 8329 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8330 SourceLocation Loc, 8331 IdentifierInfo *II, bool *IsInline, 8332 NamespaceDecl *PrevNS) { 8333 assert(*IsInline != PrevNS->isInline()); 8334 8335 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8336 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8337 // inline namespaces, with the intention of bringing names into namespace std. 8338 // 8339 // We support this just well enough to get that case working; this is not 8340 // sufficient to support reopening namespaces as inline in general. 8341 if (*IsInline && II && II->getName().startswith("__atomic") && 8342 S.getSourceManager().isInSystemHeader(Loc)) { 8343 // Mark all prior declarations of the namespace as inline. 8344 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8345 NS = NS->getPreviousDecl()) 8346 NS->setInline(*IsInline); 8347 // Patch up the lookup table for the containing namespace. This isn't really 8348 // correct, but it's good enough for this particular case. 8349 for (auto *I : PrevNS->decls()) 8350 if (auto *ND = dyn_cast<NamedDecl>(I)) 8351 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8352 return; 8353 } 8354 8355 if (PrevNS->isInline()) 8356 // The user probably just forgot the 'inline', so suggest that it 8357 // be added back. 8358 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8359 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8360 else 8361 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8362 8363 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8364 *IsInline = PrevNS->isInline(); 8365 } 8366 8367 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8368 /// definition. 8369 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8370 SourceLocation InlineLoc, 8371 SourceLocation NamespaceLoc, 8372 SourceLocation IdentLoc, 8373 IdentifierInfo *II, 8374 SourceLocation LBrace, 8375 AttributeList *AttrList, 8376 UsingDirectiveDecl *&UD) { 8377 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8378 // For anonymous namespace, take the location of the left brace. 8379 SourceLocation Loc = II ? IdentLoc : LBrace; 8380 bool IsInline = InlineLoc.isValid(); 8381 bool IsInvalid = false; 8382 bool IsStd = false; 8383 bool AddToKnown = false; 8384 Scope *DeclRegionScope = NamespcScope->getParent(); 8385 8386 NamespaceDecl *PrevNS = nullptr; 8387 if (II) { 8388 // C++ [namespace.def]p2: 8389 // The identifier in an original-namespace-definition shall not 8390 // have been previously defined in the declarative region in 8391 // which the original-namespace-definition appears. The 8392 // identifier in an original-namespace-definition is the name of 8393 // the namespace. Subsequently in that declarative region, it is 8394 // treated as an original-namespace-name. 8395 // 8396 // Since namespace names are unique in their scope, and we don't 8397 // look through using directives, just look for any ordinary names 8398 // as if by qualified name lookup. 8399 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration); 8400 LookupQualifiedName(R, CurContext->getRedeclContext()); 8401 NamedDecl *PrevDecl = 8402 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8403 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8404 8405 if (PrevNS) { 8406 // This is an extended namespace definition. 8407 if (IsInline != PrevNS->isInline()) 8408 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8409 &IsInline, PrevNS); 8410 } else if (PrevDecl) { 8411 // This is an invalid name redefinition. 8412 Diag(Loc, diag::err_redefinition_different_kind) 8413 << II; 8414 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8415 IsInvalid = true; 8416 // Continue on to push Namespc as current DeclContext and return it. 8417 } else if (II->isStr("std") && 8418 CurContext->getRedeclContext()->isTranslationUnit()) { 8419 // This is the first "real" definition of the namespace "std", so update 8420 // our cache of the "std" namespace to point at this definition. 8421 PrevNS = getStdNamespace(); 8422 IsStd = true; 8423 AddToKnown = !IsInline; 8424 } else { 8425 // We've seen this namespace for the first time. 8426 AddToKnown = !IsInline; 8427 } 8428 } else { 8429 // Anonymous namespaces. 8430 8431 // Determine whether the parent already has an anonymous namespace. 8432 DeclContext *Parent = CurContext->getRedeclContext(); 8433 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8434 PrevNS = TU->getAnonymousNamespace(); 8435 } else { 8436 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8437 PrevNS = ND->getAnonymousNamespace(); 8438 } 8439 8440 if (PrevNS && IsInline != PrevNS->isInline()) 8441 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8442 &IsInline, PrevNS); 8443 } 8444 8445 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8446 StartLoc, Loc, II, PrevNS); 8447 if (IsInvalid) 8448 Namespc->setInvalidDecl(); 8449 8450 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8451 8452 // FIXME: Should we be merging attributes? 8453 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8454 PushNamespaceVisibilityAttr(Attr, Loc); 8455 8456 if (IsStd) 8457 StdNamespace = Namespc; 8458 if (AddToKnown) 8459 KnownNamespaces[Namespc] = false; 8460 8461 if (II) { 8462 PushOnScopeChains(Namespc, DeclRegionScope); 8463 } else { 8464 // Link the anonymous namespace into its parent. 8465 DeclContext *Parent = CurContext->getRedeclContext(); 8466 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8467 TU->setAnonymousNamespace(Namespc); 8468 } else { 8469 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8470 } 8471 8472 CurContext->addDecl(Namespc); 8473 8474 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8475 // behaves as if it were replaced by 8476 // namespace unique { /* empty body */ } 8477 // using namespace unique; 8478 // namespace unique { namespace-body } 8479 // where all occurrences of 'unique' in a translation unit are 8480 // replaced by the same identifier and this identifier differs 8481 // from all other identifiers in the entire program. 8482 8483 // We just create the namespace with an empty name and then add an 8484 // implicit using declaration, just like the standard suggests. 8485 // 8486 // CodeGen enforces the "universally unique" aspect by giving all 8487 // declarations semantically contained within an anonymous 8488 // namespace internal linkage. 8489 8490 if (!PrevNS) { 8491 UD = UsingDirectiveDecl::Create(Context, Parent, 8492 /* 'using' */ LBrace, 8493 /* 'namespace' */ SourceLocation(), 8494 /* qualifier */ NestedNameSpecifierLoc(), 8495 /* identifier */ SourceLocation(), 8496 Namespc, 8497 /* Ancestor */ Parent); 8498 UD->setImplicit(); 8499 Parent->addDecl(UD); 8500 } 8501 } 8502 8503 ActOnDocumentableDecl(Namespc); 8504 8505 // Although we could have an invalid decl (i.e. the namespace name is a 8506 // redefinition), push it as current DeclContext and try to continue parsing. 8507 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8508 // for the namespace has the declarations that showed up in that particular 8509 // namespace definition. 8510 PushDeclContext(NamespcScope, Namespc); 8511 return Namespc; 8512 } 8513 8514 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8515 /// is a namespace alias, returns the namespace it points to. 8516 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8517 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8518 return AD->getNamespace(); 8519 return dyn_cast_or_null<NamespaceDecl>(D); 8520 } 8521 8522 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8523 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8524 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8525 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8526 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8527 Namespc->setRBraceLoc(RBrace); 8528 PopDeclContext(); 8529 if (Namespc->hasAttr<VisibilityAttr>()) 8530 PopPragmaVisibility(true, RBrace); 8531 } 8532 8533 CXXRecordDecl *Sema::getStdBadAlloc() const { 8534 return cast_or_null<CXXRecordDecl>( 8535 StdBadAlloc.get(Context.getExternalSource())); 8536 } 8537 8538 EnumDecl *Sema::getStdAlignValT() const { 8539 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8540 } 8541 8542 NamespaceDecl *Sema::getStdNamespace() const { 8543 return cast_or_null<NamespaceDecl>( 8544 StdNamespace.get(Context.getExternalSource())); 8545 } 8546 8547 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8548 if (!StdExperimentalNamespaceCache) { 8549 if (auto Std = getStdNamespace()) { 8550 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8551 SourceLocation(), LookupNamespaceName); 8552 if (!LookupQualifiedName(Result, Std) || 8553 !(StdExperimentalNamespaceCache = 8554 Result.getAsSingle<NamespaceDecl>())) 8555 Result.suppressDiagnostics(); 8556 } 8557 } 8558 return StdExperimentalNamespaceCache; 8559 } 8560 8561 /// \brief Retrieve the special "std" namespace, which may require us to 8562 /// implicitly define the namespace. 8563 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8564 if (!StdNamespace) { 8565 // The "std" namespace has not yet been defined, so build one implicitly. 8566 StdNamespace = NamespaceDecl::Create(Context, 8567 Context.getTranslationUnitDecl(), 8568 /*Inline=*/false, 8569 SourceLocation(), SourceLocation(), 8570 &PP.getIdentifierTable().get("std"), 8571 /*PrevDecl=*/nullptr); 8572 getStdNamespace()->setImplicit(true); 8573 } 8574 8575 return getStdNamespace(); 8576 } 8577 8578 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8579 assert(getLangOpts().CPlusPlus && 8580 "Looking for std::initializer_list outside of C++."); 8581 8582 // We're looking for implicit instantiations of 8583 // template <typename E> class std::initializer_list. 8584 8585 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8586 return false; 8587 8588 ClassTemplateDecl *Template = nullptr; 8589 const TemplateArgument *Arguments = nullptr; 8590 8591 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8592 8593 ClassTemplateSpecializationDecl *Specialization = 8594 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8595 if (!Specialization) 8596 return false; 8597 8598 Template = Specialization->getSpecializedTemplate(); 8599 Arguments = Specialization->getTemplateArgs().data(); 8600 } else if (const TemplateSpecializationType *TST = 8601 Ty->getAs<TemplateSpecializationType>()) { 8602 Template = dyn_cast_or_null<ClassTemplateDecl>( 8603 TST->getTemplateName().getAsTemplateDecl()); 8604 Arguments = TST->getArgs(); 8605 } 8606 if (!Template) 8607 return false; 8608 8609 if (!StdInitializerList) { 8610 // Haven't recognized std::initializer_list yet, maybe this is it. 8611 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8612 if (TemplateClass->getIdentifier() != 8613 &PP.getIdentifierTable().get("initializer_list") || 8614 !getStdNamespace()->InEnclosingNamespaceSetOf( 8615 TemplateClass->getDeclContext())) 8616 return false; 8617 // This is a template called std::initializer_list, but is it the right 8618 // template? 8619 TemplateParameterList *Params = Template->getTemplateParameters(); 8620 if (Params->getMinRequiredArguments() != 1) 8621 return false; 8622 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8623 return false; 8624 8625 // It's the right template. 8626 StdInitializerList = Template; 8627 } 8628 8629 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8630 return false; 8631 8632 // This is an instance of std::initializer_list. Find the argument type. 8633 if (Element) 8634 *Element = Arguments[0].getAsType(); 8635 return true; 8636 } 8637 8638 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8639 NamespaceDecl *Std = S.getStdNamespace(); 8640 if (!Std) { 8641 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8642 return nullptr; 8643 } 8644 8645 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8646 Loc, Sema::LookupOrdinaryName); 8647 if (!S.LookupQualifiedName(Result, Std)) { 8648 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8649 return nullptr; 8650 } 8651 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8652 if (!Template) { 8653 Result.suppressDiagnostics(); 8654 // We found something weird. Complain about the first thing we found. 8655 NamedDecl *Found = *Result.begin(); 8656 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8657 return nullptr; 8658 } 8659 8660 // We found some template called std::initializer_list. Now verify that it's 8661 // correct. 8662 TemplateParameterList *Params = Template->getTemplateParameters(); 8663 if (Params->getMinRequiredArguments() != 1 || 8664 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8665 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8666 return nullptr; 8667 } 8668 8669 return Template; 8670 } 8671 8672 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8673 if (!StdInitializerList) { 8674 StdInitializerList = LookupStdInitializerList(*this, Loc); 8675 if (!StdInitializerList) 8676 return QualType(); 8677 } 8678 8679 TemplateArgumentListInfo Args(Loc, Loc); 8680 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8681 Context.getTrivialTypeSourceInfo(Element, 8682 Loc))); 8683 return Context.getCanonicalType( 8684 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8685 } 8686 8687 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 8688 // C++ [dcl.init.list]p2: 8689 // A constructor is an initializer-list constructor if its first parameter 8690 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8691 // std::initializer_list<E> for some type E, and either there are no other 8692 // parameters or else all other parameters have default arguments. 8693 if (Ctor->getNumParams() < 1 || 8694 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8695 return false; 8696 8697 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8698 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8699 ArgType = RT->getPointeeType().getUnqualifiedType(); 8700 8701 return isStdInitializerList(ArgType, nullptr); 8702 } 8703 8704 /// \brief Determine whether a using statement is in a context where it will be 8705 /// apply in all contexts. 8706 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8707 switch (CurContext->getDeclKind()) { 8708 case Decl::TranslationUnit: 8709 return true; 8710 case Decl::LinkageSpec: 8711 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8712 default: 8713 return false; 8714 } 8715 } 8716 8717 namespace { 8718 8719 // Callback to only accept typo corrections that are namespaces. 8720 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8721 public: 8722 bool ValidateCandidate(const TypoCorrection &candidate) override { 8723 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8724 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8725 return false; 8726 } 8727 }; 8728 8729 } 8730 8731 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8732 CXXScopeSpec &SS, 8733 SourceLocation IdentLoc, 8734 IdentifierInfo *Ident) { 8735 R.clear(); 8736 if (TypoCorrection Corrected = 8737 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8738 llvm::make_unique<NamespaceValidatorCCC>(), 8739 Sema::CTK_ErrorRecovery)) { 8740 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8741 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8742 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8743 Ident->getName().equals(CorrectedStr); 8744 S.diagnoseTypo(Corrected, 8745 S.PDiag(diag::err_using_directive_member_suggest) 8746 << Ident << DC << DroppedSpecifier << SS.getRange(), 8747 S.PDiag(diag::note_namespace_defined_here)); 8748 } else { 8749 S.diagnoseTypo(Corrected, 8750 S.PDiag(diag::err_using_directive_suggest) << Ident, 8751 S.PDiag(diag::note_namespace_defined_here)); 8752 } 8753 R.addDecl(Corrected.getFoundDecl()); 8754 return true; 8755 } 8756 return false; 8757 } 8758 8759 Decl *Sema::ActOnUsingDirective(Scope *S, 8760 SourceLocation UsingLoc, 8761 SourceLocation NamespcLoc, 8762 CXXScopeSpec &SS, 8763 SourceLocation IdentLoc, 8764 IdentifierInfo *NamespcName, 8765 AttributeList *AttrList) { 8766 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8767 assert(NamespcName && "Invalid NamespcName."); 8768 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 8769 8770 // This can only happen along a recovery path. 8771 while (S->isTemplateParamScope()) 8772 S = S->getParent(); 8773 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8774 8775 UsingDirectiveDecl *UDir = nullptr; 8776 NestedNameSpecifier *Qualifier = nullptr; 8777 if (SS.isSet()) 8778 Qualifier = SS.getScopeRep(); 8779 8780 // Lookup namespace name. 8781 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 8782 LookupParsedName(R, S, &SS); 8783 if (R.isAmbiguous()) 8784 return nullptr; 8785 8786 if (R.empty()) { 8787 R.clear(); 8788 // Allow "using namespace std;" or "using namespace ::std;" even if 8789 // "std" hasn't been defined yet, for GCC compatibility. 8790 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 8791 NamespcName->isStr("std")) { 8792 Diag(IdentLoc, diag::ext_using_undefined_std); 8793 R.addDecl(getOrCreateStdNamespace()); 8794 R.resolveKind(); 8795 } 8796 // Otherwise, attempt typo correction. 8797 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 8798 } 8799 8800 if (!R.empty()) { 8801 NamedDecl *Named = R.getRepresentativeDecl(); 8802 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 8803 assert(NS && "expected namespace decl"); 8804 8805 // The use of a nested name specifier may trigger deprecation warnings. 8806 DiagnoseUseOfDecl(Named, IdentLoc); 8807 8808 // C++ [namespace.udir]p1: 8809 // A using-directive specifies that the names in the nominated 8810 // namespace can be used in the scope in which the 8811 // using-directive appears after the using-directive. During 8812 // unqualified name lookup (3.4.1), the names appear as if they 8813 // were declared in the nearest enclosing namespace which 8814 // contains both the using-directive and the nominated 8815 // namespace. [Note: in this context, "contains" means "contains 8816 // directly or indirectly". ] 8817 8818 // Find enclosing context containing both using-directive and 8819 // nominated namespace. 8820 DeclContext *CommonAncestor = cast<DeclContext>(NS); 8821 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 8822 CommonAncestor = CommonAncestor->getParent(); 8823 8824 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 8825 SS.getWithLocInContext(Context), 8826 IdentLoc, Named, CommonAncestor); 8827 8828 if (IsUsingDirectiveInToplevelContext(CurContext) && 8829 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 8830 Diag(IdentLoc, diag::warn_using_directive_in_header); 8831 } 8832 8833 PushUsingDirective(S, UDir); 8834 } else { 8835 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8836 } 8837 8838 if (UDir) 8839 ProcessDeclAttributeList(S, UDir, AttrList); 8840 8841 return UDir; 8842 } 8843 8844 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 8845 // If the scope has an associated entity and the using directive is at 8846 // namespace or translation unit scope, add the UsingDirectiveDecl into 8847 // its lookup structure so qualified name lookup can find it. 8848 DeclContext *Ctx = S->getEntity(); 8849 if (Ctx && !Ctx->isFunctionOrMethod()) 8850 Ctx->addDecl(UDir); 8851 else 8852 // Otherwise, it is at block scope. The using-directives will affect lookup 8853 // only to the end of the scope. 8854 S->PushUsingDirective(UDir); 8855 } 8856 8857 8858 Decl *Sema::ActOnUsingDeclaration(Scope *S, 8859 AccessSpecifier AS, 8860 SourceLocation UsingLoc, 8861 SourceLocation TypenameLoc, 8862 CXXScopeSpec &SS, 8863 UnqualifiedId &Name, 8864 SourceLocation EllipsisLoc, 8865 AttributeList *AttrList) { 8866 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8867 8868 if (SS.isEmpty()) { 8869 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 8870 return nullptr; 8871 } 8872 8873 switch (Name.getKind()) { 8874 case UnqualifiedId::IK_ImplicitSelfParam: 8875 case UnqualifiedId::IK_Identifier: 8876 case UnqualifiedId::IK_OperatorFunctionId: 8877 case UnqualifiedId::IK_LiteralOperatorId: 8878 case UnqualifiedId::IK_ConversionFunctionId: 8879 break; 8880 8881 case UnqualifiedId::IK_ConstructorName: 8882 case UnqualifiedId::IK_ConstructorTemplateId: 8883 // C++11 inheriting constructors. 8884 Diag(Name.getLocStart(), 8885 getLangOpts().CPlusPlus11 ? 8886 diag::warn_cxx98_compat_using_decl_constructor : 8887 diag::err_using_decl_constructor) 8888 << SS.getRange(); 8889 8890 if (getLangOpts().CPlusPlus11) break; 8891 8892 return nullptr; 8893 8894 case UnqualifiedId::IK_DestructorName: 8895 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 8896 << SS.getRange(); 8897 return nullptr; 8898 8899 case UnqualifiedId::IK_TemplateId: 8900 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 8901 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 8902 return nullptr; 8903 8904 case UnqualifiedId::IK_DeductionGuideName: 8905 llvm_unreachable("cannot parse qualified deduction guide name"); 8906 } 8907 8908 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 8909 DeclarationName TargetName = TargetNameInfo.getName(); 8910 if (!TargetName) 8911 return nullptr; 8912 8913 // Warn about access declarations. 8914 if (UsingLoc.isInvalid()) { 8915 Diag(Name.getLocStart(), 8916 getLangOpts().CPlusPlus11 ? diag::err_access_decl 8917 : diag::warn_access_decl_deprecated) 8918 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 8919 } 8920 8921 if (EllipsisLoc.isInvalid()) { 8922 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 8923 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 8924 return nullptr; 8925 } else { 8926 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 8927 !TargetNameInfo.containsUnexpandedParameterPack()) { 8928 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 8929 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 8930 EllipsisLoc = SourceLocation(); 8931 } 8932 } 8933 8934 NamedDecl *UD = 8935 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 8936 SS, TargetNameInfo, EllipsisLoc, AttrList, 8937 /*IsInstantiation*/false); 8938 if (UD) 8939 PushOnScopeChains(UD, S, /*AddToContext*/ false); 8940 8941 return UD; 8942 } 8943 8944 /// \brief Determine whether a using declaration considers the given 8945 /// declarations as "equivalent", e.g., if they are redeclarations of 8946 /// the same entity or are both typedefs of the same type. 8947 static bool 8948 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 8949 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 8950 return true; 8951 8952 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 8953 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 8954 return Context.hasSameType(TD1->getUnderlyingType(), 8955 TD2->getUnderlyingType()); 8956 8957 return false; 8958 } 8959 8960 8961 /// Determines whether to create a using shadow decl for a particular 8962 /// decl, given the set of decls existing prior to this using lookup. 8963 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 8964 const LookupResult &Previous, 8965 UsingShadowDecl *&PrevShadow) { 8966 // Diagnose finding a decl which is not from a base class of the 8967 // current class. We do this now because there are cases where this 8968 // function will silently decide not to build a shadow decl, which 8969 // will pre-empt further diagnostics. 8970 // 8971 // We don't need to do this in C++11 because we do the check once on 8972 // the qualifier. 8973 // 8974 // FIXME: diagnose the following if we care enough: 8975 // struct A { int foo; }; 8976 // struct B : A { using A::foo; }; 8977 // template <class T> struct C : A {}; 8978 // template <class T> struct D : C<T> { using B::foo; } // <--- 8979 // This is invalid (during instantiation) in C++03 because B::foo 8980 // resolves to the using decl in B, which is not a base class of D<T>. 8981 // We can't diagnose it immediately because C<T> is an unknown 8982 // specialization. The UsingShadowDecl in D<T> then points directly 8983 // to A::foo, which will look well-formed when we instantiate. 8984 // The right solution is to not collapse the shadow-decl chain. 8985 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 8986 DeclContext *OrigDC = Orig->getDeclContext(); 8987 8988 // Handle enums and anonymous structs. 8989 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 8990 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 8991 while (OrigRec->isAnonymousStructOrUnion()) 8992 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 8993 8994 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 8995 if (OrigDC == CurContext) { 8996 Diag(Using->getLocation(), 8997 diag::err_using_decl_nested_name_specifier_is_current_class) 8998 << Using->getQualifierLoc().getSourceRange(); 8999 Diag(Orig->getLocation(), diag::note_using_decl_target); 9000 Using->setInvalidDecl(); 9001 return true; 9002 } 9003 9004 Diag(Using->getQualifierLoc().getBeginLoc(), 9005 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9006 << Using->getQualifier() 9007 << cast<CXXRecordDecl>(CurContext) 9008 << Using->getQualifierLoc().getSourceRange(); 9009 Diag(Orig->getLocation(), diag::note_using_decl_target); 9010 Using->setInvalidDecl(); 9011 return true; 9012 } 9013 } 9014 9015 if (Previous.empty()) return false; 9016 9017 NamedDecl *Target = Orig; 9018 if (isa<UsingShadowDecl>(Target)) 9019 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9020 9021 // If the target happens to be one of the previous declarations, we 9022 // don't have a conflict. 9023 // 9024 // FIXME: but we might be increasing its access, in which case we 9025 // should redeclare it. 9026 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9027 bool FoundEquivalentDecl = false; 9028 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9029 I != E; ++I) { 9030 NamedDecl *D = (*I)->getUnderlyingDecl(); 9031 // We can have UsingDecls in our Previous results because we use the same 9032 // LookupResult for checking whether the UsingDecl itself is a valid 9033 // redeclaration. 9034 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9035 continue; 9036 9037 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9038 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9039 PrevShadow = Shadow; 9040 FoundEquivalentDecl = true; 9041 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9042 // We don't conflict with an existing using shadow decl of an equivalent 9043 // declaration, but we're not a redeclaration of it. 9044 FoundEquivalentDecl = true; 9045 } 9046 9047 if (isVisible(D)) 9048 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9049 } 9050 9051 if (FoundEquivalentDecl) 9052 return false; 9053 9054 if (FunctionDecl *FD = Target->getAsFunction()) { 9055 NamedDecl *OldDecl = nullptr; 9056 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9057 /*IsForUsingDecl*/ true)) { 9058 case Ovl_Overload: 9059 return false; 9060 9061 case Ovl_NonFunction: 9062 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9063 break; 9064 9065 // We found a decl with the exact signature. 9066 case Ovl_Match: 9067 // If we're in a record, we want to hide the target, so we 9068 // return true (without a diagnostic) to tell the caller not to 9069 // build a shadow decl. 9070 if (CurContext->isRecord()) 9071 return true; 9072 9073 // If we're not in a record, this is an error. 9074 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9075 break; 9076 } 9077 9078 Diag(Target->getLocation(), diag::note_using_decl_target); 9079 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9080 Using->setInvalidDecl(); 9081 return true; 9082 } 9083 9084 // Target is not a function. 9085 9086 if (isa<TagDecl>(Target)) { 9087 // No conflict between a tag and a non-tag. 9088 if (!Tag) return false; 9089 9090 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9091 Diag(Target->getLocation(), diag::note_using_decl_target); 9092 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9093 Using->setInvalidDecl(); 9094 return true; 9095 } 9096 9097 // No conflict between a tag and a non-tag. 9098 if (!NonTag) return false; 9099 9100 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9101 Diag(Target->getLocation(), diag::note_using_decl_target); 9102 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9103 Using->setInvalidDecl(); 9104 return true; 9105 } 9106 9107 /// Determine whether a direct base class is a virtual base class. 9108 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9109 if (!Derived->getNumVBases()) 9110 return false; 9111 for (auto &B : Derived->bases()) 9112 if (B.getType()->getAsCXXRecordDecl() == Base) 9113 return B.isVirtual(); 9114 llvm_unreachable("not a direct base class"); 9115 } 9116 9117 /// Builds a shadow declaration corresponding to a 'using' declaration. 9118 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9119 UsingDecl *UD, 9120 NamedDecl *Orig, 9121 UsingShadowDecl *PrevDecl) { 9122 // If we resolved to another shadow declaration, just coalesce them. 9123 NamedDecl *Target = Orig; 9124 if (isa<UsingShadowDecl>(Target)) { 9125 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9126 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9127 } 9128 9129 NamedDecl *NonTemplateTarget = Target; 9130 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9131 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9132 9133 UsingShadowDecl *Shadow; 9134 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9135 bool IsVirtualBase = 9136 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9137 UD->getQualifier()->getAsRecordDecl()); 9138 Shadow = ConstructorUsingShadowDecl::Create( 9139 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9140 } else { 9141 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9142 Target); 9143 } 9144 UD->addShadowDecl(Shadow); 9145 9146 Shadow->setAccess(UD->getAccess()); 9147 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9148 Shadow->setInvalidDecl(); 9149 9150 Shadow->setPreviousDecl(PrevDecl); 9151 9152 if (S) 9153 PushOnScopeChains(Shadow, S); 9154 else 9155 CurContext->addDecl(Shadow); 9156 9157 9158 return Shadow; 9159 } 9160 9161 /// Hides a using shadow declaration. This is required by the current 9162 /// using-decl implementation when a resolvable using declaration in a 9163 /// class is followed by a declaration which would hide or override 9164 /// one or more of the using decl's targets; for example: 9165 /// 9166 /// struct Base { void foo(int); }; 9167 /// struct Derived : Base { 9168 /// using Base::foo; 9169 /// void foo(int); 9170 /// }; 9171 /// 9172 /// The governing language is C++03 [namespace.udecl]p12: 9173 /// 9174 /// When a using-declaration brings names from a base class into a 9175 /// derived class scope, member functions in the derived class 9176 /// override and/or hide member functions with the same name and 9177 /// parameter types in a base class (rather than conflicting). 9178 /// 9179 /// There are two ways to implement this: 9180 /// (1) optimistically create shadow decls when they're not hidden 9181 /// by existing declarations, or 9182 /// (2) don't create any shadow decls (or at least don't make them 9183 /// visible) until we've fully parsed/instantiated the class. 9184 /// The problem with (1) is that we might have to retroactively remove 9185 /// a shadow decl, which requires several O(n) operations because the 9186 /// decl structures are (very reasonably) not designed for removal. 9187 /// (2) avoids this but is very fiddly and phase-dependent. 9188 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9189 if (Shadow->getDeclName().getNameKind() == 9190 DeclarationName::CXXConversionFunctionName) 9191 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9192 9193 // Remove it from the DeclContext... 9194 Shadow->getDeclContext()->removeDecl(Shadow); 9195 9196 // ...and the scope, if applicable... 9197 if (S) { 9198 S->RemoveDecl(Shadow); 9199 IdResolver.RemoveDecl(Shadow); 9200 } 9201 9202 // ...and the using decl. 9203 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9204 9205 // TODO: complain somehow if Shadow was used. It shouldn't 9206 // be possible for this to happen, because...? 9207 } 9208 9209 /// Find the base specifier for a base class with the given type. 9210 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9211 QualType DesiredBase, 9212 bool &AnyDependentBases) { 9213 // Check whether the named type is a direct base class. 9214 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9215 for (auto &Base : Derived->bases()) { 9216 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9217 if (CanonicalDesiredBase == BaseType) 9218 return &Base; 9219 if (BaseType->isDependentType()) 9220 AnyDependentBases = true; 9221 } 9222 return nullptr; 9223 } 9224 9225 namespace { 9226 class UsingValidatorCCC : public CorrectionCandidateCallback { 9227 public: 9228 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9229 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9230 : HasTypenameKeyword(HasTypenameKeyword), 9231 IsInstantiation(IsInstantiation), OldNNS(NNS), 9232 RequireMemberOf(RequireMemberOf) {} 9233 9234 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9235 NamedDecl *ND = Candidate.getCorrectionDecl(); 9236 9237 // Keywords are not valid here. 9238 if (!ND || isa<NamespaceDecl>(ND)) 9239 return false; 9240 9241 // Completely unqualified names are invalid for a 'using' declaration. 9242 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9243 return false; 9244 9245 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9246 // reject. 9247 9248 if (RequireMemberOf) { 9249 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9250 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9251 // No-one ever wants a using-declaration to name an injected-class-name 9252 // of a base class, unless they're declaring an inheriting constructor. 9253 ASTContext &Ctx = ND->getASTContext(); 9254 if (!Ctx.getLangOpts().CPlusPlus11) 9255 return false; 9256 QualType FoundType = Ctx.getRecordType(FoundRecord); 9257 9258 // Check that the injected-class-name is named as a member of its own 9259 // type; we don't want to suggest 'using Derived::Base;', since that 9260 // means something else. 9261 NestedNameSpecifier *Specifier = 9262 Candidate.WillReplaceSpecifier() 9263 ? Candidate.getCorrectionSpecifier() 9264 : OldNNS; 9265 if (!Specifier->getAsType() || 9266 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9267 return false; 9268 9269 // Check that this inheriting constructor declaration actually names a 9270 // direct base class of the current class. 9271 bool AnyDependentBases = false; 9272 if (!findDirectBaseWithType(RequireMemberOf, 9273 Ctx.getRecordType(FoundRecord), 9274 AnyDependentBases) && 9275 !AnyDependentBases) 9276 return false; 9277 } else { 9278 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9279 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9280 return false; 9281 9282 // FIXME: Check that the base class member is accessible? 9283 } 9284 } else { 9285 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9286 if (FoundRecord && FoundRecord->isInjectedClassName()) 9287 return false; 9288 } 9289 9290 if (isa<TypeDecl>(ND)) 9291 return HasTypenameKeyword || !IsInstantiation; 9292 9293 return !HasTypenameKeyword; 9294 } 9295 9296 private: 9297 bool HasTypenameKeyword; 9298 bool IsInstantiation; 9299 NestedNameSpecifier *OldNNS; 9300 CXXRecordDecl *RequireMemberOf; 9301 }; 9302 } // end anonymous namespace 9303 9304 /// Builds a using declaration. 9305 /// 9306 /// \param IsInstantiation - Whether this call arises from an 9307 /// instantiation of an unresolved using declaration. We treat 9308 /// the lookup differently for these declarations. 9309 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9310 SourceLocation UsingLoc, 9311 bool HasTypenameKeyword, 9312 SourceLocation TypenameLoc, 9313 CXXScopeSpec &SS, 9314 DeclarationNameInfo NameInfo, 9315 SourceLocation EllipsisLoc, 9316 AttributeList *AttrList, 9317 bool IsInstantiation) { 9318 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9319 SourceLocation IdentLoc = NameInfo.getLoc(); 9320 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9321 9322 // FIXME: We ignore attributes for now. 9323 9324 // For an inheriting constructor declaration, the name of the using 9325 // declaration is the name of a constructor in this class, not in the 9326 // base class. 9327 DeclarationNameInfo UsingName = NameInfo; 9328 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9329 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9330 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9331 Context.getCanonicalType(Context.getRecordType(RD)))); 9332 9333 // Do the redeclaration lookup in the current scope. 9334 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9335 ForRedeclaration); 9336 Previous.setHideTags(false); 9337 if (S) { 9338 LookupName(Previous, S); 9339 9340 // It is really dumb that we have to do this. 9341 LookupResult::Filter F = Previous.makeFilter(); 9342 while (F.hasNext()) { 9343 NamedDecl *D = F.next(); 9344 if (!isDeclInScope(D, CurContext, S)) 9345 F.erase(); 9346 // If we found a local extern declaration that's not ordinarily visible, 9347 // and this declaration is being added to a non-block scope, ignore it. 9348 // We're only checking for scope conflicts here, not also for violations 9349 // of the linkage rules. 9350 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9351 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9352 F.erase(); 9353 } 9354 F.done(); 9355 } else { 9356 assert(IsInstantiation && "no scope in non-instantiation"); 9357 if (CurContext->isRecord()) 9358 LookupQualifiedName(Previous, CurContext); 9359 else { 9360 // No redeclaration check is needed here; in non-member contexts we 9361 // diagnosed all possible conflicts with other using-declarations when 9362 // building the template: 9363 // 9364 // For a dependent non-type using declaration, the only valid case is 9365 // if we instantiate to a single enumerator. We check for conflicts 9366 // between shadow declarations we introduce, and we check in the template 9367 // definition for conflicts between a non-type using declaration and any 9368 // other declaration, which together covers all cases. 9369 // 9370 // A dependent typename using declaration will never successfully 9371 // instantiate, since it will always name a class member, so we reject 9372 // that in the template definition. 9373 } 9374 } 9375 9376 // Check for invalid redeclarations. 9377 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9378 SS, IdentLoc, Previous)) 9379 return nullptr; 9380 9381 // Check for bad qualifiers. 9382 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9383 IdentLoc)) 9384 return nullptr; 9385 9386 DeclContext *LookupContext = computeDeclContext(SS); 9387 NamedDecl *D; 9388 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9389 if (!LookupContext || EllipsisLoc.isValid()) { 9390 if (HasTypenameKeyword) { 9391 // FIXME: not all declaration name kinds are legal here 9392 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9393 UsingLoc, TypenameLoc, 9394 QualifierLoc, 9395 IdentLoc, NameInfo.getName(), 9396 EllipsisLoc); 9397 } else { 9398 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9399 QualifierLoc, NameInfo, EllipsisLoc); 9400 } 9401 D->setAccess(AS); 9402 CurContext->addDecl(D); 9403 return D; 9404 } 9405 9406 auto Build = [&](bool Invalid) { 9407 UsingDecl *UD = 9408 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9409 UsingName, HasTypenameKeyword); 9410 UD->setAccess(AS); 9411 CurContext->addDecl(UD); 9412 UD->setInvalidDecl(Invalid); 9413 return UD; 9414 }; 9415 auto BuildInvalid = [&]{ return Build(true); }; 9416 auto BuildValid = [&]{ return Build(false); }; 9417 9418 if (RequireCompleteDeclContext(SS, LookupContext)) 9419 return BuildInvalid(); 9420 9421 // Look up the target name. 9422 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9423 9424 // Unlike most lookups, we don't always want to hide tag 9425 // declarations: tag names are visible through the using declaration 9426 // even if hidden by ordinary names, *except* in a dependent context 9427 // where it's important for the sanity of two-phase lookup. 9428 if (!IsInstantiation) 9429 R.setHideTags(false); 9430 9431 // For the purposes of this lookup, we have a base object type 9432 // equal to that of the current context. 9433 if (CurContext->isRecord()) { 9434 R.setBaseObjectType( 9435 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9436 } 9437 9438 LookupQualifiedName(R, LookupContext); 9439 9440 // Try to correct typos if possible. If constructor name lookup finds no 9441 // results, that means the named class has no explicit constructors, and we 9442 // suppressed declaring implicit ones (probably because it's dependent or 9443 // invalid). 9444 if (R.empty() && 9445 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9446 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9447 // it will believe that glibc provides a ::gets in cases where it does not, 9448 // and will try to pull it into namespace std with a using-declaration. 9449 // Just ignore the using-declaration in that case. 9450 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9451 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9452 CurContext->isStdNamespace() && 9453 isa<TranslationUnitDecl>(LookupContext) && 9454 getSourceManager().isInSystemHeader(UsingLoc)) 9455 return nullptr; 9456 if (TypoCorrection Corrected = CorrectTypo( 9457 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9458 llvm::make_unique<UsingValidatorCCC>( 9459 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9460 dyn_cast<CXXRecordDecl>(CurContext)), 9461 CTK_ErrorRecovery)) { 9462 // We reject candidates where DroppedSpecifier == true, hence the 9463 // literal '0' below. 9464 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9465 << NameInfo.getName() << LookupContext << 0 9466 << SS.getRange()); 9467 9468 // If we picked a correction with no attached Decl we can't do anything 9469 // useful with it, bail out. 9470 NamedDecl *ND = Corrected.getCorrectionDecl(); 9471 if (!ND) 9472 return BuildInvalid(); 9473 9474 // If we corrected to an inheriting constructor, handle it as one. 9475 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9476 if (RD && RD->isInjectedClassName()) { 9477 // The parent of the injected class name is the class itself. 9478 RD = cast<CXXRecordDecl>(RD->getParent()); 9479 9480 // Fix up the information we'll use to build the using declaration. 9481 if (Corrected.WillReplaceSpecifier()) { 9482 NestedNameSpecifierLocBuilder Builder; 9483 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9484 QualifierLoc.getSourceRange()); 9485 QualifierLoc = Builder.getWithLocInContext(Context); 9486 } 9487 9488 // In this case, the name we introduce is the name of a derived class 9489 // constructor. 9490 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9491 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9492 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9493 UsingName.setNamedTypeInfo(nullptr); 9494 for (auto *Ctor : LookupConstructors(RD)) 9495 R.addDecl(Ctor); 9496 R.resolveKind(); 9497 } else { 9498 // FIXME: Pick up all the declarations if we found an overloaded 9499 // function. 9500 UsingName.setName(ND->getDeclName()); 9501 R.addDecl(ND); 9502 } 9503 } else { 9504 Diag(IdentLoc, diag::err_no_member) 9505 << NameInfo.getName() << LookupContext << SS.getRange(); 9506 return BuildInvalid(); 9507 } 9508 } 9509 9510 if (R.isAmbiguous()) 9511 return BuildInvalid(); 9512 9513 if (HasTypenameKeyword) { 9514 // If we asked for a typename and got a non-type decl, error out. 9515 if (!R.getAsSingle<TypeDecl>()) { 9516 Diag(IdentLoc, diag::err_using_typename_non_type); 9517 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9518 Diag((*I)->getUnderlyingDecl()->getLocation(), 9519 diag::note_using_decl_target); 9520 return BuildInvalid(); 9521 } 9522 } else { 9523 // If we asked for a non-typename and we got a type, error out, 9524 // but only if this is an instantiation of an unresolved using 9525 // decl. Otherwise just silently find the type name. 9526 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9527 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9528 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9529 return BuildInvalid(); 9530 } 9531 } 9532 9533 // C++14 [namespace.udecl]p6: 9534 // A using-declaration shall not name a namespace. 9535 if (R.getAsSingle<NamespaceDecl>()) { 9536 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9537 << SS.getRange(); 9538 return BuildInvalid(); 9539 } 9540 9541 // C++14 [namespace.udecl]p7: 9542 // A using-declaration shall not name a scoped enumerator. 9543 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9544 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9545 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9546 << SS.getRange(); 9547 return BuildInvalid(); 9548 } 9549 } 9550 9551 UsingDecl *UD = BuildValid(); 9552 9553 // Some additional rules apply to inheriting constructors. 9554 if (UsingName.getName().getNameKind() == 9555 DeclarationName::CXXConstructorName) { 9556 // Suppress access diagnostics; the access check is instead performed at the 9557 // point of use for an inheriting constructor. 9558 R.suppressDiagnostics(); 9559 if (CheckInheritingConstructorUsingDecl(UD)) 9560 return UD; 9561 } 9562 9563 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9564 UsingShadowDecl *PrevDecl = nullptr; 9565 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9566 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9567 } 9568 9569 return UD; 9570 } 9571 9572 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 9573 ArrayRef<NamedDecl *> Expansions) { 9574 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 9575 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 9576 isa<UsingPackDecl>(InstantiatedFrom)); 9577 9578 auto *UPD = 9579 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 9580 UPD->setAccess(InstantiatedFrom->getAccess()); 9581 CurContext->addDecl(UPD); 9582 return UPD; 9583 } 9584 9585 /// Additional checks for a using declaration referring to a constructor name. 9586 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9587 assert(!UD->hasTypename() && "expecting a constructor name"); 9588 9589 const Type *SourceType = UD->getQualifier()->getAsType(); 9590 assert(SourceType && 9591 "Using decl naming constructor doesn't have type in scope spec."); 9592 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9593 9594 // Check whether the named type is a direct base class. 9595 bool AnyDependentBases = false; 9596 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9597 AnyDependentBases); 9598 if (!Base && !AnyDependentBases) { 9599 Diag(UD->getUsingLoc(), 9600 diag::err_using_decl_constructor_not_in_direct_base) 9601 << UD->getNameInfo().getSourceRange() 9602 << QualType(SourceType, 0) << TargetClass; 9603 UD->setInvalidDecl(); 9604 return true; 9605 } 9606 9607 if (Base) 9608 Base->setInheritConstructors(); 9609 9610 return false; 9611 } 9612 9613 /// Checks that the given using declaration is not an invalid 9614 /// redeclaration. Note that this is checking only for the using decl 9615 /// itself, not for any ill-formedness among the UsingShadowDecls. 9616 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9617 bool HasTypenameKeyword, 9618 const CXXScopeSpec &SS, 9619 SourceLocation NameLoc, 9620 const LookupResult &Prev) { 9621 NestedNameSpecifier *Qual = SS.getScopeRep(); 9622 9623 // C++03 [namespace.udecl]p8: 9624 // C++0x [namespace.udecl]p10: 9625 // A using-declaration is a declaration and can therefore be used 9626 // repeatedly where (and only where) multiple declarations are 9627 // allowed. 9628 // 9629 // That's in non-member contexts. 9630 if (!CurContext->getRedeclContext()->isRecord()) { 9631 // A dependent qualifier outside a class can only ever resolve to an 9632 // enumeration type. Therefore it conflicts with any other non-type 9633 // declaration in the same scope. 9634 // FIXME: How should we check for dependent type-type conflicts at block 9635 // scope? 9636 if (Qual->isDependent() && !HasTypenameKeyword) { 9637 for (auto *D : Prev) { 9638 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 9639 bool OldCouldBeEnumerator = 9640 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 9641 Diag(NameLoc, 9642 OldCouldBeEnumerator ? diag::err_redefinition 9643 : diag::err_redefinition_different_kind) 9644 << Prev.getLookupName(); 9645 Diag(D->getLocation(), diag::note_previous_definition); 9646 return true; 9647 } 9648 } 9649 } 9650 return false; 9651 } 9652 9653 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9654 NamedDecl *D = *I; 9655 9656 bool DTypename; 9657 NestedNameSpecifier *DQual; 9658 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9659 DTypename = UD->hasTypename(); 9660 DQual = UD->getQualifier(); 9661 } else if (UnresolvedUsingValueDecl *UD 9662 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9663 DTypename = false; 9664 DQual = UD->getQualifier(); 9665 } else if (UnresolvedUsingTypenameDecl *UD 9666 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9667 DTypename = true; 9668 DQual = UD->getQualifier(); 9669 } else continue; 9670 9671 // using decls differ if one says 'typename' and the other doesn't. 9672 // FIXME: non-dependent using decls? 9673 if (HasTypenameKeyword != DTypename) continue; 9674 9675 // using decls differ if they name different scopes (but note that 9676 // template instantiation can cause this check to trigger when it 9677 // didn't before instantiation). 9678 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9679 Context.getCanonicalNestedNameSpecifier(DQual)) 9680 continue; 9681 9682 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9683 Diag(D->getLocation(), diag::note_using_decl) << 1; 9684 return true; 9685 } 9686 9687 return false; 9688 } 9689 9690 9691 /// Checks that the given nested-name qualifier used in a using decl 9692 /// in the current context is appropriately related to the current 9693 /// scope. If an error is found, diagnoses it and returns true. 9694 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9695 bool HasTypename, 9696 const CXXScopeSpec &SS, 9697 const DeclarationNameInfo &NameInfo, 9698 SourceLocation NameLoc) { 9699 DeclContext *NamedContext = computeDeclContext(SS); 9700 9701 if (!CurContext->isRecord()) { 9702 // C++03 [namespace.udecl]p3: 9703 // C++0x [namespace.udecl]p8: 9704 // A using-declaration for a class member shall be a member-declaration. 9705 9706 // If we weren't able to compute a valid scope, it might validly be a 9707 // dependent class scope or a dependent enumeration unscoped scope. If 9708 // we have a 'typename' keyword, the scope must resolve to a class type. 9709 if ((HasTypename && !NamedContext) || 9710 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 9711 auto *RD = NamedContext 9712 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9713 : nullptr; 9714 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9715 RD = nullptr; 9716 9717 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9718 << SS.getRange(); 9719 9720 // If we have a complete, non-dependent source type, try to suggest a 9721 // way to get the same effect. 9722 if (!RD) 9723 return true; 9724 9725 // Find what this using-declaration was referring to. 9726 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9727 R.setHideTags(false); 9728 R.suppressDiagnostics(); 9729 LookupQualifiedName(R, RD); 9730 9731 if (R.getAsSingle<TypeDecl>()) { 9732 if (getLangOpts().CPlusPlus11) { 9733 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9734 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9735 << 0 // alias declaration 9736 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9737 NameInfo.getName().getAsString() + 9738 " = "); 9739 } else { 9740 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9741 SourceLocation InsertLoc = 9742 getLocForEndOfToken(NameInfo.getLocEnd()); 9743 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9744 << 1 // typedef declaration 9745 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9746 << FixItHint::CreateInsertion( 9747 InsertLoc, " " + NameInfo.getName().getAsString()); 9748 } 9749 } else if (R.getAsSingle<VarDecl>()) { 9750 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9751 // repeating the type of the static data member here. 9752 FixItHint FixIt; 9753 if (getLangOpts().CPlusPlus11) { 9754 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9755 FixIt = FixItHint::CreateReplacement( 9756 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9757 } 9758 9759 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9760 << 2 // reference declaration 9761 << FixIt; 9762 } else if (R.getAsSingle<EnumConstantDecl>()) { 9763 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9764 // repeating the type of the enumeration here, and we can't do so if 9765 // the type is anonymous. 9766 FixItHint FixIt; 9767 if (getLangOpts().CPlusPlus11) { 9768 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9769 FixIt = FixItHint::CreateReplacement( 9770 UsingLoc, 9771 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 9772 } 9773 9774 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9775 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 9776 << FixIt; 9777 } 9778 return true; 9779 } 9780 9781 // Otherwise, this might be valid. 9782 return false; 9783 } 9784 9785 // The current scope is a record. 9786 9787 // If the named context is dependent, we can't decide much. 9788 if (!NamedContext) { 9789 // FIXME: in C++0x, we can diagnose if we can prove that the 9790 // nested-name-specifier does not refer to a base class, which is 9791 // still possible in some cases. 9792 9793 // Otherwise we have to conservatively report that things might be 9794 // okay. 9795 return false; 9796 } 9797 9798 if (!NamedContext->isRecord()) { 9799 // Ideally this would point at the last name in the specifier, 9800 // but we don't have that level of source info. 9801 Diag(SS.getRange().getBegin(), 9802 diag::err_using_decl_nested_name_specifier_is_not_class) 9803 << SS.getScopeRep() << SS.getRange(); 9804 return true; 9805 } 9806 9807 if (!NamedContext->isDependentContext() && 9808 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 9809 return true; 9810 9811 if (getLangOpts().CPlusPlus11) { 9812 // C++11 [namespace.udecl]p3: 9813 // In a using-declaration used as a member-declaration, the 9814 // nested-name-specifier shall name a base class of the class 9815 // being defined. 9816 9817 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 9818 cast<CXXRecordDecl>(NamedContext))) { 9819 if (CurContext == NamedContext) { 9820 Diag(NameLoc, 9821 diag::err_using_decl_nested_name_specifier_is_current_class) 9822 << SS.getRange(); 9823 return true; 9824 } 9825 9826 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 9827 Diag(SS.getRange().getBegin(), 9828 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9829 << SS.getScopeRep() 9830 << cast<CXXRecordDecl>(CurContext) 9831 << SS.getRange(); 9832 } 9833 return true; 9834 } 9835 9836 return false; 9837 } 9838 9839 // C++03 [namespace.udecl]p4: 9840 // A using-declaration used as a member-declaration shall refer 9841 // to a member of a base class of the class being defined [etc.]. 9842 9843 // Salient point: SS doesn't have to name a base class as long as 9844 // lookup only finds members from base classes. Therefore we can 9845 // diagnose here only if we can prove that that can't happen, 9846 // i.e. if the class hierarchies provably don't intersect. 9847 9848 // TODO: it would be nice if "definitely valid" results were cached 9849 // in the UsingDecl and UsingShadowDecl so that these checks didn't 9850 // need to be repeated. 9851 9852 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 9853 auto Collect = [&Bases](const CXXRecordDecl *Base) { 9854 Bases.insert(Base); 9855 return true; 9856 }; 9857 9858 // Collect all bases. Return false if we find a dependent base. 9859 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 9860 return false; 9861 9862 // Returns true if the base is dependent or is one of the accumulated base 9863 // classes. 9864 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 9865 return !Bases.count(Base); 9866 }; 9867 9868 // Return false if the class has a dependent base or if it or one 9869 // of its bases is present in the base set of the current context. 9870 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 9871 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 9872 return false; 9873 9874 Diag(SS.getRange().getBegin(), 9875 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9876 << SS.getScopeRep() 9877 << cast<CXXRecordDecl>(CurContext) 9878 << SS.getRange(); 9879 9880 return true; 9881 } 9882 9883 Decl *Sema::ActOnAliasDeclaration(Scope *S, 9884 AccessSpecifier AS, 9885 MultiTemplateParamsArg TemplateParamLists, 9886 SourceLocation UsingLoc, 9887 UnqualifiedId &Name, 9888 AttributeList *AttrList, 9889 TypeResult Type, 9890 Decl *DeclFromDeclSpec) { 9891 // Skip up to the relevant declaration scope. 9892 while (S->isTemplateParamScope()) 9893 S = S->getParent(); 9894 assert((S->getFlags() & Scope::DeclScope) && 9895 "got alias-declaration outside of declaration scope"); 9896 9897 if (Type.isInvalid()) 9898 return nullptr; 9899 9900 bool Invalid = false; 9901 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 9902 TypeSourceInfo *TInfo = nullptr; 9903 GetTypeFromParser(Type.get(), &TInfo); 9904 9905 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 9906 return nullptr; 9907 9908 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 9909 UPPC_DeclarationType)) { 9910 Invalid = true; 9911 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9912 TInfo->getTypeLoc().getBeginLoc()); 9913 } 9914 9915 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 9916 LookupName(Previous, S); 9917 9918 // Warn about shadowing the name of a template parameter. 9919 if (Previous.isSingleResult() && 9920 Previous.getFoundDecl()->isTemplateParameter()) { 9921 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 9922 Previous.clear(); 9923 } 9924 9925 assert(Name.Kind == UnqualifiedId::IK_Identifier && 9926 "name in alias declaration must be an identifier"); 9927 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 9928 Name.StartLocation, 9929 Name.Identifier, TInfo); 9930 9931 NewTD->setAccess(AS); 9932 9933 if (Invalid) 9934 NewTD->setInvalidDecl(); 9935 9936 ProcessDeclAttributeList(S, NewTD, AttrList); 9937 9938 CheckTypedefForVariablyModifiedType(S, NewTD); 9939 Invalid |= NewTD->isInvalidDecl(); 9940 9941 bool Redeclaration = false; 9942 9943 NamedDecl *NewND; 9944 if (TemplateParamLists.size()) { 9945 TypeAliasTemplateDecl *OldDecl = nullptr; 9946 TemplateParameterList *OldTemplateParams = nullptr; 9947 9948 if (TemplateParamLists.size() != 1) { 9949 Diag(UsingLoc, diag::err_alias_template_extra_headers) 9950 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 9951 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 9952 } 9953 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 9954 9955 // Check that we can declare a template here. 9956 if (CheckTemplateDeclScope(S, TemplateParams)) 9957 return nullptr; 9958 9959 // Only consider previous declarations in the same scope. 9960 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 9961 /*ExplicitInstantiationOrSpecialization*/false); 9962 if (!Previous.empty()) { 9963 Redeclaration = true; 9964 9965 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 9966 if (!OldDecl && !Invalid) { 9967 Diag(UsingLoc, diag::err_redefinition_different_kind) 9968 << Name.Identifier; 9969 9970 NamedDecl *OldD = Previous.getRepresentativeDecl(); 9971 if (OldD->getLocation().isValid()) 9972 Diag(OldD->getLocation(), diag::note_previous_definition); 9973 9974 Invalid = true; 9975 } 9976 9977 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 9978 if (TemplateParameterListsAreEqual(TemplateParams, 9979 OldDecl->getTemplateParameters(), 9980 /*Complain=*/true, 9981 TPL_TemplateMatch)) 9982 OldTemplateParams = OldDecl->getTemplateParameters(); 9983 else 9984 Invalid = true; 9985 9986 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 9987 if (!Invalid && 9988 !Context.hasSameType(OldTD->getUnderlyingType(), 9989 NewTD->getUnderlyingType())) { 9990 // FIXME: The C++0x standard does not clearly say this is ill-formed, 9991 // but we can't reasonably accept it. 9992 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 9993 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 9994 if (OldTD->getLocation().isValid()) 9995 Diag(OldTD->getLocation(), diag::note_previous_definition); 9996 Invalid = true; 9997 } 9998 } 9999 } 10000 10001 // Merge any previous default template arguments into our parameters, 10002 // and check the parameter list. 10003 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10004 TPC_TypeAliasTemplate)) 10005 return nullptr; 10006 10007 TypeAliasTemplateDecl *NewDecl = 10008 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10009 Name.Identifier, TemplateParams, 10010 NewTD); 10011 NewTD->setDescribedAliasTemplate(NewDecl); 10012 10013 NewDecl->setAccess(AS); 10014 10015 if (Invalid) 10016 NewDecl->setInvalidDecl(); 10017 else if (OldDecl) 10018 NewDecl->setPreviousDecl(OldDecl); 10019 10020 NewND = NewDecl; 10021 } else { 10022 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10023 setTagNameForLinkagePurposes(TD, NewTD); 10024 handleTagNumbering(TD, S); 10025 } 10026 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10027 NewND = NewTD; 10028 } 10029 10030 PushOnScopeChains(NewND, S); 10031 ActOnDocumentableDecl(NewND); 10032 return NewND; 10033 } 10034 10035 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10036 SourceLocation AliasLoc, 10037 IdentifierInfo *Alias, CXXScopeSpec &SS, 10038 SourceLocation IdentLoc, 10039 IdentifierInfo *Ident) { 10040 10041 // Lookup the namespace name. 10042 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10043 LookupParsedName(R, S, &SS); 10044 10045 if (R.isAmbiguous()) 10046 return nullptr; 10047 10048 if (R.empty()) { 10049 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10050 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10051 return nullptr; 10052 } 10053 } 10054 assert(!R.isAmbiguous() && !R.empty()); 10055 NamedDecl *ND = R.getRepresentativeDecl(); 10056 10057 // Check if we have a previous declaration with the same name. 10058 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10059 ForRedeclaration); 10060 LookupName(PrevR, S); 10061 10062 // Check we're not shadowing a template parameter. 10063 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10064 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10065 PrevR.clear(); 10066 } 10067 10068 // Filter out any other lookup result from an enclosing scope. 10069 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10070 /*AllowInlineNamespace*/false); 10071 10072 // Find the previous declaration and check that we can redeclare it. 10073 NamespaceAliasDecl *Prev = nullptr; 10074 if (PrevR.isSingleResult()) { 10075 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10076 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10077 // We already have an alias with the same name that points to the same 10078 // namespace; check that it matches. 10079 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10080 Prev = AD; 10081 } else if (isVisible(PrevDecl)) { 10082 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10083 << Alias; 10084 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10085 << AD->getNamespace(); 10086 return nullptr; 10087 } 10088 } else if (isVisible(PrevDecl)) { 10089 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10090 ? diag::err_redefinition 10091 : diag::err_redefinition_different_kind; 10092 Diag(AliasLoc, DiagID) << Alias; 10093 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10094 return nullptr; 10095 } 10096 } 10097 10098 // The use of a nested name specifier may trigger deprecation warnings. 10099 DiagnoseUseOfDecl(ND, IdentLoc); 10100 10101 NamespaceAliasDecl *AliasDecl = 10102 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10103 Alias, SS.getWithLocInContext(Context), 10104 IdentLoc, ND); 10105 if (Prev) 10106 AliasDecl->setPreviousDecl(Prev); 10107 10108 PushOnScopeChains(AliasDecl, S); 10109 return AliasDecl; 10110 } 10111 10112 namespace { 10113 struct SpecialMemberExceptionSpecInfo 10114 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10115 SourceLocation Loc; 10116 Sema::ImplicitExceptionSpecification ExceptSpec; 10117 10118 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10119 Sema::CXXSpecialMember CSM, 10120 Sema::InheritedConstructorInfo *ICI, 10121 SourceLocation Loc) 10122 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10123 10124 bool visitBase(CXXBaseSpecifier *Base); 10125 bool visitField(FieldDecl *FD); 10126 10127 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10128 unsigned Quals); 10129 10130 void visitSubobjectCall(Subobject Subobj, 10131 Sema::SpecialMemberOverloadResult SMOR); 10132 }; 10133 } 10134 10135 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10136 auto *RT = Base->getType()->getAs<RecordType>(); 10137 if (!RT) 10138 return false; 10139 10140 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10141 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10142 if (auto *BaseCtor = SMOR.getMethod()) { 10143 visitSubobjectCall(Base, BaseCtor); 10144 return false; 10145 } 10146 10147 visitClassSubobject(BaseClass, Base, 0); 10148 return false; 10149 } 10150 10151 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10152 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10153 Expr *E = FD->getInClassInitializer(); 10154 if (!E) 10155 // FIXME: It's a little wasteful to build and throw away a 10156 // CXXDefaultInitExpr here. 10157 // FIXME: We should have a single context note pointing at Loc, and 10158 // this location should be MD->getLocation() instead, since that's 10159 // the location where we actually use the default init expression. 10160 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10161 if (E) 10162 ExceptSpec.CalledExpr(E); 10163 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10164 ->getAs<RecordType>()) { 10165 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10166 FD->getType().getCVRQualifiers()); 10167 } 10168 return false; 10169 } 10170 10171 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10172 Subobject Subobj, 10173 unsigned Quals) { 10174 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10175 bool IsMutable = Field && Field->isMutable(); 10176 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10177 } 10178 10179 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10180 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10181 // Note, if lookup fails, it doesn't matter what exception specification we 10182 // choose because the special member will be deleted. 10183 if (CXXMethodDecl *MD = SMOR.getMethod()) 10184 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10185 } 10186 10187 static Sema::ImplicitExceptionSpecification 10188 ComputeDefaultedSpecialMemberExceptionSpec( 10189 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10190 Sema::InheritedConstructorInfo *ICI) { 10191 CXXRecordDecl *ClassDecl = MD->getParent(); 10192 10193 // C++ [except.spec]p14: 10194 // An implicitly declared special member function (Clause 12) shall have an 10195 // exception-specification. [...] 10196 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10197 if (ClassDecl->isInvalidDecl()) 10198 return Info.ExceptSpec; 10199 10200 // C++1z [except.spec]p7: 10201 // [Look for exceptions thrown by] a constructor selected [...] to 10202 // initialize a potentially constructed subobject, 10203 // C++1z [except.spec]p8: 10204 // The exception specification for an implicitly-declared destructor, or a 10205 // destructor without a noexcept-specifier, is potentially-throwing if and 10206 // only if any of the destructors for any of its potentially constructed 10207 // subojects is potentially throwing. 10208 // FIXME: We respect the first rule but ignore the "potentially constructed" 10209 // in the second rule to resolve a core issue (no number yet) that would have 10210 // us reject: 10211 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10212 // struct B : A {}; 10213 // struct C : B { void f(); }; 10214 // ... due to giving B::~B() a non-throwing exception specification. 10215 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10216 : Info.VisitAllBases); 10217 10218 return Info.ExceptSpec; 10219 } 10220 10221 namespace { 10222 /// RAII object to register a special member as being currently declared. 10223 struct DeclaringSpecialMember { 10224 Sema &S; 10225 Sema::SpecialMemberDecl D; 10226 Sema::ContextRAII SavedContext; 10227 bool WasAlreadyBeingDeclared; 10228 10229 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10230 : S(S), D(RD, CSM), SavedContext(S, RD) { 10231 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10232 if (WasAlreadyBeingDeclared) 10233 // This almost never happens, but if it does, ensure that our cache 10234 // doesn't contain a stale result. 10235 S.SpecialMemberCache.clear(); 10236 else { 10237 // Register a note to be produced if we encounter an error while 10238 // declaring the special member. 10239 Sema::CodeSynthesisContext Ctx; 10240 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10241 // FIXME: We don't have a location to use here. Using the class's 10242 // location maintains the fiction that we declare all special members 10243 // with the class, but (1) it's not clear that lying about that helps our 10244 // users understand what's going on, and (2) there may be outer contexts 10245 // on the stack (some of which are relevant) and printing them exposes 10246 // our lies. 10247 Ctx.PointOfInstantiation = RD->getLocation(); 10248 Ctx.Entity = RD; 10249 Ctx.SpecialMember = CSM; 10250 S.pushCodeSynthesisContext(Ctx); 10251 } 10252 } 10253 ~DeclaringSpecialMember() { 10254 if (!WasAlreadyBeingDeclared) { 10255 S.SpecialMembersBeingDeclared.erase(D); 10256 S.popCodeSynthesisContext(); 10257 } 10258 } 10259 10260 /// \brief Are we already trying to declare this special member? 10261 bool isAlreadyBeingDeclared() const { 10262 return WasAlreadyBeingDeclared; 10263 } 10264 }; 10265 } 10266 10267 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10268 // Look up any existing declarations, but don't trigger declaration of all 10269 // implicit special members with this name. 10270 DeclarationName Name = FD->getDeclName(); 10271 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10272 ForRedeclaration); 10273 for (auto *D : FD->getParent()->lookup(Name)) 10274 if (auto *Acceptable = R.getAcceptableDecl(D)) 10275 R.addDecl(Acceptable); 10276 R.resolveKind(); 10277 R.suppressDiagnostics(); 10278 10279 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10280 } 10281 10282 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10283 CXXRecordDecl *ClassDecl) { 10284 // C++ [class.ctor]p5: 10285 // A default constructor for a class X is a constructor of class X 10286 // that can be called without an argument. If there is no 10287 // user-declared constructor for class X, a default constructor is 10288 // implicitly declared. An implicitly-declared default constructor 10289 // is an inline public member of its class. 10290 assert(ClassDecl->needsImplicitDefaultConstructor() && 10291 "Should not build implicit default constructor!"); 10292 10293 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10294 if (DSM.isAlreadyBeingDeclared()) 10295 return nullptr; 10296 10297 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10298 CXXDefaultConstructor, 10299 false); 10300 10301 // Create the actual constructor declaration. 10302 CanQualType ClassType 10303 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10304 SourceLocation ClassLoc = ClassDecl->getLocation(); 10305 DeclarationName Name 10306 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10307 DeclarationNameInfo NameInfo(Name, ClassLoc); 10308 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10309 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10310 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10311 /*isImplicitlyDeclared=*/true, Constexpr); 10312 DefaultCon->setAccess(AS_public); 10313 DefaultCon->setDefaulted(); 10314 10315 if (getLangOpts().CUDA) { 10316 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10317 DefaultCon, 10318 /* ConstRHS */ false, 10319 /* Diagnose */ false); 10320 } 10321 10322 // Build an exception specification pointing back at this constructor. 10323 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10324 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10325 10326 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10327 // constructors is easy to compute. 10328 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10329 10330 // Note that we have declared this constructor. 10331 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10332 10333 Scope *S = getScopeForContext(ClassDecl); 10334 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10335 10336 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10337 SetDeclDeleted(DefaultCon, ClassLoc); 10338 10339 if (S) 10340 PushOnScopeChains(DefaultCon, S, false); 10341 ClassDecl->addDecl(DefaultCon); 10342 10343 return DefaultCon; 10344 } 10345 10346 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10347 CXXConstructorDecl *Constructor) { 10348 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10349 !Constructor->doesThisDeclarationHaveABody() && 10350 !Constructor->isDeleted()) && 10351 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10352 10353 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10354 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10355 10356 SynthesizedFunctionScope Scope(*this, Constructor); 10357 DiagnosticErrorTrap Trap(Diags); 10358 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 10359 Trap.hasErrorOccurred()) { 10360 Diag(CurrentLocation, diag::note_member_synthesized_at) 10361 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 10362 Constructor->setInvalidDecl(); 10363 return; 10364 } 10365 10366 // The exception specification is needed because we are defining the 10367 // function. 10368 ResolveExceptionSpec(CurrentLocation, 10369 Constructor->getType()->castAs<FunctionProtoType>()); 10370 10371 SourceLocation Loc = Constructor->getLocEnd().isValid() 10372 ? Constructor->getLocEnd() 10373 : Constructor->getLocation(); 10374 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10375 10376 Constructor->markUsed(Context); 10377 MarkVTableUsed(CurrentLocation, ClassDecl); 10378 10379 if (ASTMutationListener *L = getASTMutationListener()) { 10380 L->CompletedImplicitDefinition(Constructor); 10381 } 10382 10383 DiagnoseUninitializedFields(*this, Constructor); 10384 } 10385 10386 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10387 // Perform any delayed checks on exception specifications. 10388 CheckDelayedMemberExceptionSpecs(); 10389 } 10390 10391 /// Find or create the fake constructor we synthesize to model constructing an 10392 /// object of a derived class via a constructor of a base class. 10393 CXXConstructorDecl * 10394 Sema::findInheritingConstructor(SourceLocation Loc, 10395 CXXConstructorDecl *BaseCtor, 10396 ConstructorUsingShadowDecl *Shadow) { 10397 CXXRecordDecl *Derived = Shadow->getParent(); 10398 SourceLocation UsingLoc = Shadow->getLocation(); 10399 10400 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10401 // For now we use the name of the base class constructor as a member of the 10402 // derived class to indicate a (fake) inherited constructor name. 10403 DeclarationName Name = BaseCtor->getDeclName(); 10404 10405 // Check to see if we already have a fake constructor for this inherited 10406 // constructor call. 10407 for (NamedDecl *Ctor : Derived->lookup(Name)) 10408 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10409 ->getInheritedConstructor() 10410 .getConstructor(), 10411 BaseCtor)) 10412 return cast<CXXConstructorDecl>(Ctor); 10413 10414 DeclarationNameInfo NameInfo(Name, UsingLoc); 10415 TypeSourceInfo *TInfo = 10416 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10417 FunctionProtoTypeLoc ProtoLoc = 10418 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10419 10420 // Check the inherited constructor is valid and find the list of base classes 10421 // from which it was inherited. 10422 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10423 10424 bool Constexpr = 10425 BaseCtor->isConstexpr() && 10426 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10427 false, BaseCtor, &ICI); 10428 10429 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10430 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10431 BaseCtor->isExplicit(), /*Inline=*/true, 10432 /*ImplicitlyDeclared=*/true, Constexpr, 10433 InheritedConstructor(Shadow, BaseCtor)); 10434 if (Shadow->isInvalidDecl()) 10435 DerivedCtor->setInvalidDecl(); 10436 10437 // Build an unevaluated exception specification for this fake constructor. 10438 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10439 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10440 EPI.ExceptionSpec.Type = EST_Unevaluated; 10441 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10442 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10443 FPT->getParamTypes(), EPI)); 10444 10445 // Build the parameter declarations. 10446 SmallVector<ParmVarDecl *, 16> ParamDecls; 10447 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10448 TypeSourceInfo *TInfo = 10449 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10450 ParmVarDecl *PD = ParmVarDecl::Create( 10451 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10452 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10453 PD->setScopeInfo(0, I); 10454 PD->setImplicit(); 10455 // Ensure attributes are propagated onto parameters (this matters for 10456 // format, pass_object_size, ...). 10457 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10458 ParamDecls.push_back(PD); 10459 ProtoLoc.setParam(I, PD); 10460 } 10461 10462 // Set up the new constructor. 10463 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10464 DerivedCtor->setAccess(BaseCtor->getAccess()); 10465 DerivedCtor->setParams(ParamDecls); 10466 Derived->addDecl(DerivedCtor); 10467 10468 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10469 SetDeclDeleted(DerivedCtor, UsingLoc); 10470 10471 return DerivedCtor; 10472 } 10473 10474 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10475 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10476 Ctor->getInheritedConstructor().getShadowDecl()); 10477 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10478 /*Diagnose*/true); 10479 } 10480 10481 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10482 CXXConstructorDecl *Constructor) { 10483 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10484 assert(Constructor->getInheritedConstructor() && 10485 !Constructor->doesThisDeclarationHaveABody() && 10486 !Constructor->isDeleted()); 10487 if (Constructor->isInvalidDecl()) 10488 return; 10489 10490 ConstructorUsingShadowDecl *Shadow = 10491 Constructor->getInheritedConstructor().getShadowDecl(); 10492 CXXConstructorDecl *InheritedCtor = 10493 Constructor->getInheritedConstructor().getConstructor(); 10494 10495 // [class.inhctor.init]p1: 10496 // initialization proceeds as if a defaulted default constructor is used to 10497 // initialize the D object and each base class subobject from which the 10498 // constructor was inherited 10499 10500 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10501 CXXRecordDecl *RD = Shadow->getParent(); 10502 SourceLocation InitLoc = Shadow->getLocation(); 10503 10504 // Initializations are performed "as if by a defaulted default constructor", 10505 // so enter the appropriate scope. 10506 SynthesizedFunctionScope Scope(*this, Constructor); 10507 DiagnosticErrorTrap Trap(Diags); 10508 10509 // Build explicit initializers for all base classes from which the 10510 // constructor was inherited. 10511 SmallVector<CXXCtorInitializer*, 8> Inits; 10512 for (bool VBase : {false, true}) { 10513 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10514 if (B.isVirtual() != VBase) 10515 continue; 10516 10517 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10518 if (!BaseRD) 10519 continue; 10520 10521 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10522 if (!BaseCtor.first) 10523 continue; 10524 10525 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10526 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10527 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10528 10529 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10530 Inits.push_back(new (Context) CXXCtorInitializer( 10531 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10532 SourceLocation())); 10533 } 10534 } 10535 10536 // We now proceed as if for a defaulted default constructor, with the relevant 10537 // initializers replaced. 10538 10539 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits); 10540 if (HadError || Trap.hasErrorOccurred()) { 10541 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD; 10542 Constructor->setInvalidDecl(); 10543 return; 10544 } 10545 10546 // The exception specification is needed because we are defining the 10547 // function. 10548 ResolveExceptionSpec(CurrentLocation, 10549 Constructor->getType()->castAs<FunctionProtoType>()); 10550 10551 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10552 10553 Constructor->markUsed(Context); 10554 MarkVTableUsed(CurrentLocation, ClassDecl); 10555 10556 if (ASTMutationListener *L = getASTMutationListener()) { 10557 L->CompletedImplicitDefinition(Constructor); 10558 } 10559 10560 DiagnoseUninitializedFields(*this, Constructor); 10561 } 10562 10563 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10564 // C++ [class.dtor]p2: 10565 // If a class has no user-declared destructor, a destructor is 10566 // declared implicitly. An implicitly-declared destructor is an 10567 // inline public member of its class. 10568 assert(ClassDecl->needsImplicitDestructor()); 10569 10570 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10571 if (DSM.isAlreadyBeingDeclared()) 10572 return nullptr; 10573 10574 // Create the actual destructor declaration. 10575 CanQualType ClassType 10576 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10577 SourceLocation ClassLoc = ClassDecl->getLocation(); 10578 DeclarationName Name 10579 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10580 DeclarationNameInfo NameInfo(Name, ClassLoc); 10581 CXXDestructorDecl *Destructor 10582 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10583 QualType(), nullptr, /*isInline=*/true, 10584 /*isImplicitlyDeclared=*/true); 10585 Destructor->setAccess(AS_public); 10586 Destructor->setDefaulted(); 10587 10588 if (getLangOpts().CUDA) { 10589 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10590 Destructor, 10591 /* ConstRHS */ false, 10592 /* Diagnose */ false); 10593 } 10594 10595 // Build an exception specification pointing back at this destructor. 10596 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10597 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10598 10599 // We don't need to use SpecialMemberIsTrivial here; triviality for 10600 // destructors is easy to compute. 10601 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10602 10603 // Note that we have declared this destructor. 10604 ++ASTContext::NumImplicitDestructorsDeclared; 10605 10606 Scope *S = getScopeForContext(ClassDecl); 10607 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10608 10609 // We can't check whether an implicit destructor is deleted before we complete 10610 // the definition of the class, because its validity depends on the alignment 10611 // of the class. We'll check this from ActOnFields once the class is complete. 10612 if (ClassDecl->isCompleteDefinition() && 10613 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10614 SetDeclDeleted(Destructor, ClassLoc); 10615 10616 // Introduce this destructor into its scope. 10617 if (S) 10618 PushOnScopeChains(Destructor, S, false); 10619 ClassDecl->addDecl(Destructor); 10620 10621 return Destructor; 10622 } 10623 10624 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10625 CXXDestructorDecl *Destructor) { 10626 assert((Destructor->isDefaulted() && 10627 !Destructor->doesThisDeclarationHaveABody() && 10628 !Destructor->isDeleted()) && 10629 "DefineImplicitDestructor - call it for implicit default dtor"); 10630 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10631 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10632 10633 if (Destructor->isInvalidDecl()) 10634 return; 10635 10636 SynthesizedFunctionScope Scope(*this, Destructor); 10637 10638 DiagnosticErrorTrap Trap(Diags); 10639 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10640 Destructor->getParent()); 10641 10642 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 10643 Diag(CurrentLocation, diag::note_member_synthesized_at) 10644 << CXXDestructor << Context.getTagDeclType(ClassDecl); 10645 10646 Destructor->setInvalidDecl(); 10647 return; 10648 } 10649 10650 // The exception specification is needed because we are defining the 10651 // function. 10652 ResolveExceptionSpec(CurrentLocation, 10653 Destructor->getType()->castAs<FunctionProtoType>()); 10654 10655 SourceLocation Loc = Destructor->getLocEnd().isValid() 10656 ? Destructor->getLocEnd() 10657 : Destructor->getLocation(); 10658 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10659 Destructor->markUsed(Context); 10660 MarkVTableUsed(CurrentLocation, ClassDecl); 10661 10662 if (ASTMutationListener *L = getASTMutationListener()) { 10663 L->CompletedImplicitDefinition(Destructor); 10664 } 10665 } 10666 10667 /// \brief Perform any semantic analysis which needs to be delayed until all 10668 /// pending class member declarations have been parsed. 10669 void Sema::ActOnFinishCXXMemberDecls() { 10670 // If the context is an invalid C++ class, just suppress these checks. 10671 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10672 if (Record->isInvalidDecl()) { 10673 DelayedDefaultedMemberExceptionSpecs.clear(); 10674 DelayedExceptionSpecChecks.clear(); 10675 return; 10676 } 10677 checkForMultipleExportedDefaultConstructors(*this, Record); 10678 } 10679 } 10680 10681 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10682 referenceDLLExportedClassMethods(); 10683 } 10684 10685 void Sema::referenceDLLExportedClassMethods() { 10686 if (!DelayedDllExportClasses.empty()) { 10687 // Calling ReferenceDllExportedMethods might cause the current function to 10688 // be called again, so use a local copy of DelayedDllExportClasses. 10689 SmallVector<CXXRecordDecl *, 4> WorkList; 10690 std::swap(DelayedDllExportClasses, WorkList); 10691 for (CXXRecordDecl *Class : WorkList) 10692 ReferenceDllExportedMethods(*this, Class); 10693 } 10694 } 10695 10696 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10697 CXXDestructorDecl *Destructor) { 10698 assert(getLangOpts().CPlusPlus11 && 10699 "adjusting dtor exception specs was introduced in c++11"); 10700 10701 // C++11 [class.dtor]p3: 10702 // A declaration of a destructor that does not have an exception- 10703 // specification is implicitly considered to have the same exception- 10704 // specification as an implicit declaration. 10705 const FunctionProtoType *DtorType = Destructor->getType()-> 10706 getAs<FunctionProtoType>(); 10707 if (DtorType->hasExceptionSpec()) 10708 return; 10709 10710 // Replace the destructor's type, building off the existing one. Fortunately, 10711 // the only thing of interest in the destructor type is its extended info. 10712 // The return and arguments are fixed. 10713 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10714 EPI.ExceptionSpec.Type = EST_Unevaluated; 10715 EPI.ExceptionSpec.SourceDecl = Destructor; 10716 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10717 10718 // FIXME: If the destructor has a body that could throw, and the newly created 10719 // spec doesn't allow exceptions, we should emit a warning, because this 10720 // change in behavior can break conforming C++03 programs at runtime. 10721 // However, we don't have a body or an exception specification yet, so it 10722 // needs to be done somewhere else. 10723 } 10724 10725 namespace { 10726 /// \brief An abstract base class for all helper classes used in building the 10727 // copy/move operators. These classes serve as factory functions and help us 10728 // avoid using the same Expr* in the AST twice. 10729 class ExprBuilder { 10730 ExprBuilder(const ExprBuilder&) = delete; 10731 ExprBuilder &operator=(const ExprBuilder&) = delete; 10732 10733 protected: 10734 static Expr *assertNotNull(Expr *E) { 10735 assert(E && "Expression construction must not fail."); 10736 return E; 10737 } 10738 10739 public: 10740 ExprBuilder() {} 10741 virtual ~ExprBuilder() {} 10742 10743 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10744 }; 10745 10746 class RefBuilder: public ExprBuilder { 10747 VarDecl *Var; 10748 QualType VarType; 10749 10750 public: 10751 Expr *build(Sema &S, SourceLocation Loc) const override { 10752 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10753 } 10754 10755 RefBuilder(VarDecl *Var, QualType VarType) 10756 : Var(Var), VarType(VarType) {} 10757 }; 10758 10759 class ThisBuilder: public ExprBuilder { 10760 public: 10761 Expr *build(Sema &S, SourceLocation Loc) const override { 10762 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 10763 } 10764 }; 10765 10766 class CastBuilder: public ExprBuilder { 10767 const ExprBuilder &Builder; 10768 QualType Type; 10769 ExprValueKind Kind; 10770 const CXXCastPath &Path; 10771 10772 public: 10773 Expr *build(Sema &S, SourceLocation Loc) const override { 10774 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 10775 CK_UncheckedDerivedToBase, Kind, 10776 &Path).get()); 10777 } 10778 10779 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 10780 const CXXCastPath &Path) 10781 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 10782 }; 10783 10784 class DerefBuilder: public ExprBuilder { 10785 const ExprBuilder &Builder; 10786 10787 public: 10788 Expr *build(Sema &S, SourceLocation Loc) const override { 10789 return assertNotNull( 10790 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 10791 } 10792 10793 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10794 }; 10795 10796 class MemberBuilder: public ExprBuilder { 10797 const ExprBuilder &Builder; 10798 QualType Type; 10799 CXXScopeSpec SS; 10800 bool IsArrow; 10801 LookupResult &MemberLookup; 10802 10803 public: 10804 Expr *build(Sema &S, SourceLocation Loc) const override { 10805 return assertNotNull(S.BuildMemberReferenceExpr( 10806 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 10807 nullptr, MemberLookup, nullptr, nullptr).get()); 10808 } 10809 10810 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 10811 LookupResult &MemberLookup) 10812 : Builder(Builder), Type(Type), IsArrow(IsArrow), 10813 MemberLookup(MemberLookup) {} 10814 }; 10815 10816 class MoveCastBuilder: public ExprBuilder { 10817 const ExprBuilder &Builder; 10818 10819 public: 10820 Expr *build(Sema &S, SourceLocation Loc) const override { 10821 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 10822 } 10823 10824 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10825 }; 10826 10827 class LvalueConvBuilder: public ExprBuilder { 10828 const ExprBuilder &Builder; 10829 10830 public: 10831 Expr *build(Sema &S, SourceLocation Loc) const override { 10832 return assertNotNull( 10833 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 10834 } 10835 10836 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10837 }; 10838 10839 class SubscriptBuilder: public ExprBuilder { 10840 const ExprBuilder &Base; 10841 const ExprBuilder &Index; 10842 10843 public: 10844 Expr *build(Sema &S, SourceLocation Loc) const override { 10845 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 10846 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 10847 } 10848 10849 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 10850 : Base(Base), Index(Index) {} 10851 }; 10852 10853 } // end anonymous namespace 10854 10855 /// When generating a defaulted copy or move assignment operator, if a field 10856 /// should be copied with __builtin_memcpy rather than via explicit assignments, 10857 /// do so. This optimization only applies for arrays of scalars, and for arrays 10858 /// of class type where the selected copy/move-assignment operator is trivial. 10859 static StmtResult 10860 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 10861 const ExprBuilder &ToB, const ExprBuilder &FromB) { 10862 // Compute the size of the memory buffer to be copied. 10863 QualType SizeType = S.Context.getSizeType(); 10864 llvm::APInt Size(S.Context.getTypeSize(SizeType), 10865 S.Context.getTypeSizeInChars(T).getQuantity()); 10866 10867 // Take the address of the field references for "from" and "to". We 10868 // directly construct UnaryOperators here because semantic analysis 10869 // does not permit us to take the address of an xvalue. 10870 Expr *From = FromB.build(S, Loc); 10871 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 10872 S.Context.getPointerType(From->getType()), 10873 VK_RValue, OK_Ordinary, Loc); 10874 Expr *To = ToB.build(S, Loc); 10875 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 10876 S.Context.getPointerType(To->getType()), 10877 VK_RValue, OK_Ordinary, Loc); 10878 10879 const Type *E = T->getBaseElementTypeUnsafe(); 10880 bool NeedsCollectableMemCpy = 10881 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 10882 10883 // Create a reference to the __builtin_objc_memmove_collectable function 10884 StringRef MemCpyName = NeedsCollectableMemCpy ? 10885 "__builtin_objc_memmove_collectable" : 10886 "__builtin_memcpy"; 10887 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 10888 Sema::LookupOrdinaryName); 10889 S.LookupName(R, S.TUScope, true); 10890 10891 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 10892 if (!MemCpy) 10893 // Something went horribly wrong earlier, and we will have complained 10894 // about it. 10895 return StmtError(); 10896 10897 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 10898 VK_RValue, Loc, nullptr); 10899 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 10900 10901 Expr *CallArgs[] = { 10902 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 10903 }; 10904 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 10905 Loc, CallArgs, Loc); 10906 10907 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 10908 return Call.getAs<Stmt>(); 10909 } 10910 10911 /// \brief Builds a statement that copies/moves the given entity from \p From to 10912 /// \c To. 10913 /// 10914 /// This routine is used to copy/move the members of a class with an 10915 /// implicitly-declared copy/move assignment operator. When the entities being 10916 /// copied are arrays, this routine builds for loops to copy them. 10917 /// 10918 /// \param S The Sema object used for type-checking. 10919 /// 10920 /// \param Loc The location where the implicit copy/move is being generated. 10921 /// 10922 /// \param T The type of the expressions being copied/moved. Both expressions 10923 /// must have this type. 10924 /// 10925 /// \param To The expression we are copying/moving to. 10926 /// 10927 /// \param From The expression we are copying/moving from. 10928 /// 10929 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 10930 /// Otherwise, it's a non-static member subobject. 10931 /// 10932 /// \param Copying Whether we're copying or moving. 10933 /// 10934 /// \param Depth Internal parameter recording the depth of the recursion. 10935 /// 10936 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 10937 /// if a memcpy should be used instead. 10938 static StmtResult 10939 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 10940 const ExprBuilder &To, const ExprBuilder &From, 10941 bool CopyingBaseSubobject, bool Copying, 10942 unsigned Depth = 0) { 10943 // C++11 [class.copy]p28: 10944 // Each subobject is assigned in the manner appropriate to its type: 10945 // 10946 // - if the subobject is of class type, as if by a call to operator= with 10947 // the subobject as the object expression and the corresponding 10948 // subobject of x as a single function argument (as if by explicit 10949 // qualification; that is, ignoring any possible virtual overriding 10950 // functions in more derived classes); 10951 // 10952 // C++03 [class.copy]p13: 10953 // - if the subobject is of class type, the copy assignment operator for 10954 // the class is used (as if by explicit qualification; that is, 10955 // ignoring any possible virtual overriding functions in more derived 10956 // classes); 10957 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 10958 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 10959 10960 // Look for operator=. 10961 DeclarationName Name 10962 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10963 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 10964 S.LookupQualifiedName(OpLookup, ClassDecl, false); 10965 10966 // Prior to C++11, filter out any result that isn't a copy/move-assignment 10967 // operator. 10968 if (!S.getLangOpts().CPlusPlus11) { 10969 LookupResult::Filter F = OpLookup.makeFilter(); 10970 while (F.hasNext()) { 10971 NamedDecl *D = F.next(); 10972 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 10973 if (Method->isCopyAssignmentOperator() || 10974 (!Copying && Method->isMoveAssignmentOperator())) 10975 continue; 10976 10977 F.erase(); 10978 } 10979 F.done(); 10980 } 10981 10982 // Suppress the protected check (C++ [class.protected]) for each of the 10983 // assignment operators we found. This strange dance is required when 10984 // we're assigning via a base classes's copy-assignment operator. To 10985 // ensure that we're getting the right base class subobject (without 10986 // ambiguities), we need to cast "this" to that subobject type; to 10987 // ensure that we don't go through the virtual call mechanism, we need 10988 // to qualify the operator= name with the base class (see below). However, 10989 // this means that if the base class has a protected copy assignment 10990 // operator, the protected member access check will fail. So, we 10991 // rewrite "protected" access to "public" access in this case, since we 10992 // know by construction that we're calling from a derived class. 10993 if (CopyingBaseSubobject) { 10994 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 10995 L != LEnd; ++L) { 10996 if (L.getAccess() == AS_protected) 10997 L.setAccess(AS_public); 10998 } 10999 } 11000 11001 // Create the nested-name-specifier that will be used to qualify the 11002 // reference to operator=; this is required to suppress the virtual 11003 // call mechanism. 11004 CXXScopeSpec SS; 11005 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11006 SS.MakeTrivial(S.Context, 11007 NestedNameSpecifier::Create(S.Context, nullptr, false, 11008 CanonicalT), 11009 Loc); 11010 11011 // Create the reference to operator=. 11012 ExprResult OpEqualRef 11013 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11014 SS, /*TemplateKWLoc=*/SourceLocation(), 11015 /*FirstQualifierInScope=*/nullptr, 11016 OpLookup, 11017 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11018 /*SuppressQualifierCheck=*/true); 11019 if (OpEqualRef.isInvalid()) 11020 return StmtError(); 11021 11022 // Build the call to the assignment operator. 11023 11024 Expr *FromInst = From.build(S, Loc); 11025 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11026 OpEqualRef.getAs<Expr>(), 11027 Loc, FromInst, Loc); 11028 if (Call.isInvalid()) 11029 return StmtError(); 11030 11031 // If we built a call to a trivial 'operator=' while copying an array, 11032 // bail out. We'll replace the whole shebang with a memcpy. 11033 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11034 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11035 return StmtResult((Stmt*)nullptr); 11036 11037 // Convert to an expression-statement, and clean up any produced 11038 // temporaries. 11039 return S.ActOnExprStmt(Call); 11040 } 11041 11042 // - if the subobject is of scalar type, the built-in assignment 11043 // operator is used. 11044 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11045 if (!ArrayTy) { 11046 ExprResult Assignment = S.CreateBuiltinBinOp( 11047 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11048 if (Assignment.isInvalid()) 11049 return StmtError(); 11050 return S.ActOnExprStmt(Assignment); 11051 } 11052 11053 // - if the subobject is an array, each element is assigned, in the 11054 // manner appropriate to the element type; 11055 11056 // Construct a loop over the array bounds, e.g., 11057 // 11058 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11059 // 11060 // that will copy each of the array elements. 11061 QualType SizeType = S.Context.getSizeType(); 11062 11063 // Create the iteration variable. 11064 IdentifierInfo *IterationVarName = nullptr; 11065 { 11066 SmallString<8> Str; 11067 llvm::raw_svector_ostream OS(Str); 11068 OS << "__i" << Depth; 11069 IterationVarName = &S.Context.Idents.get(OS.str()); 11070 } 11071 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11072 IterationVarName, SizeType, 11073 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11074 SC_None); 11075 11076 // Initialize the iteration variable to zero. 11077 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11078 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11079 11080 // Creates a reference to the iteration variable. 11081 RefBuilder IterationVarRef(IterationVar, SizeType); 11082 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11083 11084 // Create the DeclStmt that holds the iteration variable. 11085 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11086 11087 // Subscript the "from" and "to" expressions with the iteration variable. 11088 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11089 MoveCastBuilder FromIndexMove(FromIndexCopy); 11090 const ExprBuilder *FromIndex; 11091 if (Copying) 11092 FromIndex = &FromIndexCopy; 11093 else 11094 FromIndex = &FromIndexMove; 11095 11096 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11097 11098 // Build the copy/move for an individual element of the array. 11099 StmtResult Copy = 11100 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11101 ToIndex, *FromIndex, CopyingBaseSubobject, 11102 Copying, Depth + 1); 11103 // Bail out if copying fails or if we determined that we should use memcpy. 11104 if (Copy.isInvalid() || !Copy.get()) 11105 return Copy; 11106 11107 // Create the comparison against the array bound. 11108 llvm::APInt Upper 11109 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11110 Expr *Comparison 11111 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11112 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11113 BO_NE, S.Context.BoolTy, 11114 VK_RValue, OK_Ordinary, Loc, false); 11115 11116 // Create the pre-increment of the iteration variable. 11117 Expr *Increment 11118 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 11119 SizeType, VK_LValue, OK_Ordinary, Loc); 11120 11121 // Construct the loop that copies all elements of this array. 11122 return S.ActOnForStmt( 11123 Loc, Loc, InitStmt, 11124 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11125 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11126 } 11127 11128 static StmtResult 11129 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11130 const ExprBuilder &To, const ExprBuilder &From, 11131 bool CopyingBaseSubobject, bool Copying) { 11132 // Maybe we should use a memcpy? 11133 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11134 T.isTriviallyCopyableType(S.Context)) 11135 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11136 11137 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11138 CopyingBaseSubobject, 11139 Copying, 0)); 11140 11141 // If we ended up picking a trivial assignment operator for an array of a 11142 // non-trivially-copyable class type, just emit a memcpy. 11143 if (!Result.isInvalid() && !Result.get()) 11144 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11145 11146 return Result; 11147 } 11148 11149 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11150 // Note: The following rules are largely analoguous to the copy 11151 // constructor rules. Note that virtual bases are not taken into account 11152 // for determining the argument type of the operator. Note also that 11153 // operators taking an object instead of a reference are allowed. 11154 assert(ClassDecl->needsImplicitCopyAssignment()); 11155 11156 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11157 if (DSM.isAlreadyBeingDeclared()) 11158 return nullptr; 11159 11160 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11161 QualType RetType = Context.getLValueReferenceType(ArgType); 11162 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11163 if (Const) 11164 ArgType = ArgType.withConst(); 11165 ArgType = Context.getLValueReferenceType(ArgType); 11166 11167 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11168 CXXCopyAssignment, 11169 Const); 11170 11171 // An implicitly-declared copy assignment operator is an inline public 11172 // member of its class. 11173 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11174 SourceLocation ClassLoc = ClassDecl->getLocation(); 11175 DeclarationNameInfo NameInfo(Name, ClassLoc); 11176 CXXMethodDecl *CopyAssignment = 11177 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11178 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11179 /*isInline=*/true, Constexpr, SourceLocation()); 11180 CopyAssignment->setAccess(AS_public); 11181 CopyAssignment->setDefaulted(); 11182 CopyAssignment->setImplicit(); 11183 11184 if (getLangOpts().CUDA) { 11185 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11186 CopyAssignment, 11187 /* ConstRHS */ Const, 11188 /* Diagnose */ false); 11189 } 11190 11191 // Build an exception specification pointing back at this member. 11192 FunctionProtoType::ExtProtoInfo EPI = 11193 getImplicitMethodEPI(*this, CopyAssignment); 11194 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11195 11196 // Add the parameter to the operator. 11197 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11198 ClassLoc, ClassLoc, 11199 /*Id=*/nullptr, ArgType, 11200 /*TInfo=*/nullptr, SC_None, 11201 nullptr); 11202 CopyAssignment->setParams(FromParam); 11203 11204 CopyAssignment->setTrivial( 11205 ClassDecl->needsOverloadResolutionForCopyAssignment() 11206 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11207 : ClassDecl->hasTrivialCopyAssignment()); 11208 11209 // Note that we have added this copy-assignment operator. 11210 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11211 11212 Scope *S = getScopeForContext(ClassDecl); 11213 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11214 11215 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11216 SetDeclDeleted(CopyAssignment, ClassLoc); 11217 11218 if (S) 11219 PushOnScopeChains(CopyAssignment, S, false); 11220 ClassDecl->addDecl(CopyAssignment); 11221 11222 return CopyAssignment; 11223 } 11224 11225 /// Diagnose an implicit copy operation for a class which is odr-used, but 11226 /// which is deprecated because the class has a user-declared copy constructor, 11227 /// copy assignment operator, or destructor. 11228 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 11229 SourceLocation UseLoc) { 11230 assert(CopyOp->isImplicit()); 11231 11232 CXXRecordDecl *RD = CopyOp->getParent(); 11233 CXXMethodDecl *UserDeclaredOperation = nullptr; 11234 11235 // In Microsoft mode, assignment operations don't affect constructors and 11236 // vice versa. 11237 if (RD->hasUserDeclaredDestructor()) { 11238 UserDeclaredOperation = RD->getDestructor(); 11239 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11240 RD->hasUserDeclaredCopyConstructor() && 11241 !S.getLangOpts().MSVCCompat) { 11242 // Find any user-declared copy constructor. 11243 for (auto *I : RD->ctors()) { 11244 if (I->isCopyConstructor()) { 11245 UserDeclaredOperation = I; 11246 break; 11247 } 11248 } 11249 assert(UserDeclaredOperation); 11250 } else if (isa<CXXConstructorDecl>(CopyOp) && 11251 RD->hasUserDeclaredCopyAssignment() && 11252 !S.getLangOpts().MSVCCompat) { 11253 // Find any user-declared move assignment operator. 11254 for (auto *I : RD->methods()) { 11255 if (I->isCopyAssignmentOperator()) { 11256 UserDeclaredOperation = I; 11257 break; 11258 } 11259 } 11260 assert(UserDeclaredOperation); 11261 } 11262 11263 if (UserDeclaredOperation) { 11264 S.Diag(UserDeclaredOperation->getLocation(), 11265 diag::warn_deprecated_copy_operation) 11266 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11267 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11268 S.Diag(UseLoc, diag::note_member_synthesized_at) 11269 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 11270 : Sema::CXXCopyAssignment) 11271 << RD; 11272 } 11273 } 11274 11275 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11276 CXXMethodDecl *CopyAssignOperator) { 11277 assert((CopyAssignOperator->isDefaulted() && 11278 CopyAssignOperator->isOverloadedOperator() && 11279 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11280 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11281 !CopyAssignOperator->isDeleted()) && 11282 "DefineImplicitCopyAssignment called for wrong function"); 11283 11284 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11285 11286 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 11287 CopyAssignOperator->setInvalidDecl(); 11288 return; 11289 } 11290 11291 // C++11 [class.copy]p18: 11292 // The [definition of an implicitly declared copy assignment operator] is 11293 // deprecated if the class has a user-declared copy constructor or a 11294 // user-declared destructor. 11295 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11296 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 11297 11298 CopyAssignOperator->markUsed(Context); 11299 11300 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11301 DiagnosticErrorTrap Trap(Diags); 11302 11303 // C++0x [class.copy]p30: 11304 // The implicitly-defined or explicitly-defaulted copy assignment operator 11305 // for a non-union class X performs memberwise copy assignment of its 11306 // subobjects. The direct base classes of X are assigned first, in the 11307 // order of their declaration in the base-specifier-list, and then the 11308 // immediate non-static data members of X are assigned, in the order in 11309 // which they were declared in the class definition. 11310 11311 // The statements that form the synthesized function body. 11312 SmallVector<Stmt*, 8> Statements; 11313 11314 // The parameter for the "other" object, which we are copying from. 11315 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11316 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11317 QualType OtherRefType = Other->getType(); 11318 if (const LValueReferenceType *OtherRef 11319 = OtherRefType->getAs<LValueReferenceType>()) { 11320 OtherRefType = OtherRef->getPointeeType(); 11321 OtherQuals = OtherRefType.getQualifiers(); 11322 } 11323 11324 // Our location for everything implicitly-generated. 11325 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11326 ? CopyAssignOperator->getLocEnd() 11327 : CopyAssignOperator->getLocation(); 11328 11329 // Builds a DeclRefExpr for the "other" object. 11330 RefBuilder OtherRef(Other, OtherRefType); 11331 11332 // Builds the "this" pointer. 11333 ThisBuilder This; 11334 11335 // Assign base classes. 11336 bool Invalid = false; 11337 for (auto &Base : ClassDecl->bases()) { 11338 // Form the assignment: 11339 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11340 QualType BaseType = Base.getType().getUnqualifiedType(); 11341 if (!BaseType->isRecordType()) { 11342 Invalid = true; 11343 continue; 11344 } 11345 11346 CXXCastPath BasePath; 11347 BasePath.push_back(&Base); 11348 11349 // Construct the "from" expression, which is an implicit cast to the 11350 // appropriately-qualified base type. 11351 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11352 VK_LValue, BasePath); 11353 11354 // Dereference "this". 11355 DerefBuilder DerefThis(This); 11356 CastBuilder To(DerefThis, 11357 Context.getCVRQualifiedType( 11358 BaseType, CopyAssignOperator->getTypeQualifiers()), 11359 VK_LValue, BasePath); 11360 11361 // Build the copy. 11362 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11363 To, From, 11364 /*CopyingBaseSubobject=*/true, 11365 /*Copying=*/true); 11366 if (Copy.isInvalid()) { 11367 Diag(CurrentLocation, diag::note_member_synthesized_at) 11368 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11369 CopyAssignOperator->setInvalidDecl(); 11370 return; 11371 } 11372 11373 // Success! Record the copy. 11374 Statements.push_back(Copy.getAs<Expr>()); 11375 } 11376 11377 // Assign non-static members. 11378 for (auto *Field : ClassDecl->fields()) { 11379 // FIXME: We should form some kind of AST representation for the implied 11380 // memcpy in a union copy operation. 11381 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11382 continue; 11383 11384 if (Field->isInvalidDecl()) { 11385 Invalid = true; 11386 continue; 11387 } 11388 11389 // Check for members of reference type; we can't copy those. 11390 if (Field->getType()->isReferenceType()) { 11391 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11392 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11393 Diag(Field->getLocation(), diag::note_declared_at); 11394 Diag(CurrentLocation, diag::note_member_synthesized_at) 11395 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11396 Invalid = true; 11397 continue; 11398 } 11399 11400 // Check for members of const-qualified, non-class type. 11401 QualType BaseType = Context.getBaseElementType(Field->getType()); 11402 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11403 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11404 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11405 Diag(Field->getLocation(), diag::note_declared_at); 11406 Diag(CurrentLocation, diag::note_member_synthesized_at) 11407 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11408 Invalid = true; 11409 continue; 11410 } 11411 11412 // Suppress assigning zero-width bitfields. 11413 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11414 continue; 11415 11416 QualType FieldType = Field->getType().getNonReferenceType(); 11417 if (FieldType->isIncompleteArrayType()) { 11418 assert(ClassDecl->hasFlexibleArrayMember() && 11419 "Incomplete array type is not valid"); 11420 continue; 11421 } 11422 11423 // Build references to the field in the object we're copying from and to. 11424 CXXScopeSpec SS; // Intentionally empty 11425 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11426 LookupMemberName); 11427 MemberLookup.addDecl(Field); 11428 MemberLookup.resolveKind(); 11429 11430 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11431 11432 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11433 11434 // Build the copy of this field. 11435 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11436 To, From, 11437 /*CopyingBaseSubobject=*/false, 11438 /*Copying=*/true); 11439 if (Copy.isInvalid()) { 11440 Diag(CurrentLocation, diag::note_member_synthesized_at) 11441 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11442 CopyAssignOperator->setInvalidDecl(); 11443 return; 11444 } 11445 11446 // Success! Record the copy. 11447 Statements.push_back(Copy.getAs<Stmt>()); 11448 } 11449 11450 if (!Invalid) { 11451 // Add a "return *this;" 11452 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11453 11454 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11455 if (Return.isInvalid()) 11456 Invalid = true; 11457 else { 11458 Statements.push_back(Return.getAs<Stmt>()); 11459 11460 if (Trap.hasErrorOccurred()) { 11461 Diag(CurrentLocation, diag::note_member_synthesized_at) 11462 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11463 Invalid = true; 11464 } 11465 } 11466 } 11467 11468 // The exception specification is needed because we are defining the 11469 // function. 11470 ResolveExceptionSpec(CurrentLocation, 11471 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11472 11473 if (Invalid) { 11474 CopyAssignOperator->setInvalidDecl(); 11475 return; 11476 } 11477 11478 StmtResult Body; 11479 { 11480 CompoundScopeRAII CompoundScope(*this); 11481 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11482 /*isStmtExpr=*/false); 11483 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11484 } 11485 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11486 11487 if (ASTMutationListener *L = getASTMutationListener()) { 11488 L->CompletedImplicitDefinition(CopyAssignOperator); 11489 } 11490 } 11491 11492 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11493 assert(ClassDecl->needsImplicitMoveAssignment()); 11494 11495 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11496 if (DSM.isAlreadyBeingDeclared()) 11497 return nullptr; 11498 11499 // Note: The following rules are largely analoguous to the move 11500 // constructor rules. 11501 11502 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11503 QualType RetType = Context.getLValueReferenceType(ArgType); 11504 ArgType = Context.getRValueReferenceType(ArgType); 11505 11506 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11507 CXXMoveAssignment, 11508 false); 11509 11510 // An implicitly-declared move assignment operator is an inline public 11511 // member of its class. 11512 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11513 SourceLocation ClassLoc = ClassDecl->getLocation(); 11514 DeclarationNameInfo NameInfo(Name, ClassLoc); 11515 CXXMethodDecl *MoveAssignment = 11516 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11517 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11518 /*isInline=*/true, Constexpr, SourceLocation()); 11519 MoveAssignment->setAccess(AS_public); 11520 MoveAssignment->setDefaulted(); 11521 MoveAssignment->setImplicit(); 11522 11523 if (getLangOpts().CUDA) { 11524 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11525 MoveAssignment, 11526 /* ConstRHS */ false, 11527 /* Diagnose */ false); 11528 } 11529 11530 // Build an exception specification pointing back at this member. 11531 FunctionProtoType::ExtProtoInfo EPI = 11532 getImplicitMethodEPI(*this, MoveAssignment); 11533 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11534 11535 // Add the parameter to the operator. 11536 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11537 ClassLoc, ClassLoc, 11538 /*Id=*/nullptr, ArgType, 11539 /*TInfo=*/nullptr, SC_None, 11540 nullptr); 11541 MoveAssignment->setParams(FromParam); 11542 11543 MoveAssignment->setTrivial( 11544 ClassDecl->needsOverloadResolutionForMoveAssignment() 11545 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11546 : ClassDecl->hasTrivialMoveAssignment()); 11547 11548 // Note that we have added this copy-assignment operator. 11549 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11550 11551 Scope *S = getScopeForContext(ClassDecl); 11552 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11553 11554 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11555 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11556 SetDeclDeleted(MoveAssignment, ClassLoc); 11557 } 11558 11559 if (S) 11560 PushOnScopeChains(MoveAssignment, S, false); 11561 ClassDecl->addDecl(MoveAssignment); 11562 11563 return MoveAssignment; 11564 } 11565 11566 /// Check if we're implicitly defining a move assignment operator for a class 11567 /// with virtual bases. Such a move assignment might move-assign the virtual 11568 /// base multiple times. 11569 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11570 SourceLocation CurrentLocation) { 11571 assert(!Class->isDependentContext() && "should not define dependent move"); 11572 11573 // Only a virtual base could get implicitly move-assigned multiple times. 11574 // Only a non-trivial move assignment can observe this. We only want to 11575 // diagnose if we implicitly define an assignment operator that assigns 11576 // two base classes, both of which move-assign the same virtual base. 11577 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11578 Class->getNumBases() < 2) 11579 return; 11580 11581 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11582 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11583 VBaseMap VBases; 11584 11585 for (auto &BI : Class->bases()) { 11586 Worklist.push_back(&BI); 11587 while (!Worklist.empty()) { 11588 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11589 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11590 11591 // If the base has no non-trivial move assignment operators, 11592 // we don't care about moves from it. 11593 if (!Base->hasNonTrivialMoveAssignment()) 11594 continue; 11595 11596 // If there's nothing virtual here, skip it. 11597 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11598 continue; 11599 11600 // If we're not actually going to call a move assignment for this base, 11601 // or the selected move assignment is trivial, skip it. 11602 Sema::SpecialMemberOverloadResult SMOR = 11603 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11604 /*ConstArg*/false, /*VolatileArg*/false, 11605 /*RValueThis*/true, /*ConstThis*/false, 11606 /*VolatileThis*/false); 11607 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 11608 !SMOR.getMethod()->isMoveAssignmentOperator()) 11609 continue; 11610 11611 if (BaseSpec->isVirtual()) { 11612 // We're going to move-assign this virtual base, and its move 11613 // assignment operator is not trivial. If this can happen for 11614 // multiple distinct direct bases of Class, diagnose it. (If it 11615 // only happens in one base, we'll diagnose it when synthesizing 11616 // that base class's move assignment operator.) 11617 CXXBaseSpecifier *&Existing = 11618 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11619 .first->second; 11620 if (Existing && Existing != &BI) { 11621 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11622 << Class << Base; 11623 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11624 << (Base->getCanonicalDecl() == 11625 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11626 << Base << Existing->getType() << Existing->getSourceRange(); 11627 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11628 << (Base->getCanonicalDecl() == 11629 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11630 << Base << BI.getType() << BaseSpec->getSourceRange(); 11631 11632 // Only diagnose each vbase once. 11633 Existing = nullptr; 11634 } 11635 } else { 11636 // Only walk over bases that have defaulted move assignment operators. 11637 // We assume that any user-provided move assignment operator handles 11638 // the multiple-moves-of-vbase case itself somehow. 11639 if (!SMOR.getMethod()->isDefaulted()) 11640 continue; 11641 11642 // We're going to move the base classes of Base. Add them to the list. 11643 for (auto &BI : Base->bases()) 11644 Worklist.push_back(&BI); 11645 } 11646 } 11647 } 11648 } 11649 11650 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11651 CXXMethodDecl *MoveAssignOperator) { 11652 assert((MoveAssignOperator->isDefaulted() && 11653 MoveAssignOperator->isOverloadedOperator() && 11654 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11655 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11656 !MoveAssignOperator->isDeleted()) && 11657 "DefineImplicitMoveAssignment called for wrong function"); 11658 11659 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11660 11661 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 11662 MoveAssignOperator->setInvalidDecl(); 11663 return; 11664 } 11665 11666 MoveAssignOperator->markUsed(Context); 11667 11668 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11669 DiagnosticErrorTrap Trap(Diags); 11670 11671 // C++0x [class.copy]p28: 11672 // The implicitly-defined or move assignment operator for a non-union class 11673 // X performs memberwise move assignment of its subobjects. The direct base 11674 // classes of X are assigned first, in the order of their declaration in the 11675 // base-specifier-list, and then the immediate non-static data members of X 11676 // are assigned, in the order in which they were declared in the class 11677 // definition. 11678 11679 // Issue a warning if our implicit move assignment operator will move 11680 // from a virtual base more than once. 11681 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11682 11683 // The statements that form the synthesized function body. 11684 SmallVector<Stmt*, 8> Statements; 11685 11686 // The parameter for the "other" object, which we are move from. 11687 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11688 QualType OtherRefType = Other->getType()-> 11689 getAs<RValueReferenceType>()->getPointeeType(); 11690 assert(!OtherRefType.getQualifiers() && 11691 "Bad argument type of defaulted move assignment"); 11692 11693 // Our location for everything implicitly-generated. 11694 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11695 ? MoveAssignOperator->getLocEnd() 11696 : MoveAssignOperator->getLocation(); 11697 11698 // Builds a reference to the "other" object. 11699 RefBuilder OtherRef(Other, OtherRefType); 11700 // Cast to rvalue. 11701 MoveCastBuilder MoveOther(OtherRef); 11702 11703 // Builds the "this" pointer. 11704 ThisBuilder This; 11705 11706 // Assign base classes. 11707 bool Invalid = false; 11708 for (auto &Base : ClassDecl->bases()) { 11709 // C++11 [class.copy]p28: 11710 // It is unspecified whether subobjects representing virtual base classes 11711 // are assigned more than once by the implicitly-defined copy assignment 11712 // operator. 11713 // FIXME: Do not assign to a vbase that will be assigned by some other base 11714 // class. For a move-assignment, this can result in the vbase being moved 11715 // multiple times. 11716 11717 // Form the assignment: 11718 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11719 QualType BaseType = Base.getType().getUnqualifiedType(); 11720 if (!BaseType->isRecordType()) { 11721 Invalid = true; 11722 continue; 11723 } 11724 11725 CXXCastPath BasePath; 11726 BasePath.push_back(&Base); 11727 11728 // Construct the "from" expression, which is an implicit cast to the 11729 // appropriately-qualified base type. 11730 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11731 11732 // Dereference "this". 11733 DerefBuilder DerefThis(This); 11734 11735 // Implicitly cast "this" to the appropriately-qualified base type. 11736 CastBuilder To(DerefThis, 11737 Context.getCVRQualifiedType( 11738 BaseType, MoveAssignOperator->getTypeQualifiers()), 11739 VK_LValue, BasePath); 11740 11741 // Build the move. 11742 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11743 To, From, 11744 /*CopyingBaseSubobject=*/true, 11745 /*Copying=*/false); 11746 if (Move.isInvalid()) { 11747 Diag(CurrentLocation, diag::note_member_synthesized_at) 11748 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11749 MoveAssignOperator->setInvalidDecl(); 11750 return; 11751 } 11752 11753 // Success! Record the move. 11754 Statements.push_back(Move.getAs<Expr>()); 11755 } 11756 11757 // Assign non-static members. 11758 for (auto *Field : ClassDecl->fields()) { 11759 // FIXME: We should form some kind of AST representation for the implied 11760 // memcpy in a union copy operation. 11761 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11762 continue; 11763 11764 if (Field->isInvalidDecl()) { 11765 Invalid = true; 11766 continue; 11767 } 11768 11769 // Check for members of reference type; we can't move those. 11770 if (Field->getType()->isReferenceType()) { 11771 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11772 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11773 Diag(Field->getLocation(), diag::note_declared_at); 11774 Diag(CurrentLocation, diag::note_member_synthesized_at) 11775 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11776 Invalid = true; 11777 continue; 11778 } 11779 11780 // Check for members of const-qualified, non-class type. 11781 QualType BaseType = Context.getBaseElementType(Field->getType()); 11782 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11783 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11784 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11785 Diag(Field->getLocation(), diag::note_declared_at); 11786 Diag(CurrentLocation, diag::note_member_synthesized_at) 11787 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11788 Invalid = true; 11789 continue; 11790 } 11791 11792 // Suppress assigning zero-width bitfields. 11793 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11794 continue; 11795 11796 QualType FieldType = Field->getType().getNonReferenceType(); 11797 if (FieldType->isIncompleteArrayType()) { 11798 assert(ClassDecl->hasFlexibleArrayMember() && 11799 "Incomplete array type is not valid"); 11800 continue; 11801 } 11802 11803 // Build references to the field in the object we're copying from and to. 11804 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11805 LookupMemberName); 11806 MemberLookup.addDecl(Field); 11807 MemberLookup.resolveKind(); 11808 MemberBuilder From(MoveOther, OtherRefType, 11809 /*IsArrow=*/false, MemberLookup); 11810 MemberBuilder To(This, getCurrentThisType(), 11811 /*IsArrow=*/true, MemberLookup); 11812 11813 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 11814 "Member reference with rvalue base must be rvalue except for reference " 11815 "members, which aren't allowed for move assignment."); 11816 11817 // Build the move of this field. 11818 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 11819 To, From, 11820 /*CopyingBaseSubobject=*/false, 11821 /*Copying=*/false); 11822 if (Move.isInvalid()) { 11823 Diag(CurrentLocation, diag::note_member_synthesized_at) 11824 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11825 MoveAssignOperator->setInvalidDecl(); 11826 return; 11827 } 11828 11829 // Success! Record the copy. 11830 Statements.push_back(Move.getAs<Stmt>()); 11831 } 11832 11833 if (!Invalid) { 11834 // Add a "return *this;" 11835 ExprResult ThisObj = 11836 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11837 11838 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11839 if (Return.isInvalid()) 11840 Invalid = true; 11841 else { 11842 Statements.push_back(Return.getAs<Stmt>()); 11843 11844 if (Trap.hasErrorOccurred()) { 11845 Diag(CurrentLocation, diag::note_member_synthesized_at) 11846 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11847 Invalid = true; 11848 } 11849 } 11850 } 11851 11852 // The exception specification is needed because we are defining the 11853 // function. 11854 ResolveExceptionSpec(CurrentLocation, 11855 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11856 11857 if (Invalid) { 11858 MoveAssignOperator->setInvalidDecl(); 11859 return; 11860 } 11861 11862 StmtResult Body; 11863 { 11864 CompoundScopeRAII CompoundScope(*this); 11865 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11866 /*isStmtExpr=*/false); 11867 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11868 } 11869 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 11870 11871 if (ASTMutationListener *L = getASTMutationListener()) { 11872 L->CompletedImplicitDefinition(MoveAssignOperator); 11873 } 11874 } 11875 11876 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 11877 CXXRecordDecl *ClassDecl) { 11878 // C++ [class.copy]p4: 11879 // If the class definition does not explicitly declare a copy 11880 // constructor, one is declared implicitly. 11881 assert(ClassDecl->needsImplicitCopyConstructor()); 11882 11883 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 11884 if (DSM.isAlreadyBeingDeclared()) 11885 return nullptr; 11886 11887 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11888 QualType ArgType = ClassType; 11889 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 11890 if (Const) 11891 ArgType = ArgType.withConst(); 11892 ArgType = Context.getLValueReferenceType(ArgType); 11893 11894 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11895 CXXCopyConstructor, 11896 Const); 11897 11898 DeclarationName Name 11899 = Context.DeclarationNames.getCXXConstructorName( 11900 Context.getCanonicalType(ClassType)); 11901 SourceLocation ClassLoc = ClassDecl->getLocation(); 11902 DeclarationNameInfo NameInfo(Name, ClassLoc); 11903 11904 // An implicitly-declared copy constructor is an inline public 11905 // member of its class. 11906 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 11907 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11908 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11909 Constexpr); 11910 CopyConstructor->setAccess(AS_public); 11911 CopyConstructor->setDefaulted(); 11912 11913 if (getLangOpts().CUDA) { 11914 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 11915 CopyConstructor, 11916 /* ConstRHS */ Const, 11917 /* Diagnose */ false); 11918 } 11919 11920 // Build an exception specification pointing back at this member. 11921 FunctionProtoType::ExtProtoInfo EPI = 11922 getImplicitMethodEPI(*this, CopyConstructor); 11923 CopyConstructor->setType( 11924 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11925 11926 // Add the parameter to the constructor. 11927 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 11928 ClassLoc, ClassLoc, 11929 /*IdentifierInfo=*/nullptr, 11930 ArgType, /*TInfo=*/nullptr, 11931 SC_None, nullptr); 11932 CopyConstructor->setParams(FromParam); 11933 11934 CopyConstructor->setTrivial( 11935 ClassDecl->needsOverloadResolutionForCopyConstructor() 11936 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 11937 : ClassDecl->hasTrivialCopyConstructor()); 11938 11939 // Note that we have declared this constructor. 11940 ++ASTContext::NumImplicitCopyConstructorsDeclared; 11941 11942 Scope *S = getScopeForContext(ClassDecl); 11943 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 11944 11945 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 11946 SetDeclDeleted(CopyConstructor, ClassLoc); 11947 11948 if (S) 11949 PushOnScopeChains(CopyConstructor, S, false); 11950 ClassDecl->addDecl(CopyConstructor); 11951 11952 return CopyConstructor; 11953 } 11954 11955 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 11956 CXXConstructorDecl *CopyConstructor) { 11957 assert((CopyConstructor->isDefaulted() && 11958 CopyConstructor->isCopyConstructor() && 11959 !CopyConstructor->doesThisDeclarationHaveABody() && 11960 !CopyConstructor->isDeleted()) && 11961 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 11962 11963 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 11964 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 11965 11966 // C++11 [class.copy]p7: 11967 // The [definition of an implicitly declared copy constructor] is 11968 // deprecated if the class has a user-declared copy assignment operator 11969 // or a user-declared destructor. 11970 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 11971 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 11972 11973 SynthesizedFunctionScope Scope(*this, CopyConstructor); 11974 DiagnosticErrorTrap Trap(Diags); 11975 11976 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 11977 Trap.hasErrorOccurred()) { 11978 Diag(CurrentLocation, diag::note_member_synthesized_at) 11979 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 11980 CopyConstructor->setInvalidDecl(); 11981 } else { 11982 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 11983 ? CopyConstructor->getLocEnd() 11984 : CopyConstructor->getLocation(); 11985 Sema::CompoundScopeRAII CompoundScope(*this); 11986 CopyConstructor->setBody( 11987 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 11988 } 11989 11990 // The exception specification is needed because we are defining the 11991 // function. 11992 ResolveExceptionSpec(CurrentLocation, 11993 CopyConstructor->getType()->castAs<FunctionProtoType>()); 11994 11995 CopyConstructor->markUsed(Context); 11996 MarkVTableUsed(CurrentLocation, ClassDecl); 11997 11998 if (ASTMutationListener *L = getASTMutationListener()) { 11999 L->CompletedImplicitDefinition(CopyConstructor); 12000 } 12001 } 12002 12003 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12004 CXXRecordDecl *ClassDecl) { 12005 assert(ClassDecl->needsImplicitMoveConstructor()); 12006 12007 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12008 if (DSM.isAlreadyBeingDeclared()) 12009 return nullptr; 12010 12011 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12012 QualType ArgType = Context.getRValueReferenceType(ClassType); 12013 12014 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12015 CXXMoveConstructor, 12016 false); 12017 12018 DeclarationName Name 12019 = Context.DeclarationNames.getCXXConstructorName( 12020 Context.getCanonicalType(ClassType)); 12021 SourceLocation ClassLoc = ClassDecl->getLocation(); 12022 DeclarationNameInfo NameInfo(Name, ClassLoc); 12023 12024 // C++11 [class.copy]p11: 12025 // An implicitly-declared copy/move constructor is an inline public 12026 // member of its class. 12027 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12028 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12029 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12030 Constexpr); 12031 MoveConstructor->setAccess(AS_public); 12032 MoveConstructor->setDefaulted(); 12033 12034 if (getLangOpts().CUDA) { 12035 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12036 MoveConstructor, 12037 /* ConstRHS */ false, 12038 /* Diagnose */ false); 12039 } 12040 12041 // Build an exception specification pointing back at this member. 12042 FunctionProtoType::ExtProtoInfo EPI = 12043 getImplicitMethodEPI(*this, MoveConstructor); 12044 MoveConstructor->setType( 12045 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12046 12047 // Add the parameter to the constructor. 12048 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12049 ClassLoc, ClassLoc, 12050 /*IdentifierInfo=*/nullptr, 12051 ArgType, /*TInfo=*/nullptr, 12052 SC_None, nullptr); 12053 MoveConstructor->setParams(FromParam); 12054 12055 MoveConstructor->setTrivial( 12056 ClassDecl->needsOverloadResolutionForMoveConstructor() 12057 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12058 : ClassDecl->hasTrivialMoveConstructor()); 12059 12060 // Note that we have declared this constructor. 12061 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12062 12063 Scope *S = getScopeForContext(ClassDecl); 12064 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12065 12066 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12067 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12068 SetDeclDeleted(MoveConstructor, ClassLoc); 12069 } 12070 12071 if (S) 12072 PushOnScopeChains(MoveConstructor, S, false); 12073 ClassDecl->addDecl(MoveConstructor); 12074 12075 return MoveConstructor; 12076 } 12077 12078 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12079 CXXConstructorDecl *MoveConstructor) { 12080 assert((MoveConstructor->isDefaulted() && 12081 MoveConstructor->isMoveConstructor() && 12082 !MoveConstructor->doesThisDeclarationHaveABody() && 12083 !MoveConstructor->isDeleted()) && 12084 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12085 12086 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12087 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12088 12089 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12090 DiagnosticErrorTrap Trap(Diags); 12091 12092 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 12093 Trap.hasErrorOccurred()) { 12094 Diag(CurrentLocation, diag::note_member_synthesized_at) 12095 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 12096 MoveConstructor->setInvalidDecl(); 12097 } else { 12098 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12099 ? MoveConstructor->getLocEnd() 12100 : MoveConstructor->getLocation(); 12101 Sema::CompoundScopeRAII CompoundScope(*this); 12102 MoveConstructor->setBody(ActOnCompoundStmt( 12103 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12104 } 12105 12106 // The exception specification is needed because we are defining the 12107 // function. 12108 ResolveExceptionSpec(CurrentLocation, 12109 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12110 12111 MoveConstructor->markUsed(Context); 12112 MarkVTableUsed(CurrentLocation, ClassDecl); 12113 12114 if (ASTMutationListener *L = getASTMutationListener()) { 12115 L->CompletedImplicitDefinition(MoveConstructor); 12116 } 12117 } 12118 12119 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12120 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12121 } 12122 12123 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12124 SourceLocation CurrentLocation, 12125 CXXConversionDecl *Conv) { 12126 CXXRecordDecl *Lambda = Conv->getParent(); 12127 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 12128 // If we are defining a specialization of a conversion to function-ptr 12129 // cache the deduced template arguments for this specialization 12130 // so that we can use them to retrieve the corresponding call-operator 12131 // and static-invoker. 12132 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 12133 12134 // Retrieve the corresponding call-operator specialization. 12135 if (Lambda->isGenericLambda()) { 12136 assert(Conv->isFunctionTemplateSpecialization()); 12137 FunctionTemplateDecl *CallOpTemplate = 12138 CallOp->getDescribedFunctionTemplate(); 12139 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 12140 void *InsertPos = nullptr; 12141 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 12142 DeducedTemplateArgs->asArray(), 12143 InsertPos); 12144 assert(CallOpSpec && 12145 "Conversion operator must have a corresponding call operator"); 12146 CallOp = cast<CXXMethodDecl>(CallOpSpec); 12147 } 12148 // Mark the call operator referenced (and add to pending instantiations 12149 // if necessary). 12150 // For both the conversion and static-invoker template specializations 12151 // we construct their body's in this function, so no need to add them 12152 // to the PendingInstantiations. 12153 MarkFunctionReferenced(CurrentLocation, CallOp); 12154 12155 SynthesizedFunctionScope Scope(*this, Conv); 12156 DiagnosticErrorTrap Trap(Diags); 12157 12158 // Retrieve the static invoker... 12159 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12160 // ... and get the corresponding specialization for a generic lambda. 12161 if (Lambda->isGenericLambda()) { 12162 assert(DeducedTemplateArgs && 12163 "Must have deduced template arguments from Conversion Operator"); 12164 FunctionTemplateDecl *InvokeTemplate = 12165 Invoker->getDescribedFunctionTemplate(); 12166 void *InsertPos = nullptr; 12167 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 12168 DeducedTemplateArgs->asArray(), 12169 InsertPos); 12170 assert(InvokeSpec && 12171 "Must have a corresponding static invoker specialization"); 12172 Invoker = cast<CXXMethodDecl>(InvokeSpec); 12173 } 12174 // Construct the body of the conversion function { return __invoke; }. 12175 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12176 VK_LValue, Conv->getLocation()).get(); 12177 assert(FunctionRef && "Can't refer to __invoke function?"); 12178 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12179 Conv->setBody(new (Context) CompoundStmt(Context, Return, 12180 Conv->getLocation(), 12181 Conv->getLocation())); 12182 12183 Conv->markUsed(Context); 12184 Conv->setReferenced(); 12185 12186 // Fill in the __invoke function with a dummy implementation. IR generation 12187 // will fill in the actual details. 12188 Invoker->markUsed(Context); 12189 Invoker->setReferenced(); 12190 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12191 12192 if (ASTMutationListener *L = getASTMutationListener()) { 12193 L->CompletedImplicitDefinition(Conv); 12194 L->CompletedImplicitDefinition(Invoker); 12195 } 12196 } 12197 12198 12199 12200 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12201 SourceLocation CurrentLocation, 12202 CXXConversionDecl *Conv) 12203 { 12204 assert(!Conv->getParent()->isGenericLambda()); 12205 12206 Conv->markUsed(Context); 12207 12208 SynthesizedFunctionScope Scope(*this, Conv); 12209 DiagnosticErrorTrap Trap(Diags); 12210 12211 // Copy-initialize the lambda object as needed to capture it. 12212 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12213 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12214 12215 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12216 Conv->getLocation(), 12217 Conv, DerefThis); 12218 12219 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12220 // behavior. Note that only the general conversion function does this 12221 // (since it's unusable otherwise); in the case where we inline the 12222 // block literal, it has block literal lifetime semantics. 12223 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12224 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12225 CK_CopyAndAutoreleaseBlockObject, 12226 BuildBlock.get(), nullptr, VK_RValue); 12227 12228 if (BuildBlock.isInvalid()) { 12229 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12230 Conv->setInvalidDecl(); 12231 return; 12232 } 12233 12234 // Create the return statement that returns the block from the conversion 12235 // function. 12236 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12237 if (Return.isInvalid()) { 12238 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12239 Conv->setInvalidDecl(); 12240 return; 12241 } 12242 12243 // Set the body of the conversion function. 12244 Stmt *ReturnS = Return.get(); 12245 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 12246 Conv->getLocation(), 12247 Conv->getLocation())); 12248 12249 // We're done; notify the mutation listener, if any. 12250 if (ASTMutationListener *L = getASTMutationListener()) { 12251 L->CompletedImplicitDefinition(Conv); 12252 } 12253 } 12254 12255 /// \brief Determine whether the given list arguments contains exactly one 12256 /// "real" (non-default) argument. 12257 static bool hasOneRealArgument(MultiExprArg Args) { 12258 switch (Args.size()) { 12259 case 0: 12260 return false; 12261 12262 default: 12263 if (!Args[1]->isDefaultArgument()) 12264 return false; 12265 12266 // fall through 12267 case 1: 12268 return !Args[0]->isDefaultArgument(); 12269 } 12270 12271 return false; 12272 } 12273 12274 ExprResult 12275 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12276 NamedDecl *FoundDecl, 12277 CXXConstructorDecl *Constructor, 12278 MultiExprArg ExprArgs, 12279 bool HadMultipleCandidates, 12280 bool IsListInitialization, 12281 bool IsStdInitListInitialization, 12282 bool RequiresZeroInit, 12283 unsigned ConstructKind, 12284 SourceRange ParenRange) { 12285 bool Elidable = false; 12286 12287 // C++0x [class.copy]p34: 12288 // When certain criteria are met, an implementation is allowed to 12289 // omit the copy/move construction of a class object, even if the 12290 // copy/move constructor and/or destructor for the object have 12291 // side effects. [...] 12292 // - when a temporary class object that has not been bound to a 12293 // reference (12.2) would be copied/moved to a class object 12294 // with the same cv-unqualified type, the copy/move operation 12295 // can be omitted by constructing the temporary object 12296 // directly into the target of the omitted copy/move 12297 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12298 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12299 Expr *SubExpr = ExprArgs[0]; 12300 Elidable = SubExpr->isTemporaryObject( 12301 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12302 } 12303 12304 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12305 FoundDecl, Constructor, 12306 Elidable, ExprArgs, HadMultipleCandidates, 12307 IsListInitialization, 12308 IsStdInitListInitialization, RequiresZeroInit, 12309 ConstructKind, ParenRange); 12310 } 12311 12312 ExprResult 12313 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12314 NamedDecl *FoundDecl, 12315 CXXConstructorDecl *Constructor, 12316 bool Elidable, 12317 MultiExprArg ExprArgs, 12318 bool HadMultipleCandidates, 12319 bool IsListInitialization, 12320 bool IsStdInitListInitialization, 12321 bool RequiresZeroInit, 12322 unsigned ConstructKind, 12323 SourceRange ParenRange) { 12324 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12325 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12326 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12327 return ExprError(); 12328 } 12329 12330 return BuildCXXConstructExpr( 12331 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12332 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12333 RequiresZeroInit, ConstructKind, ParenRange); 12334 } 12335 12336 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12337 /// including handling of its default argument expressions. 12338 ExprResult 12339 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12340 CXXConstructorDecl *Constructor, 12341 bool Elidable, 12342 MultiExprArg ExprArgs, 12343 bool HadMultipleCandidates, 12344 bool IsListInitialization, 12345 bool IsStdInitListInitialization, 12346 bool RequiresZeroInit, 12347 unsigned ConstructKind, 12348 SourceRange ParenRange) { 12349 assert(declaresSameEntity( 12350 Constructor->getParent(), 12351 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12352 "given constructor for wrong type"); 12353 MarkFunctionReferenced(ConstructLoc, Constructor); 12354 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12355 return ExprError(); 12356 12357 return CXXConstructExpr::Create( 12358 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12359 ExprArgs, HadMultipleCandidates, IsListInitialization, 12360 IsStdInitListInitialization, RequiresZeroInit, 12361 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12362 ParenRange); 12363 } 12364 12365 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12366 assert(Field->hasInClassInitializer()); 12367 12368 // If we already have the in-class initializer nothing needs to be done. 12369 if (Field->getInClassInitializer()) 12370 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12371 12372 // If we might have already tried and failed to instantiate, don't try again. 12373 if (Field->isInvalidDecl()) 12374 return ExprError(); 12375 12376 // Maybe we haven't instantiated the in-class initializer. Go check the 12377 // pattern FieldDecl to see if it has one. 12378 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12379 12380 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12381 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12382 DeclContext::lookup_result Lookup = 12383 ClassPattern->lookup(Field->getDeclName()); 12384 12385 // Lookup can return at most two results: the pattern for the field, or the 12386 // injected class name of the parent record. No other member can have the 12387 // same name as the field. 12388 // In modules mode, lookup can return multiple results (coming from 12389 // different modules). 12390 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12391 "more than two lookup results for field name"); 12392 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12393 if (!Pattern) { 12394 assert(isa<CXXRecordDecl>(Lookup[0]) && 12395 "cannot have other non-field member with same name"); 12396 for (auto L : Lookup) 12397 if (isa<FieldDecl>(L)) { 12398 Pattern = cast<FieldDecl>(L); 12399 break; 12400 } 12401 assert(Pattern && "We must have set the Pattern!"); 12402 } 12403 12404 if (InstantiateInClassInitializer(Loc, Field, Pattern, 12405 getTemplateInstantiationArgs(Field))) { 12406 // Don't diagnose this again. 12407 Field->setInvalidDecl(); 12408 return ExprError(); 12409 } 12410 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12411 } 12412 12413 // DR1351: 12414 // If the brace-or-equal-initializer of a non-static data member 12415 // invokes a defaulted default constructor of its class or of an 12416 // enclosing class in a potentially evaluated subexpression, the 12417 // program is ill-formed. 12418 // 12419 // This resolution is unworkable: the exception specification of the 12420 // default constructor can be needed in an unevaluated context, in 12421 // particular, in the operand of a noexcept-expression, and we can be 12422 // unable to compute an exception specification for an enclosed class. 12423 // 12424 // Any attempt to resolve the exception specification of a defaulted default 12425 // constructor before the initializer is lexically complete will ultimately 12426 // come here at which point we can diagnose it. 12427 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12428 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12429 << OutermostClass << Field; 12430 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12431 // Recover by marking the field invalid, unless we're in a SFINAE context. 12432 if (!isSFINAEContext()) 12433 Field->setInvalidDecl(); 12434 return ExprError(); 12435 } 12436 12437 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12438 if (VD->isInvalidDecl()) return; 12439 12440 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12441 if (ClassDecl->isInvalidDecl()) return; 12442 if (ClassDecl->hasIrrelevantDestructor()) return; 12443 if (ClassDecl->isDependentContext()) return; 12444 12445 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12446 MarkFunctionReferenced(VD->getLocation(), Destructor); 12447 CheckDestructorAccess(VD->getLocation(), Destructor, 12448 PDiag(diag::err_access_dtor_var) 12449 << VD->getDeclName() 12450 << VD->getType()); 12451 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12452 12453 if (Destructor->isTrivial()) return; 12454 if (!VD->hasGlobalStorage()) return; 12455 12456 // Emit warning for non-trivial dtor in global scope (a real global, 12457 // class-static, function-static). 12458 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12459 12460 // TODO: this should be re-enabled for static locals by !CXAAtExit 12461 if (!VD->isStaticLocal()) 12462 Diag(VD->getLocation(), diag::warn_global_destructor); 12463 } 12464 12465 /// \brief Given a constructor and the set of arguments provided for the 12466 /// constructor, convert the arguments and add any required default arguments 12467 /// to form a proper call to this constructor. 12468 /// 12469 /// \returns true if an error occurred, false otherwise. 12470 bool 12471 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12472 MultiExprArg ArgsPtr, 12473 SourceLocation Loc, 12474 SmallVectorImpl<Expr*> &ConvertedArgs, 12475 bool AllowExplicit, 12476 bool IsListInitialization) { 12477 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12478 unsigned NumArgs = ArgsPtr.size(); 12479 Expr **Args = ArgsPtr.data(); 12480 12481 const FunctionProtoType *Proto 12482 = Constructor->getType()->getAs<FunctionProtoType>(); 12483 assert(Proto && "Constructor without a prototype?"); 12484 unsigned NumParams = Proto->getNumParams(); 12485 12486 // If too few arguments are available, we'll fill in the rest with defaults. 12487 if (NumArgs < NumParams) 12488 ConvertedArgs.reserve(NumParams); 12489 else 12490 ConvertedArgs.reserve(NumArgs); 12491 12492 VariadicCallType CallType = 12493 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12494 SmallVector<Expr *, 8> AllArgs; 12495 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12496 Proto, 0, 12497 llvm::makeArrayRef(Args, NumArgs), 12498 AllArgs, 12499 CallType, AllowExplicit, 12500 IsListInitialization); 12501 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12502 12503 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12504 12505 CheckConstructorCall(Constructor, 12506 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12507 Proto, Loc); 12508 12509 return Invalid; 12510 } 12511 12512 static inline bool 12513 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12514 const FunctionDecl *FnDecl) { 12515 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12516 if (isa<NamespaceDecl>(DC)) { 12517 return SemaRef.Diag(FnDecl->getLocation(), 12518 diag::err_operator_new_delete_declared_in_namespace) 12519 << FnDecl->getDeclName(); 12520 } 12521 12522 if (isa<TranslationUnitDecl>(DC) && 12523 FnDecl->getStorageClass() == SC_Static) { 12524 return SemaRef.Diag(FnDecl->getLocation(), 12525 diag::err_operator_new_delete_declared_static) 12526 << FnDecl->getDeclName(); 12527 } 12528 12529 return false; 12530 } 12531 12532 static inline bool 12533 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12534 CanQualType ExpectedResultType, 12535 CanQualType ExpectedFirstParamType, 12536 unsigned DependentParamTypeDiag, 12537 unsigned InvalidParamTypeDiag) { 12538 QualType ResultType = 12539 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12540 12541 // Check that the result type is not dependent. 12542 if (ResultType->isDependentType()) 12543 return SemaRef.Diag(FnDecl->getLocation(), 12544 diag::err_operator_new_delete_dependent_result_type) 12545 << FnDecl->getDeclName() << ExpectedResultType; 12546 12547 // Check that the result type is what we expect. 12548 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12549 return SemaRef.Diag(FnDecl->getLocation(), 12550 diag::err_operator_new_delete_invalid_result_type) 12551 << FnDecl->getDeclName() << ExpectedResultType; 12552 12553 // A function template must have at least 2 parameters. 12554 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12555 return SemaRef.Diag(FnDecl->getLocation(), 12556 diag::err_operator_new_delete_template_too_few_parameters) 12557 << FnDecl->getDeclName(); 12558 12559 // The function decl must have at least 1 parameter. 12560 if (FnDecl->getNumParams() == 0) 12561 return SemaRef.Diag(FnDecl->getLocation(), 12562 diag::err_operator_new_delete_too_few_parameters) 12563 << FnDecl->getDeclName(); 12564 12565 // Check the first parameter type is not dependent. 12566 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12567 if (FirstParamType->isDependentType()) 12568 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12569 << FnDecl->getDeclName() << ExpectedFirstParamType; 12570 12571 // Check that the first parameter type is what we expect. 12572 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12573 ExpectedFirstParamType) 12574 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12575 << FnDecl->getDeclName() << ExpectedFirstParamType; 12576 12577 return false; 12578 } 12579 12580 static bool 12581 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12582 // C++ [basic.stc.dynamic.allocation]p1: 12583 // A program is ill-formed if an allocation function is declared in a 12584 // namespace scope other than global scope or declared static in global 12585 // scope. 12586 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12587 return true; 12588 12589 CanQualType SizeTy = 12590 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12591 12592 // C++ [basic.stc.dynamic.allocation]p1: 12593 // The return type shall be void*. The first parameter shall have type 12594 // std::size_t. 12595 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12596 SizeTy, 12597 diag::err_operator_new_dependent_param_type, 12598 diag::err_operator_new_param_type)) 12599 return true; 12600 12601 // C++ [basic.stc.dynamic.allocation]p1: 12602 // The first parameter shall not have an associated default argument. 12603 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12604 return SemaRef.Diag(FnDecl->getLocation(), 12605 diag::err_operator_new_default_arg) 12606 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12607 12608 return false; 12609 } 12610 12611 static bool 12612 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12613 // C++ [basic.stc.dynamic.deallocation]p1: 12614 // A program is ill-formed if deallocation functions are declared in a 12615 // namespace scope other than global scope or declared static in global 12616 // scope. 12617 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12618 return true; 12619 12620 // C++ [basic.stc.dynamic.deallocation]p2: 12621 // Each deallocation function shall return void and its first parameter 12622 // shall be void*. 12623 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 12624 SemaRef.Context.VoidPtrTy, 12625 diag::err_operator_delete_dependent_param_type, 12626 diag::err_operator_delete_param_type)) 12627 return true; 12628 12629 return false; 12630 } 12631 12632 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12633 /// of this overloaded operator is well-formed. If so, returns false; 12634 /// otherwise, emits appropriate diagnostics and returns true. 12635 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12636 assert(FnDecl && FnDecl->isOverloadedOperator() && 12637 "Expected an overloaded operator declaration"); 12638 12639 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12640 12641 // C++ [over.oper]p5: 12642 // The allocation and deallocation functions, operator new, 12643 // operator new[], operator delete and operator delete[], are 12644 // described completely in 3.7.3. The attributes and restrictions 12645 // found in the rest of this subclause do not apply to them unless 12646 // explicitly stated in 3.7.3. 12647 if (Op == OO_Delete || Op == OO_Array_Delete) 12648 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12649 12650 if (Op == OO_New || Op == OO_Array_New) 12651 return CheckOperatorNewDeclaration(*this, FnDecl); 12652 12653 // C++ [over.oper]p6: 12654 // An operator function shall either be a non-static member 12655 // function or be a non-member function and have at least one 12656 // parameter whose type is a class, a reference to a class, an 12657 // enumeration, or a reference to an enumeration. 12658 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12659 if (MethodDecl->isStatic()) 12660 return Diag(FnDecl->getLocation(), 12661 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12662 } else { 12663 bool ClassOrEnumParam = false; 12664 for (auto Param : FnDecl->parameters()) { 12665 QualType ParamType = Param->getType().getNonReferenceType(); 12666 if (ParamType->isDependentType() || ParamType->isRecordType() || 12667 ParamType->isEnumeralType()) { 12668 ClassOrEnumParam = true; 12669 break; 12670 } 12671 } 12672 12673 if (!ClassOrEnumParam) 12674 return Diag(FnDecl->getLocation(), 12675 diag::err_operator_overload_needs_class_or_enum) 12676 << FnDecl->getDeclName(); 12677 } 12678 12679 // C++ [over.oper]p8: 12680 // An operator function cannot have default arguments (8.3.6), 12681 // except where explicitly stated below. 12682 // 12683 // Only the function-call operator allows default arguments 12684 // (C++ [over.call]p1). 12685 if (Op != OO_Call) { 12686 for (auto Param : FnDecl->parameters()) { 12687 if (Param->hasDefaultArg()) 12688 return Diag(Param->getLocation(), 12689 diag::err_operator_overload_default_arg) 12690 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12691 } 12692 } 12693 12694 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12695 { false, false, false } 12696 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12697 , { Unary, Binary, MemberOnly } 12698 #include "clang/Basic/OperatorKinds.def" 12699 }; 12700 12701 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12702 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12703 bool MustBeMemberOperator = OperatorUses[Op][2]; 12704 12705 // C++ [over.oper]p8: 12706 // [...] Operator functions cannot have more or fewer parameters 12707 // than the number required for the corresponding operator, as 12708 // described in the rest of this subclause. 12709 unsigned NumParams = FnDecl->getNumParams() 12710 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12711 if (Op != OO_Call && 12712 ((NumParams == 1 && !CanBeUnaryOperator) || 12713 (NumParams == 2 && !CanBeBinaryOperator) || 12714 (NumParams < 1) || (NumParams > 2))) { 12715 // We have the wrong number of parameters. 12716 unsigned ErrorKind; 12717 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12718 ErrorKind = 2; // 2 -> unary or binary. 12719 } else if (CanBeUnaryOperator) { 12720 ErrorKind = 0; // 0 -> unary 12721 } else { 12722 assert(CanBeBinaryOperator && 12723 "All non-call overloaded operators are unary or binary!"); 12724 ErrorKind = 1; // 1 -> binary 12725 } 12726 12727 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12728 << FnDecl->getDeclName() << NumParams << ErrorKind; 12729 } 12730 12731 // Overloaded operators other than operator() cannot be variadic. 12732 if (Op != OO_Call && 12733 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12734 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12735 << FnDecl->getDeclName(); 12736 } 12737 12738 // Some operators must be non-static member functions. 12739 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12740 return Diag(FnDecl->getLocation(), 12741 diag::err_operator_overload_must_be_member) 12742 << FnDecl->getDeclName(); 12743 } 12744 12745 // C++ [over.inc]p1: 12746 // The user-defined function called operator++ implements the 12747 // prefix and postfix ++ operator. If this function is a member 12748 // function with no parameters, or a non-member function with one 12749 // parameter of class or enumeration type, it defines the prefix 12750 // increment operator ++ for objects of that type. If the function 12751 // is a member function with one parameter (which shall be of type 12752 // int) or a non-member function with two parameters (the second 12753 // of which shall be of type int), it defines the postfix 12754 // increment operator ++ for objects of that type. 12755 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12756 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12757 QualType ParamType = LastParam->getType(); 12758 12759 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12760 !ParamType->isDependentType()) 12761 return Diag(LastParam->getLocation(), 12762 diag::err_operator_overload_post_incdec_must_be_int) 12763 << LastParam->getType() << (Op == OO_MinusMinus); 12764 } 12765 12766 return false; 12767 } 12768 12769 static bool 12770 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12771 FunctionTemplateDecl *TpDecl) { 12772 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 12773 12774 // Must have one or two template parameters. 12775 if (TemplateParams->size() == 1) { 12776 NonTypeTemplateParmDecl *PmDecl = 12777 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 12778 12779 // The template parameter must be a char parameter pack. 12780 if (PmDecl && PmDecl->isTemplateParameterPack() && 12781 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 12782 return false; 12783 12784 } else if (TemplateParams->size() == 2) { 12785 TemplateTypeParmDecl *PmType = 12786 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 12787 NonTypeTemplateParmDecl *PmArgs = 12788 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 12789 12790 // The second template parameter must be a parameter pack with the 12791 // first template parameter as its type. 12792 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 12793 PmArgs->isTemplateParameterPack()) { 12794 const TemplateTypeParmType *TArgs = 12795 PmArgs->getType()->getAs<TemplateTypeParmType>(); 12796 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 12797 TArgs->getIndex() == PmType->getIndex()) { 12798 if (!SemaRef.inTemplateInstantiation()) 12799 SemaRef.Diag(TpDecl->getLocation(), 12800 diag::ext_string_literal_operator_template); 12801 return false; 12802 } 12803 } 12804 } 12805 12806 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 12807 diag::err_literal_operator_template) 12808 << TpDecl->getTemplateParameters()->getSourceRange(); 12809 return true; 12810 } 12811 12812 /// CheckLiteralOperatorDeclaration - Check whether the declaration 12813 /// of this literal operator function is well-formed. If so, returns 12814 /// false; otherwise, emits appropriate diagnostics and returns true. 12815 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 12816 if (isa<CXXMethodDecl>(FnDecl)) { 12817 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 12818 << FnDecl->getDeclName(); 12819 return true; 12820 } 12821 12822 if (FnDecl->isExternC()) { 12823 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 12824 if (const LinkageSpecDecl *LSD = 12825 FnDecl->getDeclContext()->getExternCContext()) 12826 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 12827 return true; 12828 } 12829 12830 // This might be the definition of a literal operator template. 12831 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 12832 12833 // This might be a specialization of a literal operator template. 12834 if (!TpDecl) 12835 TpDecl = FnDecl->getPrimaryTemplate(); 12836 12837 // template <char...> type operator "" name() and 12838 // template <class T, T...> type operator "" name() are the only valid 12839 // template signatures, and the only valid signatures with no parameters. 12840 if (TpDecl) { 12841 if (FnDecl->param_size() != 0) { 12842 Diag(FnDecl->getLocation(), 12843 diag::err_literal_operator_template_with_params); 12844 return true; 12845 } 12846 12847 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 12848 return true; 12849 12850 } else if (FnDecl->param_size() == 1) { 12851 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 12852 12853 QualType ParamType = Param->getType().getUnqualifiedType(); 12854 12855 // Only unsigned long long int, long double, any character type, and const 12856 // char * are allowed as the only parameters. 12857 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 12858 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 12859 Context.hasSameType(ParamType, Context.CharTy) || 12860 Context.hasSameType(ParamType, Context.WideCharTy) || 12861 Context.hasSameType(ParamType, Context.Char16Ty) || 12862 Context.hasSameType(ParamType, Context.Char32Ty)) { 12863 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 12864 QualType InnerType = Ptr->getPointeeType(); 12865 12866 // Pointer parameter must be a const char *. 12867 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 12868 Context.CharTy) && 12869 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 12870 Diag(Param->getSourceRange().getBegin(), 12871 diag::err_literal_operator_param) 12872 << ParamType << "'const char *'" << Param->getSourceRange(); 12873 return true; 12874 } 12875 12876 } else if (ParamType->isRealFloatingType()) { 12877 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12878 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 12879 return true; 12880 12881 } else if (ParamType->isIntegerType()) { 12882 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12883 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 12884 return true; 12885 12886 } else { 12887 Diag(Param->getSourceRange().getBegin(), 12888 diag::err_literal_operator_invalid_param) 12889 << ParamType << Param->getSourceRange(); 12890 return true; 12891 } 12892 12893 } else if (FnDecl->param_size() == 2) { 12894 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 12895 12896 // First, verify that the first parameter is correct. 12897 12898 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 12899 12900 // Two parameter function must have a pointer to const as a 12901 // first parameter; let's strip those qualifiers. 12902 const PointerType *PT = FirstParamType->getAs<PointerType>(); 12903 12904 if (!PT) { 12905 Diag((*Param)->getSourceRange().getBegin(), 12906 diag::err_literal_operator_param) 12907 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12908 return true; 12909 } 12910 12911 QualType PointeeType = PT->getPointeeType(); 12912 // First parameter must be const 12913 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 12914 Diag((*Param)->getSourceRange().getBegin(), 12915 diag::err_literal_operator_param) 12916 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12917 return true; 12918 } 12919 12920 QualType InnerType = PointeeType.getUnqualifiedType(); 12921 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 12922 // are allowed as the first parameter to a two-parameter function 12923 if (!(Context.hasSameType(InnerType, Context.CharTy) || 12924 Context.hasSameType(InnerType, Context.WideCharTy) || 12925 Context.hasSameType(InnerType, Context.Char16Ty) || 12926 Context.hasSameType(InnerType, Context.Char32Ty))) { 12927 Diag((*Param)->getSourceRange().getBegin(), 12928 diag::err_literal_operator_param) 12929 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12930 return true; 12931 } 12932 12933 // Move on to the second and final parameter. 12934 ++Param; 12935 12936 // The second parameter must be a std::size_t. 12937 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 12938 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 12939 Diag((*Param)->getSourceRange().getBegin(), 12940 diag::err_literal_operator_param) 12941 << SecondParamType << Context.getSizeType() 12942 << (*Param)->getSourceRange(); 12943 return true; 12944 } 12945 } else { 12946 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 12947 return true; 12948 } 12949 12950 // Parameters are good. 12951 12952 // A parameter-declaration-clause containing a default argument is not 12953 // equivalent to any of the permitted forms. 12954 for (auto Param : FnDecl->parameters()) { 12955 if (Param->hasDefaultArg()) { 12956 Diag(Param->getDefaultArgRange().getBegin(), 12957 diag::err_literal_operator_default_argument) 12958 << Param->getDefaultArgRange(); 12959 break; 12960 } 12961 } 12962 12963 StringRef LiteralName 12964 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 12965 if (LiteralName[0] != '_') { 12966 // C++11 [usrlit.suffix]p1: 12967 // Literal suffix identifiers that do not start with an underscore 12968 // are reserved for future standardization. 12969 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 12970 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 12971 } 12972 12973 return false; 12974 } 12975 12976 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 12977 /// linkage specification, including the language and (if present) 12978 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 12979 /// language string literal. LBraceLoc, if valid, provides the location of 12980 /// the '{' brace. Otherwise, this linkage specification does not 12981 /// have any braces. 12982 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 12983 Expr *LangStr, 12984 SourceLocation LBraceLoc) { 12985 StringLiteral *Lit = cast<StringLiteral>(LangStr); 12986 if (!Lit->isAscii()) { 12987 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 12988 << LangStr->getSourceRange(); 12989 return nullptr; 12990 } 12991 12992 StringRef Lang = Lit->getString(); 12993 LinkageSpecDecl::LanguageIDs Language; 12994 if (Lang == "C") 12995 Language = LinkageSpecDecl::lang_c; 12996 else if (Lang == "C++") 12997 Language = LinkageSpecDecl::lang_cxx; 12998 else { 12999 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13000 << LangStr->getSourceRange(); 13001 return nullptr; 13002 } 13003 13004 // FIXME: Add all the various semantics of linkage specifications 13005 13006 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13007 LangStr->getExprLoc(), Language, 13008 LBraceLoc.isValid()); 13009 CurContext->addDecl(D); 13010 PushDeclContext(S, D); 13011 return D; 13012 } 13013 13014 /// ActOnFinishLinkageSpecification - Complete the definition of 13015 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13016 /// valid, it's the position of the closing '}' brace in a linkage 13017 /// specification that uses braces. 13018 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13019 Decl *LinkageSpec, 13020 SourceLocation RBraceLoc) { 13021 if (RBraceLoc.isValid()) { 13022 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13023 LSDecl->setRBraceLoc(RBraceLoc); 13024 } 13025 PopDeclContext(); 13026 return LinkageSpec; 13027 } 13028 13029 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13030 AttributeList *AttrList, 13031 SourceLocation SemiLoc) { 13032 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13033 // Attribute declarations appertain to empty declaration so we handle 13034 // them here. 13035 if (AttrList) 13036 ProcessDeclAttributeList(S, ED, AttrList); 13037 13038 CurContext->addDecl(ED); 13039 return ED; 13040 } 13041 13042 /// \brief Perform semantic analysis for the variable declaration that 13043 /// occurs within a C++ catch clause, returning the newly-created 13044 /// variable. 13045 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13046 TypeSourceInfo *TInfo, 13047 SourceLocation StartLoc, 13048 SourceLocation Loc, 13049 IdentifierInfo *Name) { 13050 bool Invalid = false; 13051 QualType ExDeclType = TInfo->getType(); 13052 13053 // Arrays and functions decay. 13054 if (ExDeclType->isArrayType()) 13055 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13056 else if (ExDeclType->isFunctionType()) 13057 ExDeclType = Context.getPointerType(ExDeclType); 13058 13059 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13060 // The exception-declaration shall not denote a pointer or reference to an 13061 // incomplete type, other than [cv] void*. 13062 // N2844 forbids rvalue references. 13063 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13064 Diag(Loc, diag::err_catch_rvalue_ref); 13065 Invalid = true; 13066 } 13067 13068 if (ExDeclType->isVariablyModifiedType()) { 13069 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13070 Invalid = true; 13071 } 13072 13073 QualType BaseType = ExDeclType; 13074 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13075 unsigned DK = diag::err_catch_incomplete; 13076 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13077 BaseType = Ptr->getPointeeType(); 13078 Mode = 1; 13079 DK = diag::err_catch_incomplete_ptr; 13080 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13081 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13082 BaseType = Ref->getPointeeType(); 13083 Mode = 2; 13084 DK = diag::err_catch_incomplete_ref; 13085 } 13086 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13087 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13088 Invalid = true; 13089 13090 if (!Invalid && !ExDeclType->isDependentType() && 13091 RequireNonAbstractType(Loc, ExDeclType, 13092 diag::err_abstract_type_in_decl, 13093 AbstractVariableType)) 13094 Invalid = true; 13095 13096 // Only the non-fragile NeXT runtime currently supports C++ catches 13097 // of ObjC types, and no runtime supports catching ObjC types by value. 13098 if (!Invalid && getLangOpts().ObjC1) { 13099 QualType T = ExDeclType; 13100 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13101 T = RT->getPointeeType(); 13102 13103 if (T->isObjCObjectType()) { 13104 Diag(Loc, diag::err_objc_object_catch); 13105 Invalid = true; 13106 } else if (T->isObjCObjectPointerType()) { 13107 // FIXME: should this be a test for macosx-fragile specifically? 13108 if (getLangOpts().ObjCRuntime.isFragile()) 13109 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13110 } 13111 } 13112 13113 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13114 ExDeclType, TInfo, SC_None); 13115 ExDecl->setExceptionVariable(true); 13116 13117 // In ARC, infer 'retaining' for variables of retainable type. 13118 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13119 Invalid = true; 13120 13121 if (!Invalid && !ExDeclType->isDependentType()) { 13122 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13123 // Insulate this from anything else we might currently be parsing. 13124 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 13125 13126 // C++ [except.handle]p16: 13127 // The object declared in an exception-declaration or, if the 13128 // exception-declaration does not specify a name, a temporary (12.2) is 13129 // copy-initialized (8.5) from the exception object. [...] 13130 // The object is destroyed when the handler exits, after the destruction 13131 // of any automatic objects initialized within the handler. 13132 // 13133 // We just pretend to initialize the object with itself, then make sure 13134 // it can be destroyed later. 13135 QualType initType = Context.getExceptionObjectType(ExDeclType); 13136 13137 InitializedEntity entity = 13138 InitializedEntity::InitializeVariable(ExDecl); 13139 InitializationKind initKind = 13140 InitializationKind::CreateCopy(Loc, SourceLocation()); 13141 13142 Expr *opaqueValue = 13143 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13144 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13145 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13146 if (result.isInvalid()) 13147 Invalid = true; 13148 else { 13149 // If the constructor used was non-trivial, set this as the 13150 // "initializer". 13151 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13152 if (!construct->getConstructor()->isTrivial()) { 13153 Expr *init = MaybeCreateExprWithCleanups(construct); 13154 ExDecl->setInit(init); 13155 } 13156 13157 // And make sure it's destructable. 13158 FinalizeVarWithDestructor(ExDecl, recordType); 13159 } 13160 } 13161 } 13162 13163 if (Invalid) 13164 ExDecl->setInvalidDecl(); 13165 13166 return ExDecl; 13167 } 13168 13169 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13170 /// handler. 13171 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13172 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13173 bool Invalid = D.isInvalidType(); 13174 13175 // Check for unexpanded parameter packs. 13176 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13177 UPPC_ExceptionType)) { 13178 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13179 D.getIdentifierLoc()); 13180 Invalid = true; 13181 } 13182 13183 IdentifierInfo *II = D.getIdentifier(); 13184 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13185 LookupOrdinaryName, 13186 ForRedeclaration)) { 13187 // The scope should be freshly made just for us. There is just no way 13188 // it contains any previous declaration, except for function parameters in 13189 // a function-try-block's catch statement. 13190 assert(!S->isDeclScope(PrevDecl)); 13191 if (isDeclInScope(PrevDecl, CurContext, S)) { 13192 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13193 << D.getIdentifier(); 13194 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13195 Invalid = true; 13196 } else if (PrevDecl->isTemplateParameter()) 13197 // Maybe we will complain about the shadowed template parameter. 13198 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13199 } 13200 13201 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13202 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13203 << D.getCXXScopeSpec().getRange(); 13204 Invalid = true; 13205 } 13206 13207 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13208 D.getLocStart(), 13209 D.getIdentifierLoc(), 13210 D.getIdentifier()); 13211 if (Invalid) 13212 ExDecl->setInvalidDecl(); 13213 13214 // Add the exception declaration into this scope. 13215 if (II) 13216 PushOnScopeChains(ExDecl, S); 13217 else 13218 CurContext->addDecl(ExDecl); 13219 13220 ProcessDeclAttributes(S, ExDecl, D); 13221 return ExDecl; 13222 } 13223 13224 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13225 Expr *AssertExpr, 13226 Expr *AssertMessageExpr, 13227 SourceLocation RParenLoc) { 13228 StringLiteral *AssertMessage = 13229 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13230 13231 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13232 return nullptr; 13233 13234 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13235 AssertMessage, RParenLoc, false); 13236 } 13237 13238 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13239 Expr *AssertExpr, 13240 StringLiteral *AssertMessage, 13241 SourceLocation RParenLoc, 13242 bool Failed) { 13243 assert(AssertExpr != nullptr && "Expected non-null condition"); 13244 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13245 !Failed) { 13246 // In a static_assert-declaration, the constant-expression shall be a 13247 // constant expression that can be contextually converted to bool. 13248 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13249 if (Converted.isInvalid()) 13250 Failed = true; 13251 13252 llvm::APSInt Cond; 13253 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13254 diag::err_static_assert_expression_is_not_constant, 13255 /*AllowFold=*/false).isInvalid()) 13256 Failed = true; 13257 13258 if (!Failed && !Cond) { 13259 SmallString<256> MsgBuffer; 13260 llvm::raw_svector_ostream Msg(MsgBuffer); 13261 if (AssertMessage) 13262 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13263 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13264 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13265 Failed = true; 13266 } 13267 } 13268 13269 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13270 AssertExpr, AssertMessage, RParenLoc, 13271 Failed); 13272 13273 CurContext->addDecl(Decl); 13274 return Decl; 13275 } 13276 13277 /// \brief Perform semantic analysis of the given friend type declaration. 13278 /// 13279 /// \returns A friend declaration that. 13280 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13281 SourceLocation FriendLoc, 13282 TypeSourceInfo *TSInfo) { 13283 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13284 13285 QualType T = TSInfo->getType(); 13286 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13287 13288 // C++03 [class.friend]p2: 13289 // An elaborated-type-specifier shall be used in a friend declaration 13290 // for a class.* 13291 // 13292 // * The class-key of the elaborated-type-specifier is required. 13293 if (!CodeSynthesisContexts.empty()) { 13294 // Do not complain about the form of friend template types during any kind 13295 // of code synthesis. For template instantiation, we will have complained 13296 // when the template was defined. 13297 } else { 13298 if (!T->isElaboratedTypeSpecifier()) { 13299 // If we evaluated the type to a record type, suggest putting 13300 // a tag in front. 13301 if (const RecordType *RT = T->getAs<RecordType>()) { 13302 RecordDecl *RD = RT->getDecl(); 13303 13304 SmallString<16> InsertionText(" "); 13305 InsertionText += RD->getKindName(); 13306 13307 Diag(TypeRange.getBegin(), 13308 getLangOpts().CPlusPlus11 ? 13309 diag::warn_cxx98_compat_unelaborated_friend_type : 13310 diag::ext_unelaborated_friend_type) 13311 << (unsigned) RD->getTagKind() 13312 << T 13313 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13314 InsertionText); 13315 } else { 13316 Diag(FriendLoc, 13317 getLangOpts().CPlusPlus11 ? 13318 diag::warn_cxx98_compat_nonclass_type_friend : 13319 diag::ext_nonclass_type_friend) 13320 << T 13321 << TypeRange; 13322 } 13323 } else if (T->getAs<EnumType>()) { 13324 Diag(FriendLoc, 13325 getLangOpts().CPlusPlus11 ? 13326 diag::warn_cxx98_compat_enum_friend : 13327 diag::ext_enum_friend) 13328 << T 13329 << TypeRange; 13330 } 13331 13332 // C++11 [class.friend]p3: 13333 // A friend declaration that does not declare a function shall have one 13334 // of the following forms: 13335 // friend elaborated-type-specifier ; 13336 // friend simple-type-specifier ; 13337 // friend typename-specifier ; 13338 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13339 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13340 } 13341 13342 // If the type specifier in a friend declaration designates a (possibly 13343 // cv-qualified) class type, that class is declared as a friend; otherwise, 13344 // the friend declaration is ignored. 13345 return FriendDecl::Create(Context, CurContext, 13346 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13347 FriendLoc); 13348 } 13349 13350 /// Handle a friend tag declaration where the scope specifier was 13351 /// templated. 13352 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13353 unsigned TagSpec, SourceLocation TagLoc, 13354 CXXScopeSpec &SS, 13355 IdentifierInfo *Name, 13356 SourceLocation NameLoc, 13357 AttributeList *Attr, 13358 MultiTemplateParamsArg TempParamLists) { 13359 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13360 13361 bool IsMemberSpecialization = false; 13362 bool Invalid = false; 13363 13364 if (TemplateParameterList *TemplateParams = 13365 MatchTemplateParametersToScopeSpecifier( 13366 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13367 IsMemberSpecialization, Invalid)) { 13368 if (TemplateParams->size() > 0) { 13369 // This is a declaration of a class template. 13370 if (Invalid) 13371 return nullptr; 13372 13373 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13374 NameLoc, Attr, TemplateParams, AS_public, 13375 /*ModulePrivateLoc=*/SourceLocation(), 13376 FriendLoc, TempParamLists.size() - 1, 13377 TempParamLists.data()).get(); 13378 } else { 13379 // The "template<>" header is extraneous. 13380 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13381 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13382 IsMemberSpecialization = true; 13383 } 13384 } 13385 13386 if (Invalid) return nullptr; 13387 13388 bool isAllExplicitSpecializations = true; 13389 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13390 if (TempParamLists[I]->size()) { 13391 isAllExplicitSpecializations = false; 13392 break; 13393 } 13394 } 13395 13396 // FIXME: don't ignore attributes. 13397 13398 // If it's explicit specializations all the way down, just forget 13399 // about the template header and build an appropriate non-templated 13400 // friend. TODO: for source fidelity, remember the headers. 13401 if (isAllExplicitSpecializations) { 13402 if (SS.isEmpty()) { 13403 bool Owned = false; 13404 bool IsDependent = false; 13405 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13406 Attr, AS_public, 13407 /*ModulePrivateLoc=*/SourceLocation(), 13408 MultiTemplateParamsArg(), Owned, IsDependent, 13409 /*ScopedEnumKWLoc=*/SourceLocation(), 13410 /*ScopedEnumUsesClassTag=*/false, 13411 /*UnderlyingType=*/TypeResult(), 13412 /*IsTypeSpecifier=*/false); 13413 } 13414 13415 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13416 ElaboratedTypeKeyword Keyword 13417 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13418 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13419 *Name, NameLoc); 13420 if (T.isNull()) 13421 return nullptr; 13422 13423 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13424 if (isa<DependentNameType>(T)) { 13425 DependentNameTypeLoc TL = 13426 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13427 TL.setElaboratedKeywordLoc(TagLoc); 13428 TL.setQualifierLoc(QualifierLoc); 13429 TL.setNameLoc(NameLoc); 13430 } else { 13431 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13432 TL.setElaboratedKeywordLoc(TagLoc); 13433 TL.setQualifierLoc(QualifierLoc); 13434 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13435 } 13436 13437 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13438 TSI, FriendLoc, TempParamLists); 13439 Friend->setAccess(AS_public); 13440 CurContext->addDecl(Friend); 13441 return Friend; 13442 } 13443 13444 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13445 13446 13447 13448 // Handle the case of a templated-scope friend class. e.g. 13449 // template <class T> class A<T>::B; 13450 // FIXME: we don't support these right now. 13451 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13452 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13453 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13454 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13455 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13456 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13457 TL.setElaboratedKeywordLoc(TagLoc); 13458 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13459 TL.setNameLoc(NameLoc); 13460 13461 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13462 TSI, FriendLoc, TempParamLists); 13463 Friend->setAccess(AS_public); 13464 Friend->setUnsupportedFriend(true); 13465 CurContext->addDecl(Friend); 13466 return Friend; 13467 } 13468 13469 13470 /// Handle a friend type declaration. This works in tandem with 13471 /// ActOnTag. 13472 /// 13473 /// Notes on friend class templates: 13474 /// 13475 /// We generally treat friend class declarations as if they were 13476 /// declaring a class. So, for example, the elaborated type specifier 13477 /// in a friend declaration is required to obey the restrictions of a 13478 /// class-head (i.e. no typedefs in the scope chain), template 13479 /// parameters are required to match up with simple template-ids, &c. 13480 /// However, unlike when declaring a template specialization, it's 13481 /// okay to refer to a template specialization without an empty 13482 /// template parameter declaration, e.g. 13483 /// friend class A<T>::B<unsigned>; 13484 /// We permit this as a special case; if there are any template 13485 /// parameters present at all, require proper matching, i.e. 13486 /// template <> template \<class T> friend class A<int>::B; 13487 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13488 MultiTemplateParamsArg TempParams) { 13489 SourceLocation Loc = DS.getLocStart(); 13490 13491 assert(DS.isFriendSpecified()); 13492 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13493 13494 // Try to convert the decl specifier to a type. This works for 13495 // friend templates because ActOnTag never produces a ClassTemplateDecl 13496 // for a TUK_Friend. 13497 Declarator TheDeclarator(DS, Declarator::MemberContext); 13498 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13499 QualType T = TSI->getType(); 13500 if (TheDeclarator.isInvalidType()) 13501 return nullptr; 13502 13503 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13504 return nullptr; 13505 13506 // This is definitely an error in C++98. It's probably meant to 13507 // be forbidden in C++0x, too, but the specification is just 13508 // poorly written. 13509 // 13510 // The problem is with declarations like the following: 13511 // template <T> friend A<T>::foo; 13512 // where deciding whether a class C is a friend or not now hinges 13513 // on whether there exists an instantiation of A that causes 13514 // 'foo' to equal C. There are restrictions on class-heads 13515 // (which we declare (by fiat) elaborated friend declarations to 13516 // be) that makes this tractable. 13517 // 13518 // FIXME: handle "template <> friend class A<T>;", which 13519 // is possibly well-formed? Who even knows? 13520 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13521 Diag(Loc, diag::err_tagless_friend_type_template) 13522 << DS.getSourceRange(); 13523 return nullptr; 13524 } 13525 13526 // C++98 [class.friend]p1: A friend of a class is a function 13527 // or class that is not a member of the class . . . 13528 // This is fixed in DR77, which just barely didn't make the C++03 13529 // deadline. It's also a very silly restriction that seriously 13530 // affects inner classes and which nobody else seems to implement; 13531 // thus we never diagnose it, not even in -pedantic. 13532 // 13533 // But note that we could warn about it: it's always useless to 13534 // friend one of your own members (it's not, however, worthless to 13535 // friend a member of an arbitrary specialization of your template). 13536 13537 Decl *D; 13538 if (!TempParams.empty()) 13539 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13540 TempParams, 13541 TSI, 13542 DS.getFriendSpecLoc()); 13543 else 13544 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13545 13546 if (!D) 13547 return nullptr; 13548 13549 D->setAccess(AS_public); 13550 CurContext->addDecl(D); 13551 13552 return D; 13553 } 13554 13555 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13556 MultiTemplateParamsArg TemplateParams) { 13557 const DeclSpec &DS = D.getDeclSpec(); 13558 13559 assert(DS.isFriendSpecified()); 13560 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13561 13562 SourceLocation Loc = D.getIdentifierLoc(); 13563 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13564 13565 // C++ [class.friend]p1 13566 // A friend of a class is a function or class.... 13567 // Note that this sees through typedefs, which is intended. 13568 // It *doesn't* see through dependent types, which is correct 13569 // according to [temp.arg.type]p3: 13570 // If a declaration acquires a function type through a 13571 // type dependent on a template-parameter and this causes 13572 // a declaration that does not use the syntactic form of a 13573 // function declarator to have a function type, the program 13574 // is ill-formed. 13575 if (!TInfo->getType()->isFunctionType()) { 13576 Diag(Loc, diag::err_unexpected_friend); 13577 13578 // It might be worthwhile to try to recover by creating an 13579 // appropriate declaration. 13580 return nullptr; 13581 } 13582 13583 // C++ [namespace.memdef]p3 13584 // - If a friend declaration in a non-local class first declares a 13585 // class or function, the friend class or function is a member 13586 // of the innermost enclosing namespace. 13587 // - The name of the friend is not found by simple name lookup 13588 // until a matching declaration is provided in that namespace 13589 // scope (either before or after the class declaration granting 13590 // friendship). 13591 // - If a friend function is called, its name may be found by the 13592 // name lookup that considers functions from namespaces and 13593 // classes associated with the types of the function arguments. 13594 // - When looking for a prior declaration of a class or a function 13595 // declared as a friend, scopes outside the innermost enclosing 13596 // namespace scope are not considered. 13597 13598 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13599 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13600 DeclarationName Name = NameInfo.getName(); 13601 assert(Name); 13602 13603 // Check for unexpanded parameter packs. 13604 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13605 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13606 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13607 return nullptr; 13608 13609 // The context we found the declaration in, or in which we should 13610 // create the declaration. 13611 DeclContext *DC; 13612 Scope *DCScope = S; 13613 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13614 ForRedeclaration); 13615 13616 // There are five cases here. 13617 // - There's no scope specifier and we're in a local class. Only look 13618 // for functions declared in the immediately-enclosing block scope. 13619 // We recover from invalid scope qualifiers as if they just weren't there. 13620 FunctionDecl *FunctionContainingLocalClass = nullptr; 13621 if ((SS.isInvalid() || !SS.isSet()) && 13622 (FunctionContainingLocalClass = 13623 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13624 // C++11 [class.friend]p11: 13625 // If a friend declaration appears in a local class and the name 13626 // specified is an unqualified name, a prior declaration is 13627 // looked up without considering scopes that are outside the 13628 // innermost enclosing non-class scope. For a friend function 13629 // declaration, if there is no prior declaration, the program is 13630 // ill-formed. 13631 13632 // Find the innermost enclosing non-class scope. This is the block 13633 // scope containing the local class definition (or for a nested class, 13634 // the outer local class). 13635 DCScope = S->getFnParent(); 13636 13637 // Look up the function name in the scope. 13638 Previous.clear(LookupLocalFriendName); 13639 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13640 13641 if (!Previous.empty()) { 13642 // All possible previous declarations must have the same context: 13643 // either they were declared at block scope or they are members of 13644 // one of the enclosing local classes. 13645 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13646 } else { 13647 // This is ill-formed, but provide the context that we would have 13648 // declared the function in, if we were permitted to, for error recovery. 13649 DC = FunctionContainingLocalClass; 13650 } 13651 adjustContextForLocalExternDecl(DC); 13652 13653 // C++ [class.friend]p6: 13654 // A function can be defined in a friend declaration of a class if and 13655 // only if the class is a non-local class (9.8), the function name is 13656 // unqualified, and the function has namespace scope. 13657 if (D.isFunctionDefinition()) { 13658 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13659 } 13660 13661 // - There's no scope specifier, in which case we just go to the 13662 // appropriate scope and look for a function or function template 13663 // there as appropriate. 13664 } else if (SS.isInvalid() || !SS.isSet()) { 13665 // C++11 [namespace.memdef]p3: 13666 // If the name in a friend declaration is neither qualified nor 13667 // a template-id and the declaration is a function or an 13668 // elaborated-type-specifier, the lookup to determine whether 13669 // the entity has been previously declared shall not consider 13670 // any scopes outside the innermost enclosing namespace. 13671 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 13672 13673 // Find the appropriate context according to the above. 13674 DC = CurContext; 13675 13676 // Skip class contexts. If someone can cite chapter and verse 13677 // for this behavior, that would be nice --- it's what GCC and 13678 // EDG do, and it seems like a reasonable intent, but the spec 13679 // really only says that checks for unqualified existing 13680 // declarations should stop at the nearest enclosing namespace, 13681 // not that they should only consider the nearest enclosing 13682 // namespace. 13683 while (DC->isRecord()) 13684 DC = DC->getParent(); 13685 13686 DeclContext *LookupDC = DC; 13687 while (LookupDC->isTransparentContext()) 13688 LookupDC = LookupDC->getParent(); 13689 13690 while (true) { 13691 LookupQualifiedName(Previous, LookupDC); 13692 13693 if (!Previous.empty()) { 13694 DC = LookupDC; 13695 break; 13696 } 13697 13698 if (isTemplateId) { 13699 if (isa<TranslationUnitDecl>(LookupDC)) break; 13700 } else { 13701 if (LookupDC->isFileContext()) break; 13702 } 13703 LookupDC = LookupDC->getParent(); 13704 } 13705 13706 DCScope = getScopeForDeclContext(S, DC); 13707 13708 // - There's a non-dependent scope specifier, in which case we 13709 // compute it and do a previous lookup there for a function 13710 // or function template. 13711 } else if (!SS.getScopeRep()->isDependent()) { 13712 DC = computeDeclContext(SS); 13713 if (!DC) return nullptr; 13714 13715 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13716 13717 LookupQualifiedName(Previous, DC); 13718 13719 // Ignore things found implicitly in the wrong scope. 13720 // TODO: better diagnostics for this case. Suggesting the right 13721 // qualified scope would be nice... 13722 LookupResult::Filter F = Previous.makeFilter(); 13723 while (F.hasNext()) { 13724 NamedDecl *D = F.next(); 13725 if (!DC->InEnclosingNamespaceSetOf( 13726 D->getDeclContext()->getRedeclContext())) 13727 F.erase(); 13728 } 13729 F.done(); 13730 13731 if (Previous.empty()) { 13732 D.setInvalidType(); 13733 Diag(Loc, diag::err_qualified_friend_not_found) 13734 << Name << TInfo->getType(); 13735 return nullptr; 13736 } 13737 13738 // C++ [class.friend]p1: A friend of a class is a function or 13739 // class that is not a member of the class . . . 13740 if (DC->Equals(CurContext)) 13741 Diag(DS.getFriendSpecLoc(), 13742 getLangOpts().CPlusPlus11 ? 13743 diag::warn_cxx98_compat_friend_is_member : 13744 diag::err_friend_is_member); 13745 13746 if (D.isFunctionDefinition()) { 13747 // C++ [class.friend]p6: 13748 // A function can be defined in a friend declaration of a class if and 13749 // only if the class is a non-local class (9.8), the function name is 13750 // unqualified, and the function has namespace scope. 13751 SemaDiagnosticBuilder DB 13752 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 13753 13754 DB << SS.getScopeRep(); 13755 if (DC->isFileContext()) 13756 DB << FixItHint::CreateRemoval(SS.getRange()); 13757 SS.clear(); 13758 } 13759 13760 // - There's a scope specifier that does not match any template 13761 // parameter lists, in which case we use some arbitrary context, 13762 // create a method or method template, and wait for instantiation. 13763 // - There's a scope specifier that does match some template 13764 // parameter lists, which we don't handle right now. 13765 } else { 13766 if (D.isFunctionDefinition()) { 13767 // C++ [class.friend]p6: 13768 // A function can be defined in a friend declaration of a class if and 13769 // only if the class is a non-local class (9.8), the function name is 13770 // unqualified, and the function has namespace scope. 13771 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 13772 << SS.getScopeRep(); 13773 } 13774 13775 DC = CurContext; 13776 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 13777 } 13778 13779 if (!DC->isRecord()) { 13780 int DiagArg = -1; 13781 switch (D.getName().getKind()) { 13782 case UnqualifiedId::IK_ConstructorTemplateId: 13783 case UnqualifiedId::IK_ConstructorName: 13784 DiagArg = 0; 13785 break; 13786 case UnqualifiedId::IK_DestructorName: 13787 DiagArg = 1; 13788 break; 13789 case UnqualifiedId::IK_ConversionFunctionId: 13790 DiagArg = 2; 13791 break; 13792 case UnqualifiedId::IK_DeductionGuideName: 13793 DiagArg = 3; 13794 break; 13795 case UnqualifiedId::IK_Identifier: 13796 case UnqualifiedId::IK_ImplicitSelfParam: 13797 case UnqualifiedId::IK_LiteralOperatorId: 13798 case UnqualifiedId::IK_OperatorFunctionId: 13799 case UnqualifiedId::IK_TemplateId: 13800 break; 13801 } 13802 // This implies that it has to be an operator or function. 13803 if (DiagArg >= 0) { 13804 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 13805 return nullptr; 13806 } 13807 } 13808 13809 // FIXME: This is an egregious hack to cope with cases where the scope stack 13810 // does not contain the declaration context, i.e., in an out-of-line 13811 // definition of a class. 13812 Scope FakeDCScope(S, Scope::DeclScope, Diags); 13813 if (!DCScope) { 13814 FakeDCScope.setEntity(DC); 13815 DCScope = &FakeDCScope; 13816 } 13817 13818 bool AddToScope = true; 13819 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 13820 TemplateParams, AddToScope); 13821 if (!ND) return nullptr; 13822 13823 assert(ND->getLexicalDeclContext() == CurContext); 13824 13825 // If we performed typo correction, we might have added a scope specifier 13826 // and changed the decl context. 13827 DC = ND->getDeclContext(); 13828 13829 // Add the function declaration to the appropriate lookup tables, 13830 // adjusting the redeclarations list as necessary. We don't 13831 // want to do this yet if the friending class is dependent. 13832 // 13833 // Also update the scope-based lookup if the target context's 13834 // lookup context is in lexical scope. 13835 if (!CurContext->isDependentContext()) { 13836 DC = DC->getRedeclContext(); 13837 DC->makeDeclVisibleInContext(ND); 13838 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13839 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 13840 } 13841 13842 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 13843 D.getIdentifierLoc(), ND, 13844 DS.getFriendSpecLoc()); 13845 FrD->setAccess(AS_public); 13846 CurContext->addDecl(FrD); 13847 13848 if (ND->isInvalidDecl()) { 13849 FrD->setInvalidDecl(); 13850 } else { 13851 if (DC->isRecord()) CheckFriendAccess(ND); 13852 13853 FunctionDecl *FD; 13854 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 13855 FD = FTD->getTemplatedDecl(); 13856 else 13857 FD = cast<FunctionDecl>(ND); 13858 13859 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 13860 // default argument expression, that declaration shall be a definition 13861 // and shall be the only declaration of the function or function 13862 // template in the translation unit. 13863 if (functionDeclHasDefaultArgument(FD)) { 13864 // We can't look at FD->getPreviousDecl() because it may not have been set 13865 // if we're in a dependent context. If the function is known to be a 13866 // redeclaration, we will have narrowed Previous down to the right decl. 13867 if (D.isRedeclaration()) { 13868 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 13869 Diag(Previous.getRepresentativeDecl()->getLocation(), 13870 diag::note_previous_declaration); 13871 } else if (!D.isFunctionDefinition()) 13872 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 13873 } 13874 13875 // Mark templated-scope function declarations as unsupported. 13876 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 13877 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 13878 << SS.getScopeRep() << SS.getRange() 13879 << cast<CXXRecordDecl>(CurContext); 13880 FrD->setUnsupportedFriend(true); 13881 } 13882 } 13883 13884 return ND; 13885 } 13886 13887 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 13888 AdjustDeclIfTemplate(Dcl); 13889 13890 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 13891 if (!Fn) { 13892 Diag(DelLoc, diag::err_deleted_non_function); 13893 return; 13894 } 13895 13896 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 13897 // Don't consider the implicit declaration we generate for explicit 13898 // specializations. FIXME: Do not generate these implicit declarations. 13899 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 13900 Prev->getPreviousDecl()) && 13901 !Prev->isDefined()) { 13902 Diag(DelLoc, diag::err_deleted_decl_not_first); 13903 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 13904 Prev->isImplicit() ? diag::note_previous_implicit_declaration 13905 : diag::note_previous_declaration); 13906 } 13907 // If the declaration wasn't the first, we delete the function anyway for 13908 // recovery. 13909 Fn = Fn->getCanonicalDecl(); 13910 } 13911 13912 // dllimport/dllexport cannot be deleted. 13913 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 13914 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 13915 Fn->setInvalidDecl(); 13916 } 13917 13918 if (Fn->isDeleted()) 13919 return; 13920 13921 // See if we're deleting a function which is already known to override a 13922 // non-deleted virtual function. 13923 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 13924 bool IssuedDiagnostic = false; 13925 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 13926 E = MD->end_overridden_methods(); 13927 I != E; ++I) { 13928 if (!(*MD->begin_overridden_methods())->isDeleted()) { 13929 if (!IssuedDiagnostic) { 13930 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 13931 IssuedDiagnostic = true; 13932 } 13933 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 13934 } 13935 } 13936 // If this function was implicitly deleted because it was defaulted, 13937 // explain why it was deleted. 13938 if (IssuedDiagnostic && MD->isDefaulted()) 13939 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 13940 /*Diagnose*/true); 13941 } 13942 13943 // C++11 [basic.start.main]p3: 13944 // A program that defines main as deleted [...] is ill-formed. 13945 if (Fn->isMain()) 13946 Diag(DelLoc, diag::err_deleted_main); 13947 13948 // C++11 [dcl.fct.def.delete]p4: 13949 // A deleted function is implicitly inline. 13950 Fn->setImplicitlyInline(); 13951 Fn->setDeletedAsWritten(); 13952 } 13953 13954 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 13955 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 13956 13957 if (MD) { 13958 if (MD->getParent()->isDependentType()) { 13959 MD->setDefaulted(); 13960 MD->setExplicitlyDefaulted(); 13961 return; 13962 } 13963 13964 CXXSpecialMember Member = getSpecialMember(MD); 13965 if (Member == CXXInvalid) { 13966 if (!MD->isInvalidDecl()) 13967 Diag(DefaultLoc, diag::err_default_special_members); 13968 return; 13969 } 13970 13971 MD->setDefaulted(); 13972 MD->setExplicitlyDefaulted(); 13973 13974 // If this definition appears within the record, do the checking when 13975 // the record is complete. 13976 const FunctionDecl *Primary = MD; 13977 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 13978 // Ask the template instantiation pattern that actually had the 13979 // '= default' on it. 13980 Primary = Pattern; 13981 13982 // If the method was defaulted on its first declaration, we will have 13983 // already performed the checking in CheckCompletedCXXClass. Such a 13984 // declaration doesn't trigger an implicit definition. 13985 if (Primary->getCanonicalDecl()->isDefaulted()) 13986 return; 13987 13988 CheckExplicitlyDefaultedSpecialMember(MD); 13989 13990 if (!MD->isInvalidDecl()) 13991 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 13992 } else { 13993 Diag(DefaultLoc, diag::err_default_special_members); 13994 } 13995 } 13996 13997 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 13998 for (Stmt *SubStmt : S->children()) { 13999 if (!SubStmt) 14000 continue; 14001 if (isa<ReturnStmt>(SubStmt)) 14002 Self.Diag(SubStmt->getLocStart(), 14003 diag::err_return_in_constructor_handler); 14004 if (!isa<Expr>(SubStmt)) 14005 SearchForReturnInStmt(Self, SubStmt); 14006 } 14007 } 14008 14009 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14010 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14011 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14012 SearchForReturnInStmt(*this, Handler); 14013 } 14014 } 14015 14016 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14017 const CXXMethodDecl *Old) { 14018 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 14019 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 14020 14021 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14022 14023 // If the calling conventions match, everything is fine 14024 if (NewCC == OldCC) 14025 return false; 14026 14027 // If the calling conventions mismatch because the new function is static, 14028 // suppress the calling convention mismatch error; the error about static 14029 // function override (err_static_overrides_virtual from 14030 // Sema::CheckFunctionDeclaration) is more clear. 14031 if (New->getStorageClass() == SC_Static) 14032 return false; 14033 14034 Diag(New->getLocation(), 14035 diag::err_conflicting_overriding_cc_attributes) 14036 << New->getDeclName() << New->getType() << Old->getType(); 14037 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14038 return true; 14039 } 14040 14041 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14042 const CXXMethodDecl *Old) { 14043 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14044 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14045 14046 if (Context.hasSameType(NewTy, OldTy) || 14047 NewTy->isDependentType() || OldTy->isDependentType()) 14048 return false; 14049 14050 // Check if the return types are covariant 14051 QualType NewClassTy, OldClassTy; 14052 14053 /// Both types must be pointers or references to classes. 14054 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14055 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14056 NewClassTy = NewPT->getPointeeType(); 14057 OldClassTy = OldPT->getPointeeType(); 14058 } 14059 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14060 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14061 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14062 NewClassTy = NewRT->getPointeeType(); 14063 OldClassTy = OldRT->getPointeeType(); 14064 } 14065 } 14066 } 14067 14068 // The return types aren't either both pointers or references to a class type. 14069 if (NewClassTy.isNull()) { 14070 Diag(New->getLocation(), 14071 diag::err_different_return_type_for_overriding_virtual_function) 14072 << New->getDeclName() << NewTy << OldTy 14073 << New->getReturnTypeSourceRange(); 14074 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14075 << Old->getReturnTypeSourceRange(); 14076 14077 return true; 14078 } 14079 14080 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14081 // C++14 [class.virtual]p8: 14082 // If the class type in the covariant return type of D::f differs from 14083 // that of B::f, the class type in the return type of D::f shall be 14084 // complete at the point of declaration of D::f or shall be the class 14085 // type D. 14086 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14087 if (!RT->isBeingDefined() && 14088 RequireCompleteType(New->getLocation(), NewClassTy, 14089 diag::err_covariant_return_incomplete, 14090 New->getDeclName())) 14091 return true; 14092 } 14093 14094 // Check if the new class derives from the old class. 14095 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14096 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14097 << New->getDeclName() << NewTy << OldTy 14098 << New->getReturnTypeSourceRange(); 14099 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14100 << Old->getReturnTypeSourceRange(); 14101 return true; 14102 } 14103 14104 // Check if we the conversion from derived to base is valid. 14105 if (CheckDerivedToBaseConversion( 14106 NewClassTy, OldClassTy, 14107 diag::err_covariant_return_inaccessible_base, 14108 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14109 New->getLocation(), New->getReturnTypeSourceRange(), 14110 New->getDeclName(), nullptr)) { 14111 // FIXME: this note won't trigger for delayed access control 14112 // diagnostics, and it's impossible to get an undelayed error 14113 // here from access control during the original parse because 14114 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14115 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14116 << Old->getReturnTypeSourceRange(); 14117 return true; 14118 } 14119 } 14120 14121 // The qualifiers of the return types must be the same. 14122 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14123 Diag(New->getLocation(), 14124 diag::err_covariant_return_type_different_qualifications) 14125 << New->getDeclName() << NewTy << OldTy 14126 << New->getReturnTypeSourceRange(); 14127 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14128 << Old->getReturnTypeSourceRange(); 14129 return true; 14130 } 14131 14132 14133 // The new class type must have the same or less qualifiers as the old type. 14134 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14135 Diag(New->getLocation(), 14136 diag::err_covariant_return_type_class_type_more_qualified) 14137 << New->getDeclName() << NewTy << OldTy 14138 << New->getReturnTypeSourceRange(); 14139 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14140 << Old->getReturnTypeSourceRange(); 14141 return true; 14142 } 14143 14144 return false; 14145 } 14146 14147 /// \brief Mark the given method pure. 14148 /// 14149 /// \param Method the method to be marked pure. 14150 /// 14151 /// \param InitRange the source range that covers the "0" initializer. 14152 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14153 SourceLocation EndLoc = InitRange.getEnd(); 14154 if (EndLoc.isValid()) 14155 Method->setRangeEnd(EndLoc); 14156 14157 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14158 Method->setPure(); 14159 return false; 14160 } 14161 14162 if (!Method->isInvalidDecl()) 14163 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14164 << Method->getDeclName() << InitRange; 14165 return true; 14166 } 14167 14168 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14169 if (D->getFriendObjectKind()) 14170 Diag(D->getLocation(), diag::err_pure_friend); 14171 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14172 CheckPureMethod(M, ZeroLoc); 14173 else 14174 Diag(D->getLocation(), diag::err_illegal_initializer); 14175 } 14176 14177 /// \brief Determine whether the given declaration is a static data member. 14178 static bool isStaticDataMember(const Decl *D) { 14179 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14180 return Var->isStaticDataMember(); 14181 14182 return false; 14183 } 14184 14185 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 14186 /// an initializer for the out-of-line declaration 'Dcl'. The scope 14187 /// is a fresh scope pushed for just this purpose. 14188 /// 14189 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14190 /// static data member of class X, names should be looked up in the scope of 14191 /// class X. 14192 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14193 // If there is no declaration, there was an error parsing it. 14194 if (!D || D->isInvalidDecl()) 14195 return; 14196 14197 // We will always have a nested name specifier here, but this declaration 14198 // might not be out of line if the specifier names the current namespace: 14199 // extern int n; 14200 // int ::n = 0; 14201 if (D->isOutOfLine()) 14202 EnterDeclaratorContext(S, D->getDeclContext()); 14203 14204 // If we are parsing the initializer for a static data member, push a 14205 // new expression evaluation context that is associated with this static 14206 // data member. 14207 if (isStaticDataMember(D)) 14208 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 14209 } 14210 14211 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 14212 /// initializer for the out-of-line declaration 'D'. 14213 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14214 // If there is no declaration, there was an error parsing it. 14215 if (!D || D->isInvalidDecl()) 14216 return; 14217 14218 if (isStaticDataMember(D)) 14219 PopExpressionEvaluationContext(); 14220 14221 if (D->isOutOfLine()) 14222 ExitDeclaratorContext(S); 14223 } 14224 14225 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14226 /// C++ if/switch/while/for statement. 14227 /// e.g: "if (int x = f()) {...}" 14228 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14229 // C++ 6.4p2: 14230 // The declarator shall not specify a function or an array. 14231 // The type-specifier-seq shall not contain typedef and shall not declare a 14232 // new class or enumeration. 14233 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14234 "Parser allowed 'typedef' as storage class of condition decl."); 14235 14236 Decl *Dcl = ActOnDeclarator(S, D); 14237 if (!Dcl) 14238 return true; 14239 14240 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14241 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14242 << D.getSourceRange(); 14243 return true; 14244 } 14245 14246 return Dcl; 14247 } 14248 14249 void Sema::LoadExternalVTableUses() { 14250 if (!ExternalSource) 14251 return; 14252 14253 SmallVector<ExternalVTableUse, 4> VTables; 14254 ExternalSource->ReadUsedVTables(VTables); 14255 SmallVector<VTableUse, 4> NewUses; 14256 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14257 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14258 = VTablesUsed.find(VTables[I].Record); 14259 // Even if a definition wasn't required before, it may be required now. 14260 if (Pos != VTablesUsed.end()) { 14261 if (!Pos->second && VTables[I].DefinitionRequired) 14262 Pos->second = true; 14263 continue; 14264 } 14265 14266 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14267 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14268 } 14269 14270 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14271 } 14272 14273 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14274 bool DefinitionRequired) { 14275 // Ignore any vtable uses in unevaluated operands or for classes that do 14276 // not have a vtable. 14277 if (!Class->isDynamicClass() || Class->isDependentContext() || 14278 CurContext->isDependentContext() || isUnevaluatedContext()) 14279 return; 14280 14281 // Try to insert this class into the map. 14282 LoadExternalVTableUses(); 14283 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14284 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14285 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14286 if (!Pos.second) { 14287 // If we already had an entry, check to see if we are promoting this vtable 14288 // to require a definition. If so, we need to reappend to the VTableUses 14289 // list, since we may have already processed the first entry. 14290 if (DefinitionRequired && !Pos.first->second) { 14291 Pos.first->second = true; 14292 } else { 14293 // Otherwise, we can early exit. 14294 return; 14295 } 14296 } else { 14297 // The Microsoft ABI requires that we perform the destructor body 14298 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14299 // the deleting destructor is emitted with the vtable, not with the 14300 // destructor definition as in the Itanium ABI. 14301 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14302 CXXDestructorDecl *DD = Class->getDestructor(); 14303 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14304 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14305 // If this is an out-of-line declaration, marking it referenced will 14306 // not do anything. Manually call CheckDestructor to look up operator 14307 // delete(). 14308 ContextRAII SavedContext(*this, DD); 14309 CheckDestructor(DD); 14310 } else { 14311 MarkFunctionReferenced(Loc, Class->getDestructor()); 14312 } 14313 } 14314 } 14315 } 14316 14317 // Local classes need to have their virtual members marked 14318 // immediately. For all other classes, we mark their virtual members 14319 // at the end of the translation unit. 14320 if (Class->isLocalClass()) 14321 MarkVirtualMembersReferenced(Loc, Class); 14322 else 14323 VTableUses.push_back(std::make_pair(Class, Loc)); 14324 } 14325 14326 bool Sema::DefineUsedVTables() { 14327 LoadExternalVTableUses(); 14328 if (VTableUses.empty()) 14329 return false; 14330 14331 // Note: The VTableUses vector could grow as a result of marking 14332 // the members of a class as "used", so we check the size each 14333 // time through the loop and prefer indices (which are stable) to 14334 // iterators (which are not). 14335 bool DefinedAnything = false; 14336 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14337 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14338 if (!Class) 14339 continue; 14340 TemplateSpecializationKind ClassTSK = 14341 Class->getTemplateSpecializationKind(); 14342 14343 SourceLocation Loc = VTableUses[I].second; 14344 14345 bool DefineVTable = true; 14346 14347 // If this class has a key function, but that key function is 14348 // defined in another translation unit, we don't need to emit the 14349 // vtable even though we're using it. 14350 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14351 if (KeyFunction && !KeyFunction->hasBody()) { 14352 // The key function is in another translation unit. 14353 DefineVTable = false; 14354 TemplateSpecializationKind TSK = 14355 KeyFunction->getTemplateSpecializationKind(); 14356 assert(TSK != TSK_ExplicitInstantiationDefinition && 14357 TSK != TSK_ImplicitInstantiation && 14358 "Instantiations don't have key functions"); 14359 (void)TSK; 14360 } else if (!KeyFunction) { 14361 // If we have a class with no key function that is the subject 14362 // of an explicit instantiation declaration, suppress the 14363 // vtable; it will live with the explicit instantiation 14364 // definition. 14365 bool IsExplicitInstantiationDeclaration = 14366 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14367 for (auto R : Class->redecls()) { 14368 TemplateSpecializationKind TSK 14369 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14370 if (TSK == TSK_ExplicitInstantiationDeclaration) 14371 IsExplicitInstantiationDeclaration = true; 14372 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14373 IsExplicitInstantiationDeclaration = false; 14374 break; 14375 } 14376 } 14377 14378 if (IsExplicitInstantiationDeclaration) 14379 DefineVTable = false; 14380 } 14381 14382 // The exception specifications for all virtual members may be needed even 14383 // if we are not providing an authoritative form of the vtable in this TU. 14384 // We may choose to emit it available_externally anyway. 14385 if (!DefineVTable) { 14386 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14387 continue; 14388 } 14389 14390 // Mark all of the virtual members of this class as referenced, so 14391 // that we can build a vtable. Then, tell the AST consumer that a 14392 // vtable for this class is required. 14393 DefinedAnything = true; 14394 MarkVirtualMembersReferenced(Loc, Class); 14395 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14396 if (VTablesUsed[Canonical]) 14397 Consumer.HandleVTable(Class); 14398 14399 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14400 // no key function or the key function is inlined. Don't warn in C++ ABIs 14401 // that lack key functions, since the user won't be able to make one. 14402 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14403 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14404 const FunctionDecl *KeyFunctionDef = nullptr; 14405 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14406 KeyFunctionDef->isInlined())) { 14407 Diag(Class->getLocation(), 14408 ClassTSK == TSK_ExplicitInstantiationDefinition 14409 ? diag::warn_weak_template_vtable 14410 : diag::warn_weak_vtable) 14411 << Class; 14412 } 14413 } 14414 } 14415 VTableUses.clear(); 14416 14417 return DefinedAnything; 14418 } 14419 14420 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14421 const CXXRecordDecl *RD) { 14422 for (const auto *I : RD->methods()) 14423 if (I->isVirtual() && !I->isPure()) 14424 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14425 } 14426 14427 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14428 const CXXRecordDecl *RD) { 14429 // Mark all functions which will appear in RD's vtable as used. 14430 CXXFinalOverriderMap FinalOverriders; 14431 RD->getFinalOverriders(FinalOverriders); 14432 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14433 E = FinalOverriders.end(); 14434 I != E; ++I) { 14435 for (OverridingMethods::const_iterator OI = I->second.begin(), 14436 OE = I->second.end(); 14437 OI != OE; ++OI) { 14438 assert(OI->second.size() > 0 && "no final overrider"); 14439 CXXMethodDecl *Overrider = OI->second.front().Method; 14440 14441 // C++ [basic.def.odr]p2: 14442 // [...] A virtual member function is used if it is not pure. [...] 14443 if (!Overrider->isPure()) 14444 MarkFunctionReferenced(Loc, Overrider); 14445 } 14446 } 14447 14448 // Only classes that have virtual bases need a VTT. 14449 if (RD->getNumVBases() == 0) 14450 return; 14451 14452 for (const auto &I : RD->bases()) { 14453 const CXXRecordDecl *Base = 14454 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14455 if (Base->getNumVBases() == 0) 14456 continue; 14457 MarkVirtualMembersReferenced(Loc, Base); 14458 } 14459 } 14460 14461 /// SetIvarInitializers - This routine builds initialization ASTs for the 14462 /// Objective-C implementation whose ivars need be initialized. 14463 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14464 if (!getLangOpts().CPlusPlus) 14465 return; 14466 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14467 SmallVector<ObjCIvarDecl*, 8> ivars; 14468 CollectIvarsToConstructOrDestruct(OID, ivars); 14469 if (ivars.empty()) 14470 return; 14471 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14472 for (unsigned i = 0; i < ivars.size(); i++) { 14473 FieldDecl *Field = ivars[i]; 14474 if (Field->isInvalidDecl()) 14475 continue; 14476 14477 CXXCtorInitializer *Member; 14478 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14479 InitializationKind InitKind = 14480 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14481 14482 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14483 ExprResult MemberInit = 14484 InitSeq.Perform(*this, InitEntity, InitKind, None); 14485 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14486 // Note, MemberInit could actually come back empty if no initialization 14487 // is required (e.g., because it would call a trivial default constructor) 14488 if (!MemberInit.get() || MemberInit.isInvalid()) 14489 continue; 14490 14491 Member = 14492 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14493 SourceLocation(), 14494 MemberInit.getAs<Expr>(), 14495 SourceLocation()); 14496 AllToInit.push_back(Member); 14497 14498 // Be sure that the destructor is accessible and is marked as referenced. 14499 if (const RecordType *RecordTy = 14500 Context.getBaseElementType(Field->getType()) 14501 ->getAs<RecordType>()) { 14502 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14503 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14504 MarkFunctionReferenced(Field->getLocation(), Destructor); 14505 CheckDestructorAccess(Field->getLocation(), Destructor, 14506 PDiag(diag::err_access_dtor_ivar) 14507 << Context.getBaseElementType(Field->getType())); 14508 } 14509 } 14510 } 14511 ObjCImplementation->setIvarInitializers(Context, 14512 AllToInit.data(), AllToInit.size()); 14513 } 14514 } 14515 14516 static 14517 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14518 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14519 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14520 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14521 Sema &S) { 14522 if (Ctor->isInvalidDecl()) 14523 return; 14524 14525 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14526 14527 // Target may not be determinable yet, for instance if this is a dependent 14528 // call in an uninstantiated template. 14529 if (Target) { 14530 const FunctionDecl *FNTarget = nullptr; 14531 (void)Target->hasBody(FNTarget); 14532 Target = const_cast<CXXConstructorDecl*>( 14533 cast_or_null<CXXConstructorDecl>(FNTarget)); 14534 } 14535 14536 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14537 // Avoid dereferencing a null pointer here. 14538 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14539 14540 if (!Current.insert(Canonical).second) 14541 return; 14542 14543 // We know that beyond here, we aren't chaining into a cycle. 14544 if (!Target || !Target->isDelegatingConstructor() || 14545 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14546 Valid.insert(Current.begin(), Current.end()); 14547 Current.clear(); 14548 // We've hit a cycle. 14549 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14550 Current.count(TCanonical)) { 14551 // If we haven't diagnosed this cycle yet, do so now. 14552 if (!Invalid.count(TCanonical)) { 14553 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14554 diag::warn_delegating_ctor_cycle) 14555 << Ctor; 14556 14557 // Don't add a note for a function delegating directly to itself. 14558 if (TCanonical != Canonical) 14559 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14560 14561 CXXConstructorDecl *C = Target; 14562 while (C->getCanonicalDecl() != Canonical) { 14563 const FunctionDecl *FNTarget = nullptr; 14564 (void)C->getTargetConstructor()->hasBody(FNTarget); 14565 assert(FNTarget && "Ctor cycle through bodiless function"); 14566 14567 C = const_cast<CXXConstructorDecl*>( 14568 cast<CXXConstructorDecl>(FNTarget)); 14569 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14570 } 14571 } 14572 14573 Invalid.insert(Current.begin(), Current.end()); 14574 Current.clear(); 14575 } else { 14576 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14577 } 14578 } 14579 14580 14581 void Sema::CheckDelegatingCtorCycles() { 14582 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14583 14584 for (DelegatingCtorDeclsType::iterator 14585 I = DelegatingCtorDecls.begin(ExternalSource), 14586 E = DelegatingCtorDecls.end(); 14587 I != E; ++I) 14588 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14589 14590 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14591 CE = Invalid.end(); 14592 CI != CE; ++CI) 14593 (*CI)->setInvalidDecl(); 14594 } 14595 14596 namespace { 14597 /// \brief AST visitor that finds references to the 'this' expression. 14598 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14599 Sema &S; 14600 14601 public: 14602 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14603 14604 bool VisitCXXThisExpr(CXXThisExpr *E) { 14605 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14606 << E->isImplicit(); 14607 return false; 14608 } 14609 }; 14610 } 14611 14612 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14613 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14614 if (!TSInfo) 14615 return false; 14616 14617 TypeLoc TL = TSInfo->getTypeLoc(); 14618 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14619 if (!ProtoTL) 14620 return false; 14621 14622 // C++11 [expr.prim.general]p3: 14623 // [The expression this] shall not appear before the optional 14624 // cv-qualifier-seq and it shall not appear within the declaration of a 14625 // static member function (although its type and value category are defined 14626 // within a static member function as they are within a non-static member 14627 // function). [ Note: this is because declaration matching does not occur 14628 // until the complete declarator is known. - end note ] 14629 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14630 FindCXXThisExpr Finder(*this); 14631 14632 // If the return type came after the cv-qualifier-seq, check it now. 14633 if (Proto->hasTrailingReturn() && 14634 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14635 return true; 14636 14637 // Check the exception specification. 14638 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14639 return true; 14640 14641 return checkThisInStaticMemberFunctionAttributes(Method); 14642 } 14643 14644 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14645 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14646 if (!TSInfo) 14647 return false; 14648 14649 TypeLoc TL = TSInfo->getTypeLoc(); 14650 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14651 if (!ProtoTL) 14652 return false; 14653 14654 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14655 FindCXXThisExpr Finder(*this); 14656 14657 switch (Proto->getExceptionSpecType()) { 14658 case EST_Unparsed: 14659 case EST_Uninstantiated: 14660 case EST_Unevaluated: 14661 case EST_BasicNoexcept: 14662 case EST_DynamicNone: 14663 case EST_MSAny: 14664 case EST_None: 14665 break; 14666 14667 case EST_ComputedNoexcept: 14668 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14669 return true; 14670 14671 case EST_Dynamic: 14672 for (const auto &E : Proto->exceptions()) { 14673 if (!Finder.TraverseType(E)) 14674 return true; 14675 } 14676 break; 14677 } 14678 14679 return false; 14680 } 14681 14682 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14683 FindCXXThisExpr Finder(*this); 14684 14685 // Check attributes. 14686 for (const auto *A : Method->attrs()) { 14687 // FIXME: This should be emitted by tblgen. 14688 Expr *Arg = nullptr; 14689 ArrayRef<Expr *> Args; 14690 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14691 Arg = G->getArg(); 14692 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14693 Arg = G->getArg(); 14694 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14695 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14696 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14697 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14698 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14699 Arg = ETLF->getSuccessValue(); 14700 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14701 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14702 Arg = STLF->getSuccessValue(); 14703 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14704 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14705 Arg = LR->getArg(); 14706 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14707 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14708 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14709 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14710 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14711 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14712 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14713 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14714 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14715 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14716 14717 if (Arg && !Finder.TraverseStmt(Arg)) 14718 return true; 14719 14720 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14721 if (!Finder.TraverseStmt(Args[I])) 14722 return true; 14723 } 14724 } 14725 14726 return false; 14727 } 14728 14729 void Sema::checkExceptionSpecification( 14730 bool IsTopLevel, ExceptionSpecificationType EST, 14731 ArrayRef<ParsedType> DynamicExceptions, 14732 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 14733 SmallVectorImpl<QualType> &Exceptions, 14734 FunctionProtoType::ExceptionSpecInfo &ESI) { 14735 Exceptions.clear(); 14736 ESI.Type = EST; 14737 if (EST == EST_Dynamic) { 14738 Exceptions.reserve(DynamicExceptions.size()); 14739 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 14740 // FIXME: Preserve type source info. 14741 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 14742 14743 if (IsTopLevel) { 14744 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 14745 collectUnexpandedParameterPacks(ET, Unexpanded); 14746 if (!Unexpanded.empty()) { 14747 DiagnoseUnexpandedParameterPacks( 14748 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 14749 Unexpanded); 14750 continue; 14751 } 14752 } 14753 14754 // Check that the type is valid for an exception spec, and 14755 // drop it if not. 14756 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 14757 Exceptions.push_back(ET); 14758 } 14759 ESI.Exceptions = Exceptions; 14760 return; 14761 } 14762 14763 if (EST == EST_ComputedNoexcept) { 14764 // If an error occurred, there's no expression here. 14765 if (NoexceptExpr) { 14766 assert((NoexceptExpr->isTypeDependent() || 14767 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 14768 Context.BoolTy) && 14769 "Parser should have made sure that the expression is boolean"); 14770 if (IsTopLevel && NoexceptExpr && 14771 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 14772 ESI.Type = EST_BasicNoexcept; 14773 return; 14774 } 14775 14776 if (!NoexceptExpr->isValueDependent()) 14777 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 14778 diag::err_noexcept_needs_constant_expression, 14779 /*AllowFold*/ false).get(); 14780 ESI.NoexceptExpr = NoexceptExpr; 14781 } 14782 return; 14783 } 14784 } 14785 14786 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 14787 ExceptionSpecificationType EST, 14788 SourceRange SpecificationRange, 14789 ArrayRef<ParsedType> DynamicExceptions, 14790 ArrayRef<SourceRange> DynamicExceptionRanges, 14791 Expr *NoexceptExpr) { 14792 if (!MethodD) 14793 return; 14794 14795 // Dig out the method we're referring to. 14796 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 14797 MethodD = FunTmpl->getTemplatedDecl(); 14798 14799 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 14800 if (!Method) 14801 return; 14802 14803 // Check the exception specification. 14804 llvm::SmallVector<QualType, 4> Exceptions; 14805 FunctionProtoType::ExceptionSpecInfo ESI; 14806 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 14807 DynamicExceptionRanges, NoexceptExpr, Exceptions, 14808 ESI); 14809 14810 // Update the exception specification on the function type. 14811 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 14812 14813 if (Method->isStatic()) 14814 checkThisInStaticMemberFunctionExceptionSpec(Method); 14815 14816 if (Method->isVirtual()) { 14817 // Check overrides, which we previously had to delay. 14818 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 14819 OEnd = Method->end_overridden_methods(); 14820 O != OEnd; ++O) 14821 CheckOverridingFunctionExceptionSpec(Method, *O); 14822 } 14823 } 14824 14825 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 14826 /// 14827 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 14828 SourceLocation DeclStart, 14829 Declarator &D, Expr *BitWidth, 14830 InClassInitStyle InitStyle, 14831 AccessSpecifier AS, 14832 AttributeList *MSPropertyAttr) { 14833 IdentifierInfo *II = D.getIdentifier(); 14834 if (!II) { 14835 Diag(DeclStart, diag::err_anonymous_property); 14836 return nullptr; 14837 } 14838 SourceLocation Loc = D.getIdentifierLoc(); 14839 14840 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14841 QualType T = TInfo->getType(); 14842 if (getLangOpts().CPlusPlus) { 14843 CheckExtraCXXDefaultArguments(D); 14844 14845 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14846 UPPC_DataMemberType)) { 14847 D.setInvalidType(); 14848 T = Context.IntTy; 14849 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14850 } 14851 } 14852 14853 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14854 14855 if (D.getDeclSpec().isInlineSpecified()) 14856 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14857 << getLangOpts().CPlusPlus1z; 14858 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14859 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14860 diag::err_invalid_thread) 14861 << DeclSpec::getSpecifierName(TSCS); 14862 14863 // Check to see if this name was declared as a member previously 14864 NamedDecl *PrevDecl = nullptr; 14865 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14866 LookupName(Previous, S); 14867 switch (Previous.getResultKind()) { 14868 case LookupResult::Found: 14869 case LookupResult::FoundUnresolvedValue: 14870 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14871 break; 14872 14873 case LookupResult::FoundOverloaded: 14874 PrevDecl = Previous.getRepresentativeDecl(); 14875 break; 14876 14877 case LookupResult::NotFound: 14878 case LookupResult::NotFoundInCurrentInstantiation: 14879 case LookupResult::Ambiguous: 14880 break; 14881 } 14882 14883 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14884 // Maybe we will complain about the shadowed template parameter. 14885 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14886 // Just pretend that we didn't see the previous declaration. 14887 PrevDecl = nullptr; 14888 } 14889 14890 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14891 PrevDecl = nullptr; 14892 14893 SourceLocation TSSL = D.getLocStart(); 14894 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 14895 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 14896 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 14897 ProcessDeclAttributes(TUScope, NewPD, D); 14898 NewPD->setAccess(AS); 14899 14900 if (NewPD->isInvalidDecl()) 14901 Record->setInvalidDecl(); 14902 14903 if (D.getDeclSpec().isModulePrivateSpecified()) 14904 NewPD->setModulePrivate(); 14905 14906 if (NewPD->isInvalidDecl() && PrevDecl) { 14907 // Don't introduce NewFD into scope; there's already something 14908 // with the same name in the same scope. 14909 } else if (II) { 14910 PushOnScopeChains(NewPD, S); 14911 } else 14912 Record->addDecl(NewPD); 14913 14914 return NewPD; 14915 } 14916