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 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 171 EST = EST_BasicNoexcept; 172 173 switch(EST) { 174 // If this function can throw any exceptions, make a note of that. 175 case EST_MSAny: 176 case EST_None: 177 ClearExceptions(); 178 ComputedEST = EST; 179 return; 180 // FIXME: If the call to this decl is using any of its default arguments, we 181 // need to search them for potentially-throwing calls. 182 // If this function has a basic noexcept, it doesn't affect the outcome. 183 case EST_BasicNoexcept: 184 return; 185 // If we're still at noexcept(true) and there's a nothrow() callee, 186 // change to that specification. 187 case EST_DynamicNone: 188 if (ComputedEST == EST_BasicNoexcept) 189 ComputedEST = EST_DynamicNone; 190 return; 191 // Check out noexcept specs. 192 case EST_ComputedNoexcept: 193 { 194 FunctionProtoType::NoexceptResult NR = 195 Proto->getNoexceptSpec(Self->Context); 196 assert(NR != FunctionProtoType::NR_NoNoexcept && 197 "Must have noexcept result for EST_ComputedNoexcept."); 198 assert(NR != FunctionProtoType::NR_Dependent && 199 "Should not generate implicit declarations for dependent cases, " 200 "and don't know how to handle them anyway."); 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 default: 210 break; 211 } 212 assert(EST == EST_Dynamic && "EST case not considered earlier."); 213 assert(ComputedEST != EST_None && 214 "Shouldn't collect exceptions when throw-all is guaranteed."); 215 ComputedEST = EST_Dynamic; 216 // Record the exceptions in this function's exception specification. 217 for (const auto &E : Proto->exceptions()) 218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 219 Exceptions.push_back(E); 220 } 221 222 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 223 if (!E || ComputedEST == EST_MSAny) 224 return; 225 226 // FIXME: 227 // 228 // C++0x [except.spec]p14: 229 // [An] implicit exception-specification specifies the type-id T if and 230 // only if T is allowed by the exception-specification of a function directly 231 // invoked by f's implicit definition; f shall allow all exceptions if any 232 // function it directly invokes allows all exceptions, and f shall allow no 233 // exceptions if every function it directly invokes allows no exceptions. 234 // 235 // Note in particular that if an implicit exception-specification is generated 236 // for a function containing a throw-expression, that specification can still 237 // be noexcept(true). 238 // 239 // Note also that 'directly invoked' is not defined in the standard, and there 240 // is no indication that we should only consider potentially-evaluated calls. 241 // 242 // Ultimately we should implement the intent of the standard: the exception 243 // specification should be the set of exceptions which can be thrown by the 244 // implicit definition. For now, we assume that any non-nothrow expression can 245 // throw any exception. 246 247 if (Self->canThrow(E)) 248 ComputedEST = EST_None; 249 } 250 251 bool 252 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 253 SourceLocation EqualLoc) { 254 if (RequireCompleteType(Param->getLocation(), Param->getType(), 255 diag::err_typecheck_decl_incomplete_type)) { 256 Param->setInvalidDecl(); 257 return true; 258 } 259 260 // C++ [dcl.fct.default]p5 261 // A default argument expression is implicitly converted (clause 262 // 4) to the parameter type. The default argument expression has 263 // the same semantic constraints as the initializer expression in 264 // a declaration of a variable of the parameter type, using the 265 // copy-initialization semantics (8.5). 266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 267 Param); 268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 269 EqualLoc); 270 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 272 if (Result.isInvalid()) 273 return true; 274 Arg = Result.getAs<Expr>(); 275 276 CheckCompletedExpr(Arg, EqualLoc); 277 Arg = MaybeCreateExprWithCleanups(Arg); 278 279 // Okay: add the default argument to the parameter 280 Param->setDefaultArg(Arg); 281 282 // We have already instantiated this parameter; provide each of the 283 // instantiations with the uninstantiated default argument. 284 UnparsedDefaultArgInstantiationsMap::iterator InstPos 285 = UnparsedDefaultArgInstantiations.find(Param); 286 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 289 290 // We're done tracking this parameter's instantiations. 291 UnparsedDefaultArgInstantiations.erase(InstPos); 292 } 293 294 return false; 295 } 296 297 /// ActOnParamDefaultArgument - Check whether the default argument 298 /// provided for a function parameter is well-formed. If so, attach it 299 /// to the parameter declaration. 300 void 301 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 302 Expr *DefaultArg) { 303 if (!param || !DefaultArg) 304 return; 305 306 ParmVarDecl *Param = cast<ParmVarDecl>(param); 307 UnparsedDefaultArgLocs.erase(Param); 308 309 // Default arguments are only permitted in C++ 310 if (!getLangOpts().CPlusPlus) { 311 Diag(EqualLoc, diag::err_param_default_argument) 312 << DefaultArg->getSourceRange(); 313 Param->setInvalidDecl(); 314 return; 315 } 316 317 // Check for unexpanded parameter packs. 318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 319 Param->setInvalidDecl(); 320 return; 321 } 322 323 // C++11 [dcl.fct.default]p3 324 // A default argument expression [...] shall not be specified for a 325 // parameter pack. 326 if (Param->isParameterPack()) { 327 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 328 << DefaultArg->getSourceRange(); 329 return; 330 } 331 332 // Check that the default argument is well-formed 333 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 334 if (DefaultArgChecker.Visit(DefaultArg)) { 335 Param->setInvalidDecl(); 336 return; 337 } 338 339 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 340 } 341 342 /// ActOnParamUnparsedDefaultArgument - We've seen a default 343 /// argument for a function parameter, but we can't parse it yet 344 /// because we're inside a class definition. Note that this default 345 /// argument will be parsed later. 346 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 347 SourceLocation EqualLoc, 348 SourceLocation ArgLoc) { 349 if (!param) 350 return; 351 352 ParmVarDecl *Param = cast<ParmVarDecl>(param); 353 Param->setUnparsedDefaultArg(); 354 UnparsedDefaultArgLocs[Param] = ArgLoc; 355 } 356 357 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 358 /// the default argument for the parameter param failed. 359 void Sema::ActOnParamDefaultArgumentError(Decl *param, 360 SourceLocation EqualLoc) { 361 if (!param) 362 return; 363 364 ParmVarDecl *Param = cast<ParmVarDecl>(param); 365 Param->setInvalidDecl(); 366 UnparsedDefaultArgLocs.erase(Param); 367 Param->setDefaultArg(new(Context) 368 OpaqueValueExpr(EqualLoc, 369 Param->getType().getNonReferenceType(), 370 VK_RValue)); 371 } 372 373 /// CheckExtraCXXDefaultArguments - Check for any extra default 374 /// arguments in the declarator, which is not a function declaration 375 /// or definition and therefore is not permitted to have default 376 /// arguments. This routine should be invoked for every declarator 377 /// that is not a function declaration or definition. 378 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 379 // C++ [dcl.fct.default]p3 380 // A default argument expression shall be specified only in the 381 // parameter-declaration-clause of a function declaration or in a 382 // template-parameter (14.1). It shall not be specified for a 383 // parameter pack. If it is specified in a 384 // parameter-declaration-clause, it shall not occur within a 385 // declarator or abstract-declarator of a parameter-declaration. 386 bool MightBeFunction = D.isFunctionDeclarationContext(); 387 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 388 DeclaratorChunk &chunk = D.getTypeObject(i); 389 if (chunk.Kind == DeclaratorChunk::Function) { 390 if (MightBeFunction) { 391 // This is a function declaration. It can have default arguments, but 392 // keep looking in case its return type is a function type with default 393 // arguments. 394 MightBeFunction = false; 395 continue; 396 } 397 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 398 ++argIdx) { 399 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 400 if (Param->hasUnparsedDefaultArg()) { 401 std::unique_ptr<CachedTokens> Toks = 402 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 403 SourceRange SR; 404 if (Toks->size() > 1) 405 SR = SourceRange((*Toks)[1].getLocation(), 406 Toks->back().getLocation()); 407 else 408 SR = UnparsedDefaultArgLocs[Param]; 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << SR; 411 } else if (Param->getDefaultArg()) { 412 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 413 << Param->getDefaultArg()->getSourceRange(); 414 Param->setDefaultArg(nullptr); 415 } 416 } 417 } else if (chunk.Kind != DeclaratorChunk::Paren) { 418 MightBeFunction = false; 419 } 420 } 421 } 422 423 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 424 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 425 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 426 if (!PVD->hasDefaultArg()) 427 return false; 428 if (!PVD->hasInheritedDefaultArg()) 429 return true; 430 } 431 return false; 432 } 433 434 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 435 /// function, once we already know that they have the same 436 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 437 /// error, false otherwise. 438 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 439 Scope *S) { 440 bool Invalid = false; 441 442 // The declaration context corresponding to the scope is the semantic 443 // parent, unless this is a local function declaration, in which case 444 // it is that surrounding function. 445 DeclContext *ScopeDC = New->isLocalExternDecl() 446 ? New->getLexicalDeclContext() 447 : New->getDeclContext(); 448 449 // Find the previous declaration for the purpose of default arguments. 450 FunctionDecl *PrevForDefaultArgs = Old; 451 for (/**/; PrevForDefaultArgs; 452 // Don't bother looking back past the latest decl if this is a local 453 // extern declaration; nothing else could work. 454 PrevForDefaultArgs = New->isLocalExternDecl() 455 ? nullptr 456 : PrevForDefaultArgs->getPreviousDecl()) { 457 // Ignore hidden declarations. 458 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 459 continue; 460 461 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 462 !New->isCXXClassMember()) { 463 // Ignore default arguments of old decl if they are not in 464 // the same scope and this is not an out-of-line definition of 465 // a member function. 466 continue; 467 } 468 469 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 470 // If only one of these is a local function declaration, then they are 471 // declared in different scopes, even though isDeclInScope may think 472 // they're in the same scope. (If both are local, the scope check is 473 // sufficient, and if neither is local, then they are in the same scope.) 474 continue; 475 } 476 477 // We found the right previous declaration. 478 break; 479 } 480 481 // C++ [dcl.fct.default]p4: 482 // For non-template functions, default arguments can be added in 483 // later declarations of a function in the same 484 // scope. Declarations in different scopes have completely 485 // distinct sets of default arguments. That is, declarations in 486 // inner scopes do not acquire default arguments from 487 // declarations in outer scopes, and vice versa. In a given 488 // function declaration, all parameters subsequent to a 489 // parameter with a default argument shall have default 490 // arguments supplied in this or previous declarations. A 491 // default argument shall not be redefined by a later 492 // declaration (not even to the same value). 493 // 494 // C++ [dcl.fct.default]p6: 495 // Except for member functions of class templates, the default arguments 496 // in a member function definition that appears outside of the class 497 // definition are added to the set of default arguments provided by the 498 // member function declaration in the class definition. 499 for (unsigned p = 0, NumParams = PrevForDefaultArgs 500 ? PrevForDefaultArgs->getNumParams() 501 : 0; 502 p < NumParams; ++p) { 503 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 504 ParmVarDecl *NewParam = New->getParamDecl(p); 505 506 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 507 bool NewParamHasDfl = NewParam->hasDefaultArg(); 508 509 if (OldParamHasDfl && NewParamHasDfl) { 510 unsigned DiagDefaultParamID = 511 diag::err_param_default_argument_redefinition; 512 513 // MSVC accepts that default parameters be redefined for member functions 514 // of template class. The new default parameter's value is ignored. 515 Invalid = true; 516 if (getLangOpts().MicrosoftExt) { 517 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 518 if (MD && MD->getParent()->getDescribedClassTemplate()) { 519 // Merge the old default argument into the new parameter. 520 NewParam->setHasInheritedDefaultArg(); 521 if (OldParam->hasUninstantiatedDefaultArg()) 522 NewParam->setUninstantiatedDefaultArg( 523 OldParam->getUninstantiatedDefaultArg()); 524 else 525 NewParam->setDefaultArg(OldParam->getInit()); 526 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 527 Invalid = false; 528 } 529 } 530 531 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 532 // hint here. Alternatively, we could walk the type-source information 533 // for NewParam to find the last source location in the type... but it 534 // isn't worth the effort right now. This is the kind of test case that 535 // is hard to get right: 536 // int f(int); 537 // void g(int (*fp)(int) = f); 538 // void g(int (*fp)(int) = &f); 539 Diag(NewParam->getLocation(), DiagDefaultParamID) 540 << NewParam->getDefaultArgRange(); 541 542 // Look for the function declaration where the default argument was 543 // actually written, which may be a declaration prior to Old. 544 for (auto Older = PrevForDefaultArgs; 545 OldParam->hasInheritedDefaultArg(); /**/) { 546 Older = Older->getPreviousDecl(); 547 OldParam = Older->getParamDecl(p); 548 } 549 550 Diag(OldParam->getLocation(), diag::note_previous_definition) 551 << OldParam->getDefaultArgRange(); 552 } else if (OldParamHasDfl) { 553 // Merge the old default argument into the new parameter unless the new 554 // function is a friend declaration in a template class. In the latter 555 // case the default arguments will be inherited when the friend 556 // declaration will be instantiated. 557 if (New->getFriendObjectKind() == Decl::FOK_None || 558 !New->getLexicalDeclContext()->isDependentContext()) { 559 // It's important to use getInit() here; getDefaultArg() 560 // strips off any top-level ExprWithCleanups. 561 NewParam->setHasInheritedDefaultArg(); 562 if (OldParam->hasUnparsedDefaultArg()) 563 NewParam->setUnparsedDefaultArg(); 564 else if (OldParam->hasUninstantiatedDefaultArg()) 565 NewParam->setUninstantiatedDefaultArg( 566 OldParam->getUninstantiatedDefaultArg()); 567 else 568 NewParam->setDefaultArg(OldParam->getInit()); 569 } 570 } else if (NewParamHasDfl) { 571 if (New->getDescribedFunctionTemplate()) { 572 // Paragraph 4, quoted above, only applies to non-template functions. 573 Diag(NewParam->getLocation(), 574 diag::err_param_default_argument_template_redecl) 575 << NewParam->getDefaultArgRange(); 576 Diag(PrevForDefaultArgs->getLocation(), 577 diag::note_template_prev_declaration) 578 << false; 579 } else if (New->getTemplateSpecializationKind() 580 != TSK_ImplicitInstantiation && 581 New->getTemplateSpecializationKind() != TSK_Undeclared) { 582 // C++ [temp.expr.spec]p21: 583 // Default function arguments shall not be specified in a declaration 584 // or a definition for one of the following explicit specializations: 585 // - the explicit specialization of a function template; 586 // - the explicit specialization of a member function template; 587 // - the explicit specialization of a member function of a class 588 // template where the class template specialization to which the 589 // member function specialization belongs is implicitly 590 // instantiated. 591 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 592 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 593 << New->getDeclName() 594 << NewParam->getDefaultArgRange(); 595 } else if (New->getDeclContext()->isDependentContext()) { 596 // C++ [dcl.fct.default]p6 (DR217): 597 // Default arguments for a member function of a class template shall 598 // be specified on the initial declaration of the member function 599 // within the class template. 600 // 601 // Reading the tea leaves a bit in DR217 and its reference to DR205 602 // leads me to the conclusion that one cannot add default function 603 // arguments for an out-of-line definition of a member function of a 604 // dependent type. 605 int WhichKind = 2; 606 if (CXXRecordDecl *Record 607 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 608 if (Record->getDescribedClassTemplate()) 609 WhichKind = 0; 610 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 611 WhichKind = 1; 612 else 613 WhichKind = 2; 614 } 615 616 Diag(NewParam->getLocation(), 617 diag::err_param_default_argument_member_template_redecl) 618 << WhichKind 619 << NewParam->getDefaultArgRange(); 620 } 621 } 622 } 623 624 // DR1344: If a default argument is added outside a class definition and that 625 // default argument makes the function a special member function, the program 626 // is ill-formed. This can only happen for constructors. 627 if (isa<CXXConstructorDecl>(New) && 628 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 629 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 630 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 631 if (NewSM != OldSM) { 632 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 633 assert(NewParam->hasDefaultArg()); 634 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 635 << NewParam->getDefaultArgRange() << NewSM; 636 Diag(Old->getLocation(), diag::note_previous_declaration); 637 } 638 } 639 640 const FunctionDecl *Def; 641 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 642 // template has a constexpr specifier then all its declarations shall 643 // contain the constexpr specifier. 644 if (New->isConstexpr() != Old->isConstexpr()) { 645 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 646 << New << New->isConstexpr(); 647 Diag(Old->getLocation(), diag::note_previous_declaration); 648 Invalid = true; 649 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 650 Old->isDefined(Def) && 651 // If a friend function is inlined but does not have 'inline' 652 // specifier, it is a definition. Do not report attribute conflict 653 // in this case, redefinition will be diagnosed later. 654 (New->isInlineSpecified() || 655 New->getFriendObjectKind() == Decl::FOK_None)) { 656 // C++11 [dcl.fcn.spec]p4: 657 // If the definition of a function appears in a translation unit before its 658 // first declaration as inline, the program is ill-formed. 659 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 660 Diag(Def->getLocation(), diag::note_previous_definition); 661 Invalid = true; 662 } 663 664 // FIXME: It's not clear what should happen if multiple declarations of a 665 // deduction guide have different explicitness. For now at least we simply 666 // reject any case where the explicitness changes. 667 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 668 if (NewGuide && NewGuide->isExplicitSpecified() != 669 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 670 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 671 << NewGuide->isExplicitSpecified(); 672 Diag(Old->getLocation(), diag::note_previous_declaration); 673 } 674 675 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 676 // argument expression, that declaration shall be a definition and shall be 677 // the only declaration of the function or function template in the 678 // translation unit. 679 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 680 functionDeclHasDefaultArgument(Old)) { 681 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 682 Diag(Old->getLocation(), diag::note_previous_declaration); 683 Invalid = true; 684 } 685 686 return Invalid; 687 } 688 689 NamedDecl * 690 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 691 MultiTemplateParamsArg TemplateParamLists) { 692 assert(D.isDecompositionDeclarator()); 693 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 694 695 // The syntax only allows a decomposition declarator as a simple-declaration, 696 // a for-range-declaration, or a condition in Clang, but we parse it in more 697 // cases than that. 698 if (!D.mayHaveDecompositionDeclarator()) { 699 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 700 << Decomp.getSourceRange(); 701 return nullptr; 702 } 703 704 if (!TemplateParamLists.empty()) { 705 // FIXME: There's no rule against this, but there are also no rules that 706 // would actually make it usable, so we reject it for now. 707 Diag(TemplateParamLists.front()->getTemplateLoc(), 708 diag::err_decomp_decl_template); 709 return nullptr; 710 } 711 712 Diag(Decomp.getLSquareLoc(), 713 !getLangOpts().CPlusPlus17 714 ? diag::ext_decomp_decl 715 : D.getContext() == DeclaratorContext::ConditionContext 716 ? diag::ext_decomp_decl_cond 717 : diag::warn_cxx14_compat_decomp_decl) 718 << Decomp.getSourceRange(); 719 720 // The semantic context is always just the current context. 721 DeclContext *const DC = CurContext; 722 723 // C++1z [dcl.dcl]/8: 724 // The decl-specifier-seq shall contain only the type-specifier auto 725 // and cv-qualifiers. 726 auto &DS = D.getDeclSpec(); 727 { 728 SmallVector<StringRef, 8> BadSpecifiers; 729 SmallVector<SourceLocation, 8> BadSpecifierLocs; 730 if (auto SCS = DS.getStorageClassSpec()) { 731 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 732 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 733 } 734 if (auto TSCS = DS.getThreadStorageClassSpec()) { 735 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 736 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 737 } 738 if (DS.isConstexprSpecified()) { 739 BadSpecifiers.push_back("constexpr"); 740 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 741 } 742 if (DS.isInlineSpecified()) { 743 BadSpecifiers.push_back("inline"); 744 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 745 } 746 if (!BadSpecifiers.empty()) { 747 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 748 Err << (int)BadSpecifiers.size() 749 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 750 // Don't add FixItHints to remove the specifiers; we do still respect 751 // them when building the underlying variable. 752 for (auto Loc : BadSpecifierLocs) 753 Err << SourceRange(Loc, Loc); 754 } 755 // We can't recover from it being declared as a typedef. 756 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 757 return nullptr; 758 } 759 760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 761 QualType R = TInfo->getType(); 762 763 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 764 UPPC_DeclarationType)) 765 D.setInvalidType(); 766 767 // The syntax only allows a single ref-qualifier prior to the decomposition 768 // declarator. No other declarator chunks are permitted. Also check the type 769 // specifier here. 770 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 771 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 772 (D.getNumTypeObjects() == 1 && 773 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 774 Diag(Decomp.getLSquareLoc(), 775 (D.hasGroupingParens() || 776 (D.getNumTypeObjects() && 777 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 778 ? diag::err_decomp_decl_parens 779 : diag::err_decomp_decl_type) 780 << R; 781 782 // In most cases, there's no actual problem with an explicitly-specified 783 // type, but a function type won't work here, and ActOnVariableDeclarator 784 // shouldn't be called for such a type. 785 if (R->isFunctionType()) 786 D.setInvalidType(); 787 } 788 789 // Build the BindingDecls. 790 SmallVector<BindingDecl*, 8> Bindings; 791 792 // Build the BindingDecls. 793 for (auto &B : D.getDecompositionDeclarator().bindings()) { 794 // Check for name conflicts. 795 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 796 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 797 ForVisibleRedeclaration); 798 LookupName(Previous, S, 799 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 800 801 // It's not permitted to shadow a template parameter name. 802 if (Previous.isSingleResult() && 803 Previous.getFoundDecl()->isTemplateParameter()) { 804 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 805 Previous.getFoundDecl()); 806 Previous.clear(); 807 } 808 809 bool ConsiderLinkage = DC->isFunctionOrMethod() && 810 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 811 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 812 /*AllowInlineNamespace*/false); 813 if (!Previous.empty()) { 814 auto *Old = Previous.getRepresentativeDecl(); 815 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 816 Diag(Old->getLocation(), diag::note_previous_definition); 817 } 818 819 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 820 PushOnScopeChains(BD, S, true); 821 Bindings.push_back(BD); 822 ParsingInitForAutoVars.insert(BD); 823 } 824 825 // There are no prior lookup results for the variable itself, because it 826 // is unnamed. 827 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 828 Decomp.getLSquareLoc()); 829 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 830 ForVisibleRedeclaration); 831 832 // Build the variable that holds the non-decomposed object. 833 bool AddToScope = true; 834 NamedDecl *New = 835 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 836 MultiTemplateParamsArg(), AddToScope, Bindings); 837 if (AddToScope) { 838 S->AddDecl(New); 839 CurContext->addHiddenDecl(New); 840 } 841 842 if (isInOpenMPDeclareTargetContext()) 843 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 844 845 return New; 846 } 847 848 static bool checkSimpleDecomposition( 849 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 850 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 851 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 852 if ((int64_t)Bindings.size() != NumElems) { 853 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 854 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 855 << (NumElems < Bindings.size()); 856 return true; 857 } 858 859 unsigned I = 0; 860 for (auto *B : Bindings) { 861 SourceLocation Loc = B->getLocation(); 862 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 863 if (E.isInvalid()) 864 return true; 865 E = GetInit(Loc, E.get(), I++); 866 if (E.isInvalid()) 867 return true; 868 B->setBinding(ElemType, E.get()); 869 } 870 871 return false; 872 } 873 874 static bool checkArrayLikeDecomposition(Sema &S, 875 ArrayRef<BindingDecl *> Bindings, 876 ValueDecl *Src, QualType DecompType, 877 const llvm::APSInt &NumElems, 878 QualType ElemType) { 879 return checkSimpleDecomposition( 880 S, Bindings, Src, DecompType, NumElems, ElemType, 881 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 882 ExprResult E = S.ActOnIntegerConstant(Loc, I); 883 if (E.isInvalid()) 884 return ExprError(); 885 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 886 }); 887 } 888 889 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 890 ValueDecl *Src, QualType DecompType, 891 const ConstantArrayType *CAT) { 892 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 893 llvm::APSInt(CAT->getSize()), 894 CAT->getElementType()); 895 } 896 897 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 898 ValueDecl *Src, QualType DecompType, 899 const VectorType *VT) { 900 return checkArrayLikeDecomposition( 901 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 902 S.Context.getQualifiedType(VT->getElementType(), 903 DecompType.getQualifiers())); 904 } 905 906 static bool checkComplexDecomposition(Sema &S, 907 ArrayRef<BindingDecl *> Bindings, 908 ValueDecl *Src, QualType DecompType, 909 const ComplexType *CT) { 910 return checkSimpleDecomposition( 911 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 912 S.Context.getQualifiedType(CT->getElementType(), 913 DecompType.getQualifiers()), 914 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 915 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 916 }); 917 } 918 919 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 920 TemplateArgumentListInfo &Args) { 921 SmallString<128> SS; 922 llvm::raw_svector_ostream OS(SS); 923 bool First = true; 924 for (auto &Arg : Args.arguments()) { 925 if (!First) 926 OS << ", "; 927 Arg.getArgument().print(PrintingPolicy, OS); 928 First = false; 929 } 930 return OS.str(); 931 } 932 933 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 934 SourceLocation Loc, StringRef Trait, 935 TemplateArgumentListInfo &Args, 936 unsigned DiagID) { 937 auto DiagnoseMissing = [&] { 938 if (DiagID) 939 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 940 Args); 941 return true; 942 }; 943 944 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 945 NamespaceDecl *Std = S.getStdNamespace(); 946 if (!Std) 947 return DiagnoseMissing(); 948 949 // Look up the trait itself, within namespace std. We can diagnose various 950 // problems with this lookup even if we've been asked to not diagnose a 951 // missing specialization, because this can only fail if the user has been 952 // declaring their own names in namespace std or we don't support the 953 // standard library implementation in use. 954 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 955 Loc, Sema::LookupOrdinaryName); 956 if (!S.LookupQualifiedName(Result, Std)) 957 return DiagnoseMissing(); 958 if (Result.isAmbiguous()) 959 return true; 960 961 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 962 if (!TraitTD) { 963 Result.suppressDiagnostics(); 964 NamedDecl *Found = *Result.begin(); 965 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 966 S.Diag(Found->getLocation(), diag::note_declared_at); 967 return true; 968 } 969 970 // Build the template-id. 971 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 972 if (TraitTy.isNull()) 973 return true; 974 if (!S.isCompleteType(Loc, TraitTy)) { 975 if (DiagID) 976 S.RequireCompleteType( 977 Loc, TraitTy, DiagID, 978 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 979 return true; 980 } 981 982 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 983 assert(RD && "specialization of class template is not a class?"); 984 985 // Look up the member of the trait type. 986 S.LookupQualifiedName(TraitMemberLookup, RD); 987 return TraitMemberLookup.isAmbiguous(); 988 } 989 990 static TemplateArgumentLoc 991 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 992 uint64_t I) { 993 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 994 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 995 } 996 997 static TemplateArgumentLoc 998 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 999 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1000 } 1001 1002 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1003 1004 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1005 llvm::APSInt &Size) { 1006 EnterExpressionEvaluationContext ContextRAII( 1007 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1008 1009 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1010 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1011 1012 // Form template argument list for tuple_size<T>. 1013 TemplateArgumentListInfo Args(Loc, Loc); 1014 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1015 1016 // If there's no tuple_size specialization, it's not tuple-like. 1017 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1018 return IsTupleLike::NotTupleLike; 1019 1020 // If we get this far, we've committed to the tuple interpretation, but 1021 // we can still fail if there actually isn't a usable ::value. 1022 1023 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1024 LookupResult &R; 1025 TemplateArgumentListInfo &Args; 1026 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1027 : R(R), Args(Args) {} 1028 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1029 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1030 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1031 } 1032 } Diagnoser(R, Args); 1033 1034 if (R.empty()) { 1035 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1036 return IsTupleLike::Error; 1037 } 1038 1039 ExprResult E = 1040 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1041 if (E.isInvalid()) 1042 return IsTupleLike::Error; 1043 1044 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1045 if (E.isInvalid()) 1046 return IsTupleLike::Error; 1047 1048 return IsTupleLike::TupleLike; 1049 } 1050 1051 /// \return std::tuple_element<I, T>::type. 1052 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1053 unsigned I, QualType T) { 1054 // Form template argument list for tuple_element<I, T>. 1055 TemplateArgumentListInfo Args(Loc, Loc); 1056 Args.addArgument( 1057 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1058 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1059 1060 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1061 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1062 if (lookupStdTypeTraitMember( 1063 S, R, Loc, "tuple_element", Args, 1064 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1065 return QualType(); 1066 1067 auto *TD = R.getAsSingle<TypeDecl>(); 1068 if (!TD) { 1069 R.suppressDiagnostics(); 1070 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1071 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1072 if (!R.empty()) 1073 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1074 return QualType(); 1075 } 1076 1077 return S.Context.getTypeDeclType(TD); 1078 } 1079 1080 namespace { 1081 struct BindingDiagnosticTrap { 1082 Sema &S; 1083 DiagnosticErrorTrap Trap; 1084 BindingDecl *BD; 1085 1086 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1087 : S(S), Trap(S.Diags), BD(BD) {} 1088 ~BindingDiagnosticTrap() { 1089 if (Trap.hasErrorOccurred()) 1090 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1091 } 1092 }; 1093 } 1094 1095 static bool checkTupleLikeDecomposition(Sema &S, 1096 ArrayRef<BindingDecl *> Bindings, 1097 VarDecl *Src, QualType DecompType, 1098 const llvm::APSInt &TupleSize) { 1099 if ((int64_t)Bindings.size() != TupleSize) { 1100 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1101 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1102 << (TupleSize < Bindings.size()); 1103 return true; 1104 } 1105 1106 if (Bindings.empty()) 1107 return false; 1108 1109 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1110 1111 // [dcl.decomp]p3: 1112 // The unqualified-id get is looked up in the scope of E by class member 1113 // access lookup 1114 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1115 bool UseMemberGet = false; 1116 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1117 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1118 S.LookupQualifiedName(MemberGet, RD); 1119 if (MemberGet.isAmbiguous()) 1120 return true; 1121 UseMemberGet = !MemberGet.empty(); 1122 S.FilterAcceptableTemplateNames(MemberGet); 1123 } 1124 1125 unsigned I = 0; 1126 for (auto *B : Bindings) { 1127 BindingDiagnosticTrap Trap(S, B); 1128 SourceLocation Loc = B->getLocation(); 1129 1130 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1131 if (E.isInvalid()) 1132 return true; 1133 1134 // e is an lvalue if the type of the entity is an lvalue reference and 1135 // an xvalue otherwise 1136 if (!Src->getType()->isLValueReferenceType()) 1137 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1138 E.get(), nullptr, VK_XValue); 1139 1140 TemplateArgumentListInfo Args(Loc, Loc); 1141 Args.addArgument( 1142 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1143 1144 if (UseMemberGet) { 1145 // if [lookup of member get] finds at least one declaration, the 1146 // initializer is e.get<i-1>(). 1147 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1148 CXXScopeSpec(), SourceLocation(), nullptr, 1149 MemberGet, &Args, nullptr); 1150 if (E.isInvalid()) 1151 return true; 1152 1153 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1154 } else { 1155 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1156 // in the associated namespaces. 1157 Expr *Get = UnresolvedLookupExpr::Create( 1158 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1159 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1160 UnresolvedSetIterator(), UnresolvedSetIterator()); 1161 1162 Expr *Arg = E.get(); 1163 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1164 } 1165 if (E.isInvalid()) 1166 return true; 1167 Expr *Init = E.get(); 1168 1169 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1170 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1171 if (T.isNull()) 1172 return true; 1173 1174 // each vi is a variable of type "reference to T" initialized with the 1175 // initializer, where the reference is an lvalue reference if the 1176 // initializer is an lvalue and an rvalue reference otherwise 1177 QualType RefType = 1178 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1179 if (RefType.isNull()) 1180 return true; 1181 auto *RefVD = VarDecl::Create( 1182 S.Context, Src->getDeclContext(), Loc, Loc, 1183 B->getDeclName().getAsIdentifierInfo(), RefType, 1184 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1185 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1186 RefVD->setTSCSpec(Src->getTSCSpec()); 1187 RefVD->setImplicit(); 1188 if (Src->isInlineSpecified()) 1189 RefVD->setInlineSpecified(); 1190 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1191 1192 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1193 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1194 InitializationSequence Seq(S, Entity, Kind, Init); 1195 E = Seq.Perform(S, Entity, Kind, Init); 1196 if (E.isInvalid()) 1197 return true; 1198 E = S.ActOnFinishFullExpr(E.get(), Loc); 1199 if (E.isInvalid()) 1200 return true; 1201 RefVD->setInit(E.get()); 1202 RefVD->checkInitIsICE(); 1203 1204 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1205 DeclarationNameInfo(B->getDeclName(), Loc), 1206 RefVD); 1207 if (E.isInvalid()) 1208 return true; 1209 1210 B->setBinding(T, E.get()); 1211 I++; 1212 } 1213 1214 return false; 1215 } 1216 1217 /// Find the base class to decompose in a built-in decomposition of a class type. 1218 /// This base class search is, unfortunately, not quite like any other that we 1219 /// perform anywhere else in C++. 1220 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1221 SourceLocation Loc, 1222 const CXXRecordDecl *RD, 1223 CXXCastPath &BasePath) { 1224 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1225 CXXBasePath &Path) { 1226 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1227 }; 1228 1229 const CXXRecordDecl *ClassWithFields = nullptr; 1230 if (RD->hasDirectFields()) 1231 // [dcl.decomp]p4: 1232 // Otherwise, all of E's non-static data members shall be public direct 1233 // members of E ... 1234 ClassWithFields = RD; 1235 else { 1236 // ... or of ... 1237 CXXBasePaths Paths; 1238 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1239 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1240 // If no classes have fields, just decompose RD itself. (This will work 1241 // if and only if zero bindings were provided.) 1242 return RD; 1243 } 1244 1245 CXXBasePath *BestPath = nullptr; 1246 for (auto &P : Paths) { 1247 if (!BestPath) 1248 BestPath = &P; 1249 else if (!S.Context.hasSameType(P.back().Base->getType(), 1250 BestPath->back().Base->getType())) { 1251 // ... the same ... 1252 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1253 << false << RD << BestPath->back().Base->getType() 1254 << P.back().Base->getType(); 1255 return nullptr; 1256 } else if (P.Access < BestPath->Access) { 1257 BestPath = &P; 1258 } 1259 } 1260 1261 // ... unambiguous ... 1262 QualType BaseType = BestPath->back().Base->getType(); 1263 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1264 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1265 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1266 return nullptr; 1267 } 1268 1269 // ... public base class of E. 1270 if (BestPath->Access != AS_public) { 1271 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1272 << RD << BaseType; 1273 for (auto &BS : *BestPath) { 1274 if (BS.Base->getAccessSpecifier() != AS_public) { 1275 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1276 << (BS.Base->getAccessSpecifier() == AS_protected) 1277 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1278 break; 1279 } 1280 } 1281 return nullptr; 1282 } 1283 1284 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1285 S.BuildBasePathArray(Paths, BasePath); 1286 } 1287 1288 // The above search did not check whether the selected class itself has base 1289 // classes with fields, so check that now. 1290 CXXBasePaths Paths; 1291 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1292 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1293 << (ClassWithFields == RD) << RD << ClassWithFields 1294 << Paths.front().back().Base->getType(); 1295 return nullptr; 1296 } 1297 1298 return ClassWithFields; 1299 } 1300 1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1302 ValueDecl *Src, QualType DecompType, 1303 const CXXRecordDecl *RD) { 1304 CXXCastPath BasePath; 1305 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1306 if (!RD) 1307 return true; 1308 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1309 DecompType.getQualifiers()); 1310 1311 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1312 unsigned NumFields = 1313 std::count_if(RD->field_begin(), RD->field_end(), 1314 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1315 assert(Bindings.size() != NumFields); 1316 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1317 << DecompType << (unsigned)Bindings.size() << NumFields 1318 << (NumFields < Bindings.size()); 1319 return true; 1320 }; 1321 1322 // all of E's non-static data members shall be public [...] members, 1323 // E shall not have an anonymous union member, ... 1324 unsigned I = 0; 1325 for (auto *FD : RD->fields()) { 1326 if (FD->isUnnamedBitfield()) 1327 continue; 1328 1329 if (FD->isAnonymousStructOrUnion()) { 1330 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1331 << DecompType << FD->getType()->isUnionType(); 1332 S.Diag(FD->getLocation(), diag::note_declared_at); 1333 return true; 1334 } 1335 1336 // We have a real field to bind. 1337 if (I >= Bindings.size()) 1338 return DiagnoseBadNumberOfBindings(); 1339 auto *B = Bindings[I++]; 1340 1341 SourceLocation Loc = B->getLocation(); 1342 if (FD->getAccess() != AS_public) { 1343 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1344 1345 // Determine whether the access specifier was explicit. 1346 bool Implicit = true; 1347 for (const auto *D : RD->decls()) { 1348 if (declaresSameEntity(D, FD)) 1349 break; 1350 if (isa<AccessSpecDecl>(D)) { 1351 Implicit = false; 1352 break; 1353 } 1354 } 1355 1356 S.Diag(FD->getLocation(), diag::note_access_natural) 1357 << (FD->getAccess() == AS_protected) << Implicit; 1358 return true; 1359 } 1360 1361 // Initialize the binding to Src.FD. 1362 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1363 if (E.isInvalid()) 1364 return true; 1365 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1366 VK_LValue, &BasePath); 1367 if (E.isInvalid()) 1368 return true; 1369 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1370 CXXScopeSpec(), FD, 1371 DeclAccessPair::make(FD, FD->getAccess()), 1372 DeclarationNameInfo(FD->getDeclName(), Loc)); 1373 if (E.isInvalid()) 1374 return true; 1375 1376 // If the type of the member is T, the referenced type is cv T, where cv is 1377 // the cv-qualification of the decomposition expression. 1378 // 1379 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1380 // 'const' to the type of the field. 1381 Qualifiers Q = DecompType.getQualifiers(); 1382 if (FD->isMutable()) 1383 Q.removeConst(); 1384 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1385 } 1386 1387 if (I != Bindings.size()) 1388 return DiagnoseBadNumberOfBindings(); 1389 1390 return false; 1391 } 1392 1393 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1394 QualType DecompType = DD->getType(); 1395 1396 // If the type of the decomposition is dependent, then so is the type of 1397 // each binding. 1398 if (DecompType->isDependentType()) { 1399 for (auto *B : DD->bindings()) 1400 B->setType(Context.DependentTy); 1401 return; 1402 } 1403 1404 DecompType = DecompType.getNonReferenceType(); 1405 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1406 1407 // C++1z [dcl.decomp]/2: 1408 // If E is an array type [...] 1409 // As an extension, we also support decomposition of built-in complex and 1410 // vector types. 1411 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1412 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1413 DD->setInvalidDecl(); 1414 return; 1415 } 1416 if (auto *VT = DecompType->getAs<VectorType>()) { 1417 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1418 DD->setInvalidDecl(); 1419 return; 1420 } 1421 if (auto *CT = DecompType->getAs<ComplexType>()) { 1422 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1423 DD->setInvalidDecl(); 1424 return; 1425 } 1426 1427 // C++1z [dcl.decomp]/3: 1428 // if the expression std::tuple_size<E>::value is a well-formed integral 1429 // constant expression, [...] 1430 llvm::APSInt TupleSize(32); 1431 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1432 case IsTupleLike::Error: 1433 DD->setInvalidDecl(); 1434 return; 1435 1436 case IsTupleLike::TupleLike: 1437 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1438 DD->setInvalidDecl(); 1439 return; 1440 1441 case IsTupleLike::NotTupleLike: 1442 break; 1443 } 1444 1445 // C++1z [dcl.dcl]/8: 1446 // [E shall be of array or non-union class type] 1447 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1448 if (!RD || RD->isUnion()) { 1449 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1450 << DD << !RD << DecompType; 1451 DD->setInvalidDecl(); 1452 return; 1453 } 1454 1455 // C++1z [dcl.decomp]/4: 1456 // all of E's non-static data members shall be [...] direct members of 1457 // E or of the same unambiguous public base class of E, ... 1458 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1459 DD->setInvalidDecl(); 1460 } 1461 1462 /// \brief Merge the exception specifications of two variable declarations. 1463 /// 1464 /// This is called when there's a redeclaration of a VarDecl. The function 1465 /// checks if the redeclaration might have an exception specification and 1466 /// validates compatibility and merges the specs if necessary. 1467 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1468 // Shortcut if exceptions are disabled. 1469 if (!getLangOpts().CXXExceptions) 1470 return; 1471 1472 assert(Context.hasSameType(New->getType(), Old->getType()) && 1473 "Should only be called if types are otherwise the same."); 1474 1475 QualType NewType = New->getType(); 1476 QualType OldType = Old->getType(); 1477 1478 // We're only interested in pointers and references to functions, as well 1479 // as pointers to member functions. 1480 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1481 NewType = R->getPointeeType(); 1482 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1483 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1484 NewType = P->getPointeeType(); 1485 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1486 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1487 NewType = M->getPointeeType(); 1488 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1489 } 1490 1491 if (!NewType->isFunctionProtoType()) 1492 return; 1493 1494 // There's lots of special cases for functions. For function pointers, system 1495 // libraries are hopefully not as broken so that we don't need these 1496 // workarounds. 1497 if (CheckEquivalentExceptionSpec( 1498 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1499 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1500 New->setInvalidDecl(); 1501 } 1502 } 1503 1504 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1505 /// function declaration are well-formed according to C++ 1506 /// [dcl.fct.default]. 1507 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1508 unsigned NumParams = FD->getNumParams(); 1509 unsigned p; 1510 1511 // Find first parameter with a default argument 1512 for (p = 0; p < NumParams; ++p) { 1513 ParmVarDecl *Param = FD->getParamDecl(p); 1514 if (Param->hasDefaultArg()) 1515 break; 1516 } 1517 1518 // C++11 [dcl.fct.default]p4: 1519 // In a given function declaration, each parameter subsequent to a parameter 1520 // with a default argument shall have a default argument supplied in this or 1521 // a previous declaration or shall be a function parameter pack. A default 1522 // argument shall not be redefined by a later declaration (not even to the 1523 // same value). 1524 unsigned LastMissingDefaultArg = 0; 1525 for (; p < NumParams; ++p) { 1526 ParmVarDecl *Param = FD->getParamDecl(p); 1527 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1528 if (Param->isInvalidDecl()) 1529 /* We already complained about this parameter. */; 1530 else if (Param->getIdentifier()) 1531 Diag(Param->getLocation(), 1532 diag::err_param_default_argument_missing_name) 1533 << Param->getIdentifier(); 1534 else 1535 Diag(Param->getLocation(), 1536 diag::err_param_default_argument_missing); 1537 1538 LastMissingDefaultArg = p; 1539 } 1540 } 1541 1542 if (LastMissingDefaultArg > 0) { 1543 // Some default arguments were missing. Clear out all of the 1544 // default arguments up to (and including) the last missing 1545 // default argument, so that we leave the function parameters 1546 // in a semantically valid state. 1547 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1548 ParmVarDecl *Param = FD->getParamDecl(p); 1549 if (Param->hasDefaultArg()) { 1550 Param->setDefaultArg(nullptr); 1551 } 1552 } 1553 } 1554 } 1555 1556 // CheckConstexprParameterTypes - Check whether a function's parameter types 1557 // are all literal types. If so, return true. If not, produce a suitable 1558 // diagnostic and return false. 1559 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1560 const FunctionDecl *FD) { 1561 unsigned ArgIndex = 0; 1562 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1563 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1564 e = FT->param_type_end(); 1565 i != e; ++i, ++ArgIndex) { 1566 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1567 SourceLocation ParamLoc = PD->getLocation(); 1568 if (!(*i)->isDependentType() && 1569 SemaRef.RequireLiteralType(ParamLoc, *i, 1570 diag::err_constexpr_non_literal_param, 1571 ArgIndex+1, PD->getSourceRange(), 1572 isa<CXXConstructorDecl>(FD))) 1573 return false; 1574 } 1575 return true; 1576 } 1577 1578 /// \brief Get diagnostic %select index for tag kind for 1579 /// record diagnostic message. 1580 /// WARNING: Indexes apply to particular diagnostics only! 1581 /// 1582 /// \returns diagnostic %select index. 1583 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1584 switch (Tag) { 1585 case TTK_Struct: return 0; 1586 case TTK_Interface: return 1; 1587 case TTK_Class: return 2; 1588 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1589 } 1590 } 1591 1592 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1593 // the requirements of a constexpr function definition or a constexpr 1594 // constructor definition. If so, return true. If not, produce appropriate 1595 // diagnostics and return false. 1596 // 1597 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1598 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1599 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1600 if (MD && MD->isInstance()) { 1601 // C++11 [dcl.constexpr]p4: 1602 // The definition of a constexpr constructor shall satisfy the following 1603 // constraints: 1604 // - the class shall not have any virtual base classes; 1605 const CXXRecordDecl *RD = MD->getParent(); 1606 if (RD->getNumVBases()) { 1607 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1608 << isa<CXXConstructorDecl>(NewFD) 1609 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1610 for (const auto &I : RD->vbases()) 1611 Diag(I.getLocStart(), 1612 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1613 return false; 1614 } 1615 } 1616 1617 if (!isa<CXXConstructorDecl>(NewFD)) { 1618 // C++11 [dcl.constexpr]p3: 1619 // The definition of a constexpr function shall satisfy the following 1620 // constraints: 1621 // - it shall not be virtual; 1622 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1623 if (Method && Method->isVirtual()) { 1624 Method = Method->getCanonicalDecl(); 1625 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1626 1627 // If it's not obvious why this function is virtual, find an overridden 1628 // function which uses the 'virtual' keyword. 1629 const CXXMethodDecl *WrittenVirtual = Method; 1630 while (!WrittenVirtual->isVirtualAsWritten()) 1631 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1632 if (WrittenVirtual != Method) 1633 Diag(WrittenVirtual->getLocation(), 1634 diag::note_overridden_virtual_function); 1635 return false; 1636 } 1637 1638 // - its return type shall be a literal type; 1639 QualType RT = NewFD->getReturnType(); 1640 if (!RT->isDependentType() && 1641 RequireLiteralType(NewFD->getLocation(), RT, 1642 diag::err_constexpr_non_literal_return)) 1643 return false; 1644 } 1645 1646 // - each of its parameter types shall be a literal type; 1647 if (!CheckConstexprParameterTypes(*this, NewFD)) 1648 return false; 1649 1650 return true; 1651 } 1652 1653 /// Check the given declaration statement is legal within a constexpr function 1654 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1655 /// 1656 /// \return true if the body is OK (maybe only as an extension), false if we 1657 /// have diagnosed a problem. 1658 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1659 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1660 // C++11 [dcl.constexpr]p3 and p4: 1661 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1662 // contain only 1663 for (const auto *DclIt : DS->decls()) { 1664 switch (DclIt->getKind()) { 1665 case Decl::StaticAssert: 1666 case Decl::Using: 1667 case Decl::UsingShadow: 1668 case Decl::UsingDirective: 1669 case Decl::UnresolvedUsingTypename: 1670 case Decl::UnresolvedUsingValue: 1671 // - static_assert-declarations 1672 // - using-declarations, 1673 // - using-directives, 1674 continue; 1675 1676 case Decl::Typedef: 1677 case Decl::TypeAlias: { 1678 // - typedef declarations and alias-declarations that do not define 1679 // classes or enumerations, 1680 const auto *TN = cast<TypedefNameDecl>(DclIt); 1681 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1682 // Don't allow variably-modified types in constexpr functions. 1683 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1684 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1685 << TL.getSourceRange() << TL.getType() 1686 << isa<CXXConstructorDecl>(Dcl); 1687 return false; 1688 } 1689 continue; 1690 } 1691 1692 case Decl::Enum: 1693 case Decl::CXXRecord: 1694 // C++1y allows types to be defined, not just declared. 1695 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1696 SemaRef.Diag(DS->getLocStart(), 1697 SemaRef.getLangOpts().CPlusPlus14 1698 ? diag::warn_cxx11_compat_constexpr_type_definition 1699 : diag::ext_constexpr_type_definition) 1700 << isa<CXXConstructorDecl>(Dcl); 1701 continue; 1702 1703 case Decl::EnumConstant: 1704 case Decl::IndirectField: 1705 case Decl::ParmVar: 1706 // These can only appear with other declarations which are banned in 1707 // C++11 and permitted in C++1y, so ignore them. 1708 continue; 1709 1710 case Decl::Var: 1711 case Decl::Decomposition: { 1712 // C++1y [dcl.constexpr]p3 allows anything except: 1713 // a definition of a variable of non-literal type or of static or 1714 // thread storage duration or for which no initialization is performed. 1715 const auto *VD = cast<VarDecl>(DclIt); 1716 if (VD->isThisDeclarationADefinition()) { 1717 if (VD->isStaticLocal()) { 1718 SemaRef.Diag(VD->getLocation(), 1719 diag::err_constexpr_local_var_static) 1720 << isa<CXXConstructorDecl>(Dcl) 1721 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1722 return false; 1723 } 1724 if (!VD->getType()->isDependentType() && 1725 SemaRef.RequireLiteralType( 1726 VD->getLocation(), VD->getType(), 1727 diag::err_constexpr_local_var_non_literal_type, 1728 isa<CXXConstructorDecl>(Dcl))) 1729 return false; 1730 if (!VD->getType()->isDependentType() && 1731 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1732 SemaRef.Diag(VD->getLocation(), 1733 diag::err_constexpr_local_var_no_init) 1734 << isa<CXXConstructorDecl>(Dcl); 1735 return false; 1736 } 1737 } 1738 SemaRef.Diag(VD->getLocation(), 1739 SemaRef.getLangOpts().CPlusPlus14 1740 ? diag::warn_cxx11_compat_constexpr_local_var 1741 : diag::ext_constexpr_local_var) 1742 << isa<CXXConstructorDecl>(Dcl); 1743 continue; 1744 } 1745 1746 case Decl::NamespaceAlias: 1747 case Decl::Function: 1748 // These are disallowed in C++11 and permitted in C++1y. Allow them 1749 // everywhere as an extension. 1750 if (!Cxx1yLoc.isValid()) 1751 Cxx1yLoc = DS->getLocStart(); 1752 continue; 1753 1754 default: 1755 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1756 << isa<CXXConstructorDecl>(Dcl); 1757 return false; 1758 } 1759 } 1760 1761 return true; 1762 } 1763 1764 /// Check that the given field is initialized within a constexpr constructor. 1765 /// 1766 /// \param Dcl The constexpr constructor being checked. 1767 /// \param Field The field being checked. This may be a member of an anonymous 1768 /// struct or union nested within the class being checked. 1769 /// \param Inits All declarations, including anonymous struct/union members and 1770 /// indirect members, for which any initialization was provided. 1771 /// \param Diagnosed Set to true if an error is produced. 1772 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1773 const FunctionDecl *Dcl, 1774 FieldDecl *Field, 1775 llvm::SmallSet<Decl*, 16> &Inits, 1776 bool &Diagnosed) { 1777 if (Field->isInvalidDecl()) 1778 return; 1779 1780 if (Field->isUnnamedBitfield()) 1781 return; 1782 1783 // Anonymous unions with no variant members and empty anonymous structs do not 1784 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1785 // indirect fields don't need initializing. 1786 if (Field->isAnonymousStructOrUnion() && 1787 (Field->getType()->isUnionType() 1788 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1789 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1790 return; 1791 1792 if (!Inits.count(Field)) { 1793 if (!Diagnosed) { 1794 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1795 Diagnosed = true; 1796 } 1797 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1798 } else if (Field->isAnonymousStructOrUnion()) { 1799 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1800 for (auto *I : RD->fields()) 1801 // If an anonymous union contains an anonymous struct of which any member 1802 // is initialized, all members must be initialized. 1803 if (!RD->isUnion() || Inits.count(I)) 1804 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1805 } 1806 } 1807 1808 /// Check the provided statement is allowed in a constexpr function 1809 /// definition. 1810 static bool 1811 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1812 SmallVectorImpl<SourceLocation> &ReturnStmts, 1813 SourceLocation &Cxx1yLoc) { 1814 // - its function-body shall be [...] a compound-statement that contains only 1815 switch (S->getStmtClass()) { 1816 case Stmt::NullStmtClass: 1817 // - null statements, 1818 return true; 1819 1820 case Stmt::DeclStmtClass: 1821 // - static_assert-declarations 1822 // - using-declarations, 1823 // - using-directives, 1824 // - typedef declarations and alias-declarations that do not define 1825 // classes or enumerations, 1826 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1827 return false; 1828 return true; 1829 1830 case Stmt::ReturnStmtClass: 1831 // - and exactly one return statement; 1832 if (isa<CXXConstructorDecl>(Dcl)) { 1833 // C++1y allows return statements in constexpr constructors. 1834 if (!Cxx1yLoc.isValid()) 1835 Cxx1yLoc = S->getLocStart(); 1836 return true; 1837 } 1838 1839 ReturnStmts.push_back(S->getLocStart()); 1840 return true; 1841 1842 case Stmt::CompoundStmtClass: { 1843 // C++1y allows compound-statements. 1844 if (!Cxx1yLoc.isValid()) 1845 Cxx1yLoc = S->getLocStart(); 1846 1847 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1848 for (auto *BodyIt : CompStmt->body()) { 1849 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1850 Cxx1yLoc)) 1851 return false; 1852 } 1853 return true; 1854 } 1855 1856 case Stmt::AttributedStmtClass: 1857 if (!Cxx1yLoc.isValid()) 1858 Cxx1yLoc = S->getLocStart(); 1859 return true; 1860 1861 case Stmt::IfStmtClass: { 1862 // C++1y allows if-statements. 1863 if (!Cxx1yLoc.isValid()) 1864 Cxx1yLoc = S->getLocStart(); 1865 1866 IfStmt *If = cast<IfStmt>(S); 1867 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1868 Cxx1yLoc)) 1869 return false; 1870 if (If->getElse() && 1871 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1872 Cxx1yLoc)) 1873 return false; 1874 return true; 1875 } 1876 1877 case Stmt::WhileStmtClass: 1878 case Stmt::DoStmtClass: 1879 case Stmt::ForStmtClass: 1880 case Stmt::CXXForRangeStmtClass: 1881 case Stmt::ContinueStmtClass: 1882 // C++1y allows all of these. We don't allow them as extensions in C++11, 1883 // because they don't make sense without variable mutation. 1884 if (!SemaRef.getLangOpts().CPlusPlus14) 1885 break; 1886 if (!Cxx1yLoc.isValid()) 1887 Cxx1yLoc = S->getLocStart(); 1888 for (Stmt *SubStmt : S->children()) 1889 if (SubStmt && 1890 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1891 Cxx1yLoc)) 1892 return false; 1893 return true; 1894 1895 case Stmt::SwitchStmtClass: 1896 case Stmt::CaseStmtClass: 1897 case Stmt::DefaultStmtClass: 1898 case Stmt::BreakStmtClass: 1899 // C++1y allows switch-statements, and since they don't need variable 1900 // mutation, we can reasonably allow them in C++11 as an extension. 1901 if (!Cxx1yLoc.isValid()) 1902 Cxx1yLoc = S->getLocStart(); 1903 for (Stmt *SubStmt : S->children()) 1904 if (SubStmt && 1905 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1906 Cxx1yLoc)) 1907 return false; 1908 return true; 1909 1910 default: 1911 if (!isa<Expr>(S)) 1912 break; 1913 1914 // C++1y allows expression-statements. 1915 if (!Cxx1yLoc.isValid()) 1916 Cxx1yLoc = S->getLocStart(); 1917 return true; 1918 } 1919 1920 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1921 << isa<CXXConstructorDecl>(Dcl); 1922 return false; 1923 } 1924 1925 /// Check the body for the given constexpr function declaration only contains 1926 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1927 /// 1928 /// \return true if the body is OK, false if we have diagnosed a problem. 1929 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1930 if (isa<CXXTryStmt>(Body)) { 1931 // C++11 [dcl.constexpr]p3: 1932 // The definition of a constexpr function shall satisfy the following 1933 // constraints: [...] 1934 // - its function-body shall be = delete, = default, or a 1935 // compound-statement 1936 // 1937 // C++11 [dcl.constexpr]p4: 1938 // In the definition of a constexpr constructor, [...] 1939 // - its function-body shall not be a function-try-block; 1940 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1941 << isa<CXXConstructorDecl>(Dcl); 1942 return false; 1943 } 1944 1945 SmallVector<SourceLocation, 4> ReturnStmts; 1946 1947 // - its function-body shall be [...] a compound-statement that contains only 1948 // [... list of cases ...] 1949 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1950 SourceLocation Cxx1yLoc; 1951 for (auto *BodyIt : CompBody->body()) { 1952 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1953 return false; 1954 } 1955 1956 if (Cxx1yLoc.isValid()) 1957 Diag(Cxx1yLoc, 1958 getLangOpts().CPlusPlus14 1959 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1960 : diag::ext_constexpr_body_invalid_stmt) 1961 << isa<CXXConstructorDecl>(Dcl); 1962 1963 if (const CXXConstructorDecl *Constructor 1964 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1965 const CXXRecordDecl *RD = Constructor->getParent(); 1966 // DR1359: 1967 // - every non-variant non-static data member and base class sub-object 1968 // shall be initialized; 1969 // DR1460: 1970 // - if the class is a union having variant members, exactly one of them 1971 // shall be initialized; 1972 if (RD->isUnion()) { 1973 if (Constructor->getNumCtorInitializers() == 0 && 1974 RD->hasVariantMembers()) { 1975 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1976 return false; 1977 } 1978 } else if (!Constructor->isDependentContext() && 1979 !Constructor->isDelegatingConstructor()) { 1980 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1981 1982 // Skip detailed checking if we have enough initializers, and we would 1983 // allow at most one initializer per member. 1984 bool AnyAnonStructUnionMembers = false; 1985 unsigned Fields = 0; 1986 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1987 E = RD->field_end(); I != E; ++I, ++Fields) { 1988 if (I->isAnonymousStructOrUnion()) { 1989 AnyAnonStructUnionMembers = true; 1990 break; 1991 } 1992 } 1993 // DR1460: 1994 // - if the class is a union-like class, but is not a union, for each of 1995 // its anonymous union members having variant members, exactly one of 1996 // them shall be initialized; 1997 if (AnyAnonStructUnionMembers || 1998 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1999 // Check initialization of non-static data members. Base classes are 2000 // always initialized so do not need to be checked. Dependent bases 2001 // might not have initializers in the member initializer list. 2002 llvm::SmallSet<Decl*, 16> Inits; 2003 for (const auto *I: Constructor->inits()) { 2004 if (FieldDecl *FD = I->getMember()) 2005 Inits.insert(FD); 2006 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2007 Inits.insert(ID->chain_begin(), ID->chain_end()); 2008 } 2009 2010 bool Diagnosed = false; 2011 for (auto *I : RD->fields()) 2012 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2013 if (Diagnosed) 2014 return false; 2015 } 2016 } 2017 } else { 2018 if (ReturnStmts.empty()) { 2019 // C++1y doesn't require constexpr functions to contain a 'return' 2020 // statement. We still do, unless the return type might be void, because 2021 // otherwise if there's no return statement, the function cannot 2022 // be used in a core constant expression. 2023 bool OK = getLangOpts().CPlusPlus14 && 2024 (Dcl->getReturnType()->isVoidType() || 2025 Dcl->getReturnType()->isDependentType()); 2026 Diag(Dcl->getLocation(), 2027 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2028 : diag::err_constexpr_body_no_return); 2029 if (!OK) 2030 return false; 2031 } else if (ReturnStmts.size() > 1) { 2032 Diag(ReturnStmts.back(), 2033 getLangOpts().CPlusPlus14 2034 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2035 : diag::ext_constexpr_body_multiple_return); 2036 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2037 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2038 } 2039 } 2040 2041 // C++11 [dcl.constexpr]p5: 2042 // if no function argument values exist such that the function invocation 2043 // substitution would produce a constant expression, the program is 2044 // ill-formed; no diagnostic required. 2045 // C++11 [dcl.constexpr]p3: 2046 // - every constructor call and implicit conversion used in initializing the 2047 // return value shall be one of those allowed in a constant expression. 2048 // C++11 [dcl.constexpr]p4: 2049 // - every constructor involved in initializing non-static data members and 2050 // base class sub-objects shall be a constexpr constructor. 2051 SmallVector<PartialDiagnosticAt, 8> Diags; 2052 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2053 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2054 << isa<CXXConstructorDecl>(Dcl); 2055 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2056 Diag(Diags[I].first, Diags[I].second); 2057 // Don't return false here: we allow this for compatibility in 2058 // system headers. 2059 } 2060 2061 return true; 2062 } 2063 2064 /// isCurrentClassName - Determine whether the identifier II is the 2065 /// name of the class type currently being defined. In the case of 2066 /// nested classes, this will only return true if II is the name of 2067 /// the innermost class. 2068 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2069 const CXXScopeSpec *SS) { 2070 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2071 2072 CXXRecordDecl *CurDecl; 2073 if (SS && SS->isSet() && !SS->isInvalid()) { 2074 DeclContext *DC = computeDeclContext(*SS, true); 2075 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2076 } else 2077 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2078 2079 if (CurDecl && CurDecl->getIdentifier()) 2080 return &II == CurDecl->getIdentifier(); 2081 return false; 2082 } 2083 2084 /// \brief Determine whether the identifier II is a typo for the name of 2085 /// the class type currently being defined. If so, update it to the identifier 2086 /// that should have been used. 2087 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2088 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2089 2090 if (!getLangOpts().SpellChecking) 2091 return false; 2092 2093 CXXRecordDecl *CurDecl; 2094 if (SS && SS->isSet() && !SS->isInvalid()) { 2095 DeclContext *DC = computeDeclContext(*SS, true); 2096 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2097 } else 2098 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2099 2100 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2101 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2102 < II->getLength()) { 2103 II = CurDecl->getIdentifier(); 2104 return true; 2105 } 2106 2107 return false; 2108 } 2109 2110 /// \brief Determine whether the given class is a base class of the given 2111 /// class, including looking at dependent bases. 2112 static bool findCircularInheritance(const CXXRecordDecl *Class, 2113 const CXXRecordDecl *Current) { 2114 SmallVector<const CXXRecordDecl*, 8> Queue; 2115 2116 Class = Class->getCanonicalDecl(); 2117 while (true) { 2118 for (const auto &I : Current->bases()) { 2119 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2120 if (!Base) 2121 continue; 2122 2123 Base = Base->getDefinition(); 2124 if (!Base) 2125 continue; 2126 2127 if (Base->getCanonicalDecl() == Class) 2128 return true; 2129 2130 Queue.push_back(Base); 2131 } 2132 2133 if (Queue.empty()) 2134 return false; 2135 2136 Current = Queue.pop_back_val(); 2137 } 2138 2139 return false; 2140 } 2141 2142 /// \brief Check the validity of a C++ base class specifier. 2143 /// 2144 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2145 /// and returns NULL otherwise. 2146 CXXBaseSpecifier * 2147 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2148 SourceRange SpecifierRange, 2149 bool Virtual, AccessSpecifier Access, 2150 TypeSourceInfo *TInfo, 2151 SourceLocation EllipsisLoc) { 2152 QualType BaseType = TInfo->getType(); 2153 2154 // C++ [class.union]p1: 2155 // A union shall not have base classes. 2156 if (Class->isUnion()) { 2157 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2158 << SpecifierRange; 2159 return nullptr; 2160 } 2161 2162 if (EllipsisLoc.isValid() && 2163 !TInfo->getType()->containsUnexpandedParameterPack()) { 2164 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2165 << TInfo->getTypeLoc().getSourceRange(); 2166 EllipsisLoc = SourceLocation(); 2167 } 2168 2169 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2170 2171 if (BaseType->isDependentType()) { 2172 // Make sure that we don't have circular inheritance among our dependent 2173 // bases. For non-dependent bases, the check for completeness below handles 2174 // this. 2175 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2176 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2177 ((BaseDecl = BaseDecl->getDefinition()) && 2178 findCircularInheritance(Class, BaseDecl))) { 2179 Diag(BaseLoc, diag::err_circular_inheritance) 2180 << BaseType << Context.getTypeDeclType(Class); 2181 2182 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2183 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2184 << BaseType; 2185 2186 return nullptr; 2187 } 2188 } 2189 2190 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2191 Class->getTagKind() == TTK_Class, 2192 Access, TInfo, EllipsisLoc); 2193 } 2194 2195 // Base specifiers must be record types. 2196 if (!BaseType->isRecordType()) { 2197 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2198 return nullptr; 2199 } 2200 2201 // C++ [class.union]p1: 2202 // A union shall not be used as a base class. 2203 if (BaseType->isUnionType()) { 2204 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2205 return nullptr; 2206 } 2207 2208 // For the MS ABI, propagate DLL attributes to base class templates. 2209 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2210 if (Attr *ClassAttr = getDLLAttr(Class)) { 2211 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2212 BaseType->getAsCXXRecordDecl())) { 2213 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2214 BaseLoc); 2215 } 2216 } 2217 } 2218 2219 // C++ [class.derived]p2: 2220 // The class-name in a base-specifier shall not be an incompletely 2221 // defined class. 2222 if (RequireCompleteType(BaseLoc, BaseType, 2223 diag::err_incomplete_base_class, SpecifierRange)) { 2224 Class->setInvalidDecl(); 2225 return nullptr; 2226 } 2227 2228 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2229 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2230 assert(BaseDecl && "Record type has no declaration"); 2231 BaseDecl = BaseDecl->getDefinition(); 2232 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2233 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2234 assert(CXXBaseDecl && "Base type is not a C++ type"); 2235 2236 // A class which contains a flexible array member is not suitable for use as a 2237 // base class: 2238 // - If the layout determines that a base comes before another base, 2239 // the flexible array member would index into the subsequent base. 2240 // - If the layout determines that base comes before the derived class, 2241 // the flexible array member would index into the derived class. 2242 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2243 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2244 << CXXBaseDecl->getDeclName(); 2245 return nullptr; 2246 } 2247 2248 // C++ [class]p3: 2249 // If a class is marked final and it appears as a base-type-specifier in 2250 // base-clause, the program is ill-formed. 2251 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2252 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2253 << CXXBaseDecl->getDeclName() 2254 << FA->isSpelledAsSealed(); 2255 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2256 << CXXBaseDecl->getDeclName() << FA->getRange(); 2257 return nullptr; 2258 } 2259 2260 if (BaseDecl->isInvalidDecl()) 2261 Class->setInvalidDecl(); 2262 2263 // Create the base specifier. 2264 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2265 Class->getTagKind() == TTK_Class, 2266 Access, TInfo, EllipsisLoc); 2267 } 2268 2269 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2270 /// one entry in the base class list of a class specifier, for 2271 /// example: 2272 /// class foo : public bar, virtual private baz { 2273 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2274 BaseResult 2275 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2276 ParsedAttributes &Attributes, 2277 bool Virtual, AccessSpecifier Access, 2278 ParsedType basetype, SourceLocation BaseLoc, 2279 SourceLocation EllipsisLoc) { 2280 if (!classdecl) 2281 return true; 2282 2283 AdjustDeclIfTemplate(classdecl); 2284 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2285 if (!Class) 2286 return true; 2287 2288 // We haven't yet attached the base specifiers. 2289 Class->setIsParsingBaseSpecifiers(); 2290 2291 // We do not support any C++11 attributes on base-specifiers yet. 2292 // Diagnose any attributes we see. 2293 if (!Attributes.empty()) { 2294 for (AttributeList *Attr = Attributes.getList(); Attr; 2295 Attr = Attr->getNext()) { 2296 if (Attr->isInvalid() || 2297 Attr->getKind() == AttributeList::IgnoredAttribute) 2298 continue; 2299 Diag(Attr->getLoc(), 2300 Attr->getKind() == AttributeList::UnknownAttribute 2301 ? diag::warn_unknown_attribute_ignored 2302 : diag::err_base_specifier_attribute) 2303 << Attr->getName(); 2304 } 2305 } 2306 2307 TypeSourceInfo *TInfo = nullptr; 2308 GetTypeFromParser(basetype, &TInfo); 2309 2310 if (EllipsisLoc.isInvalid() && 2311 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2312 UPPC_BaseType)) 2313 return true; 2314 2315 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2316 Virtual, Access, TInfo, 2317 EllipsisLoc)) 2318 return BaseSpec; 2319 else 2320 Class->setInvalidDecl(); 2321 2322 return true; 2323 } 2324 2325 /// Use small set to collect indirect bases. As this is only used 2326 /// locally, there's no need to abstract the small size parameter. 2327 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2328 2329 /// \brief Recursively add the bases of Type. Don't add Type itself. 2330 static void 2331 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2332 const QualType &Type) 2333 { 2334 // Even though the incoming type is a base, it might not be 2335 // a class -- it could be a template parm, for instance. 2336 if (auto Rec = Type->getAs<RecordType>()) { 2337 auto Decl = Rec->getAsCXXRecordDecl(); 2338 2339 // Iterate over its bases. 2340 for (const auto &BaseSpec : Decl->bases()) { 2341 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2342 .getUnqualifiedType(); 2343 if (Set.insert(Base).second) 2344 // If we've not already seen it, recurse. 2345 NoteIndirectBases(Context, Set, Base); 2346 } 2347 } 2348 } 2349 2350 /// \brief Performs the actual work of attaching the given base class 2351 /// specifiers to a C++ class. 2352 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2353 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2354 if (Bases.empty()) 2355 return false; 2356 2357 // Used to keep track of which base types we have already seen, so 2358 // that we can properly diagnose redundant direct base types. Note 2359 // that the key is always the unqualified canonical type of the base 2360 // class. 2361 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2362 2363 // Used to track indirect bases so we can see if a direct base is 2364 // ambiguous. 2365 IndirectBaseSet IndirectBaseTypes; 2366 2367 // Copy non-redundant base specifiers into permanent storage. 2368 unsigned NumGoodBases = 0; 2369 bool Invalid = false; 2370 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2371 QualType NewBaseType 2372 = Context.getCanonicalType(Bases[idx]->getType()); 2373 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2374 2375 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2376 if (KnownBase) { 2377 // C++ [class.mi]p3: 2378 // A class shall not be specified as a direct base class of a 2379 // derived class more than once. 2380 Diag(Bases[idx]->getLocStart(), 2381 diag::err_duplicate_base_class) 2382 << KnownBase->getType() 2383 << Bases[idx]->getSourceRange(); 2384 2385 // Delete the duplicate base class specifier; we're going to 2386 // overwrite its pointer later. 2387 Context.Deallocate(Bases[idx]); 2388 2389 Invalid = true; 2390 } else { 2391 // Okay, add this new base class. 2392 KnownBase = Bases[idx]; 2393 Bases[NumGoodBases++] = Bases[idx]; 2394 2395 // Note this base's direct & indirect bases, if there could be ambiguity. 2396 if (Bases.size() > 1) 2397 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2398 2399 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2400 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2401 if (Class->isInterface() && 2402 (!RD->isInterfaceLike() || 2403 KnownBase->getAccessSpecifier() != AS_public)) { 2404 // The Microsoft extension __interface does not permit bases that 2405 // are not themselves public interfaces. 2406 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2407 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2408 << RD->getSourceRange(); 2409 Invalid = true; 2410 } 2411 if (RD->hasAttr<WeakAttr>()) 2412 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2413 } 2414 } 2415 } 2416 2417 // Attach the remaining base class specifiers to the derived class. 2418 Class->setBases(Bases.data(), NumGoodBases); 2419 2420 // Check that the only base classes that are duplicate are virtual. 2421 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2422 // Check whether this direct base is inaccessible due to ambiguity. 2423 QualType BaseType = Bases[idx]->getType(); 2424 2425 // Skip all dependent types in templates being used as base specifiers. 2426 // Checks below assume that the base specifier is a CXXRecord. 2427 if (BaseType->isDependentType()) 2428 continue; 2429 2430 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2431 .getUnqualifiedType(); 2432 2433 if (IndirectBaseTypes.count(CanonicalBase)) { 2434 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2435 /*DetectVirtual=*/true); 2436 bool found 2437 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2438 assert(found); 2439 (void)found; 2440 2441 if (Paths.isAmbiguous(CanonicalBase)) 2442 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2443 << BaseType << getAmbiguousPathsDisplayString(Paths) 2444 << Bases[idx]->getSourceRange(); 2445 else 2446 assert(Bases[idx]->isVirtual()); 2447 } 2448 2449 // Delete the base class specifier, since its data has been copied 2450 // into the CXXRecordDecl. 2451 Context.Deallocate(Bases[idx]); 2452 } 2453 2454 return Invalid; 2455 } 2456 2457 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2458 /// class, after checking whether there are any duplicate base 2459 /// classes. 2460 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2461 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2462 if (!ClassDecl || Bases.empty()) 2463 return; 2464 2465 AdjustDeclIfTemplate(ClassDecl); 2466 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2467 } 2468 2469 /// \brief Determine whether the type \p Derived is a C++ class that is 2470 /// derived from the type \p Base. 2471 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2472 if (!getLangOpts().CPlusPlus) 2473 return false; 2474 2475 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2476 if (!DerivedRD) 2477 return false; 2478 2479 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2480 if (!BaseRD) 2481 return false; 2482 2483 // If either the base or the derived type is invalid, don't try to 2484 // check whether one is derived from the other. 2485 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2486 return false; 2487 2488 // FIXME: In a modules build, do we need the entire path to be visible for us 2489 // to be able to use the inheritance relationship? 2490 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2491 return false; 2492 2493 return DerivedRD->isDerivedFrom(BaseRD); 2494 } 2495 2496 /// \brief Determine whether the type \p Derived is a C++ class that is 2497 /// derived from the type \p Base. 2498 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2499 CXXBasePaths &Paths) { 2500 if (!getLangOpts().CPlusPlus) 2501 return false; 2502 2503 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2504 if (!DerivedRD) 2505 return false; 2506 2507 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2508 if (!BaseRD) 2509 return false; 2510 2511 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2512 return false; 2513 2514 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2515 } 2516 2517 static void BuildBasePathArray(const CXXBasePath &Path, 2518 CXXCastPath &BasePathArray) { 2519 // We first go backward and check if we have a virtual base. 2520 // FIXME: It would be better if CXXBasePath had the base specifier for 2521 // the nearest virtual base. 2522 unsigned Start = 0; 2523 for (unsigned I = Path.size(); I != 0; --I) { 2524 if (Path[I - 1].Base->isVirtual()) { 2525 Start = I - 1; 2526 break; 2527 } 2528 } 2529 2530 // Now add all bases. 2531 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2533 } 2534 2535 2536 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2537 CXXCastPath &BasePathArray) { 2538 assert(BasePathArray.empty() && "Base path array must be empty!"); 2539 assert(Paths.isRecordingPaths() && "Must record paths!"); 2540 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2541 } 2542 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2543 /// conversion (where Derived and Base are class types) is 2544 /// well-formed, meaning that the conversion is unambiguous (and 2545 /// that all of the base classes are accessible). Returns true 2546 /// and emits a diagnostic if the code is ill-formed, returns false 2547 /// otherwise. Loc is the location where this routine should point to 2548 /// if there is an error, and Range is the source range to highlight 2549 /// if there is an error. 2550 /// 2551 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2552 /// diagnostic for the respective type of error will be suppressed, but the 2553 /// check for ill-formed code will still be performed. 2554 bool 2555 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2556 unsigned InaccessibleBaseID, 2557 unsigned AmbigiousBaseConvID, 2558 SourceLocation Loc, SourceRange Range, 2559 DeclarationName Name, 2560 CXXCastPath *BasePath, 2561 bool IgnoreAccess) { 2562 // First, determine whether the path from Derived to Base is 2563 // ambiguous. This is slightly more expensive than checking whether 2564 // the Derived to Base conversion exists, because here we need to 2565 // explore multiple paths to determine if there is an ambiguity. 2566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2567 /*DetectVirtual=*/false); 2568 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2569 if (!DerivationOkay) 2570 return true; 2571 2572 const CXXBasePath *Path = nullptr; 2573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2574 Path = &Paths.front(); 2575 2576 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2577 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2578 // user to access such bases. 2579 if (!Path && getLangOpts().MSVCCompat) { 2580 for (const CXXBasePath &PossiblePath : Paths) { 2581 if (PossiblePath.size() == 1) { 2582 Path = &PossiblePath; 2583 if (AmbigiousBaseConvID) 2584 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2585 << Base << Derived << Range; 2586 break; 2587 } 2588 } 2589 } 2590 2591 if (Path) { 2592 if (!IgnoreAccess) { 2593 // Check that the base class can be accessed. 2594 switch ( 2595 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2596 case AR_inaccessible: 2597 return true; 2598 case AR_accessible: 2599 case AR_dependent: 2600 case AR_delayed: 2601 break; 2602 } 2603 } 2604 2605 // Build a base path if necessary. 2606 if (BasePath) 2607 ::BuildBasePathArray(*Path, *BasePath); 2608 return false; 2609 } 2610 2611 if (AmbigiousBaseConvID) { 2612 // We know that the derived-to-base conversion is ambiguous, and 2613 // we're going to produce a diagnostic. Perform the derived-to-base 2614 // search just one more time to compute all of the possible paths so 2615 // that we can print them out. This is more expensive than any of 2616 // the previous derived-to-base checks we've done, but at this point 2617 // performance isn't as much of an issue. 2618 Paths.clear(); 2619 Paths.setRecordingPaths(true); 2620 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2621 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2622 (void)StillOkay; 2623 2624 // Build up a textual representation of the ambiguous paths, e.g., 2625 // D -> B -> A, that will be used to illustrate the ambiguous 2626 // conversions in the diagnostic. We only print one of the paths 2627 // to each base class subobject. 2628 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2629 2630 Diag(Loc, AmbigiousBaseConvID) 2631 << Derived << Base << PathDisplayStr << Range << Name; 2632 } 2633 return true; 2634 } 2635 2636 bool 2637 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2638 SourceLocation Loc, SourceRange Range, 2639 CXXCastPath *BasePath, 2640 bool IgnoreAccess) { 2641 return CheckDerivedToBaseConversion( 2642 Derived, Base, diag::err_upcast_to_inaccessible_base, 2643 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2644 BasePath, IgnoreAccess); 2645 } 2646 2647 2648 /// @brief Builds a string representing ambiguous paths from a 2649 /// specific derived class to different subobjects of the same base 2650 /// class. 2651 /// 2652 /// This function builds a string that can be used in error messages 2653 /// to show the different paths that one can take through the 2654 /// inheritance hierarchy to go from the derived class to different 2655 /// subobjects of a base class. The result looks something like this: 2656 /// @code 2657 /// struct D -> struct B -> struct A 2658 /// struct D -> struct C -> struct A 2659 /// @endcode 2660 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2661 std::string PathDisplayStr; 2662 std::set<unsigned> DisplayedPaths; 2663 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2664 Path != Paths.end(); ++Path) { 2665 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2666 // We haven't displayed a path to this particular base 2667 // class subobject yet. 2668 PathDisplayStr += "\n "; 2669 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2670 for (CXXBasePath::const_iterator Element = Path->begin(); 2671 Element != Path->end(); ++Element) 2672 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2673 } 2674 } 2675 2676 return PathDisplayStr; 2677 } 2678 2679 //===----------------------------------------------------------------------===// 2680 // C++ class member Handling 2681 //===----------------------------------------------------------------------===// 2682 2683 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2684 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2685 SourceLocation ASLoc, 2686 SourceLocation ColonLoc, 2687 AttributeList *Attrs) { 2688 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2689 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2690 ASLoc, ColonLoc); 2691 CurContext->addHiddenDecl(ASDecl); 2692 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2693 } 2694 2695 /// CheckOverrideControl - Check C++11 override control semantics. 2696 void Sema::CheckOverrideControl(NamedDecl *D) { 2697 if (D->isInvalidDecl()) 2698 return; 2699 2700 // We only care about "override" and "final" declarations. 2701 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2702 return; 2703 2704 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2705 2706 // We can't check dependent instance methods. 2707 if (MD && MD->isInstance() && 2708 (MD->getParent()->hasAnyDependentBases() || 2709 MD->getType()->isDependentType())) 2710 return; 2711 2712 if (MD && !MD->isVirtual()) { 2713 // If we have a non-virtual method, check if if hides a virtual method. 2714 // (In that case, it's most likely the method has the wrong type.) 2715 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2716 FindHiddenVirtualMethods(MD, OverloadedMethods); 2717 2718 if (!OverloadedMethods.empty()) { 2719 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2720 Diag(OA->getLocation(), 2721 diag::override_keyword_hides_virtual_member_function) 2722 << "override" << (OverloadedMethods.size() > 1); 2723 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2724 Diag(FA->getLocation(), 2725 diag::override_keyword_hides_virtual_member_function) 2726 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2727 << (OverloadedMethods.size() > 1); 2728 } 2729 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2730 MD->setInvalidDecl(); 2731 return; 2732 } 2733 // Fall through into the general case diagnostic. 2734 // FIXME: We might want to attempt typo correction here. 2735 } 2736 2737 if (!MD || !MD->isVirtual()) { 2738 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2739 Diag(OA->getLocation(), 2740 diag::override_keyword_only_allowed_on_virtual_member_functions) 2741 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2742 D->dropAttr<OverrideAttr>(); 2743 } 2744 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2745 Diag(FA->getLocation(), 2746 diag::override_keyword_only_allowed_on_virtual_member_functions) 2747 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2748 << FixItHint::CreateRemoval(FA->getLocation()); 2749 D->dropAttr<FinalAttr>(); 2750 } 2751 return; 2752 } 2753 2754 // C++11 [class.virtual]p5: 2755 // If a function is marked with the virt-specifier override and 2756 // does not override a member function of a base class, the program is 2757 // ill-formed. 2758 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2759 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2760 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2761 << MD->getDeclName(); 2762 } 2763 2764 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2765 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2766 return; 2767 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2768 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2769 return; 2770 2771 SourceLocation Loc = MD->getLocation(); 2772 SourceLocation SpellingLoc = Loc; 2773 if (getSourceManager().isMacroArgExpansion(Loc)) 2774 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2775 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2776 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2777 return; 2778 2779 if (MD->size_overridden_methods() > 0) { 2780 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2781 ? diag::warn_destructor_marked_not_override_overriding 2782 : diag::warn_function_marked_not_override_overriding; 2783 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2784 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2785 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2786 } 2787 } 2788 2789 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2790 /// function overrides a virtual member function marked 'final', according to 2791 /// C++11 [class.virtual]p4. 2792 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2793 const CXXMethodDecl *Old) { 2794 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2795 if (!FA) 2796 return false; 2797 2798 Diag(New->getLocation(), diag::err_final_function_overridden) 2799 << New->getDeclName() 2800 << FA->isSpelledAsSealed(); 2801 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2802 return true; 2803 } 2804 2805 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2806 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2807 // FIXME: Destruction of ObjC lifetime types has side-effects. 2808 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2809 return !RD->isCompleteDefinition() || 2810 !RD->hasTrivialDefaultConstructor() || 2811 !RD->hasTrivialDestructor(); 2812 return false; 2813 } 2814 2815 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2816 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2817 if (it->isDeclspecPropertyAttribute()) 2818 return it; 2819 return nullptr; 2820 } 2821 2822 // Check if there is a field shadowing. 2823 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2824 DeclarationName FieldName, 2825 const CXXRecordDecl *RD) { 2826 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2827 return; 2828 2829 // To record a shadowed field in a base 2830 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2831 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2832 CXXBasePath &Path) { 2833 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2834 // Record an ambiguous path directly 2835 if (Bases.find(Base) != Bases.end()) 2836 return true; 2837 for (const auto Field : Base->lookup(FieldName)) { 2838 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2839 Field->getAccess() != AS_private) { 2840 assert(Field->getAccess() != AS_none); 2841 assert(Bases.find(Base) == Bases.end()); 2842 Bases[Base] = Field; 2843 return true; 2844 } 2845 } 2846 return false; 2847 }; 2848 2849 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2850 /*DetectVirtual=*/true); 2851 if (!RD->lookupInBases(FieldShadowed, Paths)) 2852 return; 2853 2854 for (const auto &P : Paths) { 2855 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2856 auto It = Bases.find(Base); 2857 // Skip duplicated bases 2858 if (It == Bases.end()) 2859 continue; 2860 auto BaseField = It->second; 2861 assert(BaseField->getAccess() != AS_private); 2862 if (AS_none != 2863 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2864 Diag(Loc, diag::warn_shadow_field) 2865 << FieldName << RD << Base; 2866 Diag(BaseField->getLocation(), diag::note_shadow_field); 2867 Bases.erase(It); 2868 } 2869 } 2870 } 2871 2872 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2873 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2874 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2875 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2876 /// present (but parsing it has been deferred). 2877 NamedDecl * 2878 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2879 MultiTemplateParamsArg TemplateParameterLists, 2880 Expr *BW, const VirtSpecifiers &VS, 2881 InClassInitStyle InitStyle) { 2882 const DeclSpec &DS = D.getDeclSpec(); 2883 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2884 DeclarationName Name = NameInfo.getName(); 2885 SourceLocation Loc = NameInfo.getLoc(); 2886 2887 // For anonymous bitfields, the location should point to the type. 2888 if (Loc.isInvalid()) 2889 Loc = D.getLocStart(); 2890 2891 Expr *BitWidth = static_cast<Expr*>(BW); 2892 2893 assert(isa<CXXRecordDecl>(CurContext)); 2894 assert(!DS.isFriendSpecified()); 2895 2896 bool isFunc = D.isDeclarationOfFunction(); 2897 AttributeList *MSPropertyAttr = 2898 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2899 2900 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2901 // The Microsoft extension __interface only permits public member functions 2902 // and prohibits constructors, destructors, operators, non-public member 2903 // functions, static methods and data members. 2904 unsigned InvalidDecl; 2905 bool ShowDeclName = true; 2906 if (!isFunc && 2907 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2908 InvalidDecl = 0; 2909 else if (!isFunc) 2910 InvalidDecl = 1; 2911 else if (AS != AS_public) 2912 InvalidDecl = 2; 2913 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2914 InvalidDecl = 3; 2915 else switch (Name.getNameKind()) { 2916 case DeclarationName::CXXConstructorName: 2917 InvalidDecl = 4; 2918 ShowDeclName = false; 2919 break; 2920 2921 case DeclarationName::CXXDestructorName: 2922 InvalidDecl = 5; 2923 ShowDeclName = false; 2924 break; 2925 2926 case DeclarationName::CXXOperatorName: 2927 case DeclarationName::CXXConversionFunctionName: 2928 InvalidDecl = 6; 2929 break; 2930 2931 default: 2932 InvalidDecl = 0; 2933 break; 2934 } 2935 2936 if (InvalidDecl) { 2937 if (ShowDeclName) 2938 Diag(Loc, diag::err_invalid_member_in_interface) 2939 << (InvalidDecl-1) << Name; 2940 else 2941 Diag(Loc, diag::err_invalid_member_in_interface) 2942 << (InvalidDecl-1) << ""; 2943 return nullptr; 2944 } 2945 } 2946 2947 // C++ 9.2p6: A member shall not be declared to have automatic storage 2948 // duration (auto, register) or with the extern storage-class-specifier. 2949 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2950 // data members and cannot be applied to names declared const or static, 2951 // and cannot be applied to reference members. 2952 switch (DS.getStorageClassSpec()) { 2953 case DeclSpec::SCS_unspecified: 2954 case DeclSpec::SCS_typedef: 2955 case DeclSpec::SCS_static: 2956 break; 2957 case DeclSpec::SCS_mutable: 2958 if (isFunc) { 2959 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2960 2961 // FIXME: It would be nicer if the keyword was ignored only for this 2962 // declarator. Otherwise we could get follow-up errors. 2963 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2964 } 2965 break; 2966 default: 2967 Diag(DS.getStorageClassSpecLoc(), 2968 diag::err_storageclass_invalid_for_member); 2969 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2970 break; 2971 } 2972 2973 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2974 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2975 !isFunc); 2976 2977 if (DS.isConstexprSpecified() && isInstField) { 2978 SemaDiagnosticBuilder B = 2979 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2980 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2981 if (InitStyle == ICIS_NoInit) { 2982 B << 0 << 0; 2983 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2984 B << FixItHint::CreateRemoval(ConstexprLoc); 2985 else { 2986 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2987 D.getMutableDeclSpec().ClearConstexprSpec(); 2988 const char *PrevSpec; 2989 unsigned DiagID; 2990 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2991 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2992 (void)Failed; 2993 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2994 } 2995 } else { 2996 B << 1; 2997 const char *PrevSpec; 2998 unsigned DiagID; 2999 if (D.getMutableDeclSpec().SetStorageClassSpec( 3000 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3001 Context.getPrintingPolicy())) { 3002 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3003 "This is the only DeclSpec that should fail to be applied"); 3004 B << 1; 3005 } else { 3006 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3007 isInstField = false; 3008 } 3009 } 3010 } 3011 3012 NamedDecl *Member; 3013 if (isInstField) { 3014 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3015 3016 // Data members must have identifiers for names. 3017 if (!Name.isIdentifier()) { 3018 Diag(Loc, diag::err_bad_variable_name) 3019 << Name; 3020 return nullptr; 3021 } 3022 3023 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3024 3025 // Member field could not be with "template" keyword. 3026 // So TemplateParameterLists should be empty in this case. 3027 if (TemplateParameterLists.size()) { 3028 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3029 if (TemplateParams->size()) { 3030 // There is no such thing as a member field template. 3031 Diag(D.getIdentifierLoc(), diag::err_template_member) 3032 << II 3033 << SourceRange(TemplateParams->getTemplateLoc(), 3034 TemplateParams->getRAngleLoc()); 3035 } else { 3036 // There is an extraneous 'template<>' for this member. 3037 Diag(TemplateParams->getTemplateLoc(), 3038 diag::err_template_member_noparams) 3039 << II 3040 << SourceRange(TemplateParams->getTemplateLoc(), 3041 TemplateParams->getRAngleLoc()); 3042 } 3043 return nullptr; 3044 } 3045 3046 if (SS.isSet() && !SS.isInvalid()) { 3047 // The user provided a superfluous scope specifier inside a class 3048 // definition: 3049 // 3050 // class X { 3051 // int X::member; 3052 // }; 3053 if (DeclContext *DC = computeDeclContext(SS, false)) 3054 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3055 D.getName().getKind() == 3056 UnqualifiedIdKind::IK_TemplateId); 3057 else 3058 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3059 << Name << SS.getRange(); 3060 3061 SS.clear(); 3062 } 3063 3064 if (MSPropertyAttr) { 3065 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3066 BitWidth, InitStyle, AS, MSPropertyAttr); 3067 if (!Member) 3068 return nullptr; 3069 isInstField = false; 3070 } else { 3071 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3072 BitWidth, InitStyle, AS); 3073 if (!Member) 3074 return nullptr; 3075 } 3076 3077 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3078 } else { 3079 Member = HandleDeclarator(S, D, TemplateParameterLists); 3080 if (!Member) 3081 return nullptr; 3082 3083 // Non-instance-fields can't have a bitfield. 3084 if (BitWidth) { 3085 if (Member->isInvalidDecl()) { 3086 // don't emit another diagnostic. 3087 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3088 // C++ 9.6p3: A bit-field shall not be a static member. 3089 // "static member 'A' cannot be a bit-field" 3090 Diag(Loc, diag::err_static_not_bitfield) 3091 << Name << BitWidth->getSourceRange(); 3092 } else if (isa<TypedefDecl>(Member)) { 3093 // "typedef member 'x' cannot be a bit-field" 3094 Diag(Loc, diag::err_typedef_not_bitfield) 3095 << Name << BitWidth->getSourceRange(); 3096 } else { 3097 // A function typedef ("typedef int f(); f a;"). 3098 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3099 Diag(Loc, diag::err_not_integral_type_bitfield) 3100 << Name << cast<ValueDecl>(Member)->getType() 3101 << BitWidth->getSourceRange(); 3102 } 3103 3104 BitWidth = nullptr; 3105 Member->setInvalidDecl(); 3106 } 3107 3108 Member->setAccess(AS); 3109 3110 // If we have declared a member function template or static data member 3111 // template, set the access of the templated declaration as well. 3112 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3113 FunTmpl->getTemplatedDecl()->setAccess(AS); 3114 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3115 VarTmpl->getTemplatedDecl()->setAccess(AS); 3116 } 3117 3118 if (VS.isOverrideSpecified()) 3119 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3120 if (VS.isFinalSpecified()) 3121 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3122 VS.isFinalSpelledSealed())); 3123 3124 if (VS.getLastLocation().isValid()) { 3125 // Update the end location of a method that has a virt-specifiers. 3126 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3127 MD->setRangeEnd(VS.getLastLocation()); 3128 } 3129 3130 CheckOverrideControl(Member); 3131 3132 assert((Name || isInstField) && "No identifier for non-field ?"); 3133 3134 if (isInstField) { 3135 FieldDecl *FD = cast<FieldDecl>(Member); 3136 FieldCollector->Add(FD); 3137 3138 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3139 // Remember all explicit private FieldDecls that have a name, no side 3140 // effects and are not part of a dependent type declaration. 3141 if (!FD->isImplicit() && FD->getDeclName() && 3142 FD->getAccess() == AS_private && 3143 !FD->hasAttr<UnusedAttr>() && 3144 !FD->getParent()->isDependentContext() && 3145 !InitializationHasSideEffects(*FD)) 3146 UnusedPrivateFields.insert(FD); 3147 } 3148 } 3149 3150 return Member; 3151 } 3152 3153 namespace { 3154 class UninitializedFieldVisitor 3155 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3156 Sema &S; 3157 // List of Decls to generate a warning on. Also remove Decls that become 3158 // initialized. 3159 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3160 // List of base classes of the record. Classes are removed after their 3161 // initializers. 3162 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3163 // Vector of decls to be removed from the Decl set prior to visiting the 3164 // nodes. These Decls may have been initialized in the prior initializer. 3165 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3166 // If non-null, add a note to the warning pointing back to the constructor. 3167 const CXXConstructorDecl *Constructor; 3168 // Variables to hold state when processing an initializer list. When 3169 // InitList is true, special case initialization of FieldDecls matching 3170 // InitListFieldDecl. 3171 bool InitList; 3172 FieldDecl *InitListFieldDecl; 3173 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3174 3175 public: 3176 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3177 UninitializedFieldVisitor(Sema &S, 3178 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3179 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3180 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3181 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3182 3183 // Returns true if the use of ME is not an uninitialized use. 3184 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3185 bool CheckReferenceOnly) { 3186 llvm::SmallVector<FieldDecl*, 4> Fields; 3187 bool ReferenceField = false; 3188 while (ME) { 3189 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3190 if (!FD) 3191 return false; 3192 Fields.push_back(FD); 3193 if (FD->getType()->isReferenceType()) 3194 ReferenceField = true; 3195 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3196 } 3197 3198 // Binding a reference to an unintialized field is not an 3199 // uninitialized use. 3200 if (CheckReferenceOnly && !ReferenceField) 3201 return true; 3202 3203 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3204 // Discard the first field since it is the field decl that is being 3205 // initialized. 3206 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3207 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3208 } 3209 3210 for (auto UsedIter = UsedFieldIndex.begin(), 3211 UsedEnd = UsedFieldIndex.end(), 3212 OrigIter = InitFieldIndex.begin(), 3213 OrigEnd = InitFieldIndex.end(); 3214 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3215 if (*UsedIter < *OrigIter) 3216 return true; 3217 if (*UsedIter > *OrigIter) 3218 break; 3219 } 3220 3221 return false; 3222 } 3223 3224 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3225 bool AddressOf) { 3226 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3227 return; 3228 3229 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3230 // or union. 3231 MemberExpr *FieldME = ME; 3232 3233 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3234 3235 Expr *Base = ME; 3236 while (MemberExpr *SubME = 3237 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3238 3239 if (isa<VarDecl>(SubME->getMemberDecl())) 3240 return; 3241 3242 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3243 if (!FD->isAnonymousStructOrUnion()) 3244 FieldME = SubME; 3245 3246 if (!FieldME->getType().isPODType(S.Context)) 3247 AllPODFields = false; 3248 3249 Base = SubME->getBase(); 3250 } 3251 3252 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3253 return; 3254 3255 if (AddressOf && AllPODFields) 3256 return; 3257 3258 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3259 3260 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3261 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3262 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3263 } 3264 3265 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3266 QualType T = BaseCast->getType(); 3267 if (T->isPointerType() && 3268 BaseClasses.count(T->getPointeeType())) { 3269 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3270 << T->getPointeeType() << FoundVD; 3271 } 3272 } 3273 } 3274 3275 if (!Decls.count(FoundVD)) 3276 return; 3277 3278 const bool IsReference = FoundVD->getType()->isReferenceType(); 3279 3280 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3281 // Special checking for initializer lists. 3282 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3283 return; 3284 } 3285 } else { 3286 // Prevent double warnings on use of unbounded references. 3287 if (CheckReferenceOnly && !IsReference) 3288 return; 3289 } 3290 3291 unsigned diag = IsReference 3292 ? diag::warn_reference_field_is_uninit 3293 : diag::warn_field_is_uninit; 3294 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3295 if (Constructor) 3296 S.Diag(Constructor->getLocation(), 3297 diag::note_uninit_in_this_constructor) 3298 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3299 3300 } 3301 3302 void HandleValue(Expr *E, bool AddressOf) { 3303 E = E->IgnoreParens(); 3304 3305 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3306 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3307 AddressOf /*AddressOf*/); 3308 return; 3309 } 3310 3311 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3312 Visit(CO->getCond()); 3313 HandleValue(CO->getTrueExpr(), AddressOf); 3314 HandleValue(CO->getFalseExpr(), AddressOf); 3315 return; 3316 } 3317 3318 if (BinaryConditionalOperator *BCO = 3319 dyn_cast<BinaryConditionalOperator>(E)) { 3320 Visit(BCO->getCond()); 3321 HandleValue(BCO->getFalseExpr(), AddressOf); 3322 return; 3323 } 3324 3325 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3326 HandleValue(OVE->getSourceExpr(), AddressOf); 3327 return; 3328 } 3329 3330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3331 switch (BO->getOpcode()) { 3332 default: 3333 break; 3334 case(BO_PtrMemD): 3335 case(BO_PtrMemI): 3336 HandleValue(BO->getLHS(), AddressOf); 3337 Visit(BO->getRHS()); 3338 return; 3339 case(BO_Comma): 3340 Visit(BO->getLHS()); 3341 HandleValue(BO->getRHS(), AddressOf); 3342 return; 3343 } 3344 } 3345 3346 Visit(E); 3347 } 3348 3349 void CheckInitListExpr(InitListExpr *ILE) { 3350 InitFieldIndex.push_back(0); 3351 for (auto Child : ILE->children()) { 3352 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3353 CheckInitListExpr(SubList); 3354 } else { 3355 Visit(Child); 3356 } 3357 ++InitFieldIndex.back(); 3358 } 3359 InitFieldIndex.pop_back(); 3360 } 3361 3362 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3363 FieldDecl *Field, const Type *BaseClass) { 3364 // Remove Decls that may have been initialized in the previous 3365 // initializer. 3366 for (ValueDecl* VD : DeclsToRemove) 3367 Decls.erase(VD); 3368 DeclsToRemove.clear(); 3369 3370 Constructor = FieldConstructor; 3371 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3372 3373 if (ILE && Field) { 3374 InitList = true; 3375 InitListFieldDecl = Field; 3376 InitFieldIndex.clear(); 3377 CheckInitListExpr(ILE); 3378 } else { 3379 InitList = false; 3380 Visit(E); 3381 } 3382 3383 if (Field) 3384 Decls.erase(Field); 3385 if (BaseClass) 3386 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3387 } 3388 3389 void VisitMemberExpr(MemberExpr *ME) { 3390 // All uses of unbounded reference fields will warn. 3391 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3392 } 3393 3394 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3395 if (E->getCastKind() == CK_LValueToRValue) { 3396 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3397 return; 3398 } 3399 3400 Inherited::VisitImplicitCastExpr(E); 3401 } 3402 3403 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3404 if (E->getConstructor()->isCopyConstructor()) { 3405 Expr *ArgExpr = E->getArg(0); 3406 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3407 if (ILE->getNumInits() == 1) 3408 ArgExpr = ILE->getInit(0); 3409 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3410 if (ICE->getCastKind() == CK_NoOp) 3411 ArgExpr = ICE->getSubExpr(); 3412 HandleValue(ArgExpr, false /*AddressOf*/); 3413 return; 3414 } 3415 Inherited::VisitCXXConstructExpr(E); 3416 } 3417 3418 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3419 Expr *Callee = E->getCallee(); 3420 if (isa<MemberExpr>(Callee)) { 3421 HandleValue(Callee, false /*AddressOf*/); 3422 for (auto Arg : E->arguments()) 3423 Visit(Arg); 3424 return; 3425 } 3426 3427 Inherited::VisitCXXMemberCallExpr(E); 3428 } 3429 3430 void VisitCallExpr(CallExpr *E) { 3431 // Treat std::move as a use. 3432 if (E->isCallToStdMove()) { 3433 HandleValue(E->getArg(0), /*AddressOf=*/false); 3434 return; 3435 } 3436 3437 Inherited::VisitCallExpr(E); 3438 } 3439 3440 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3441 Expr *Callee = E->getCallee(); 3442 3443 if (isa<UnresolvedLookupExpr>(Callee)) 3444 return Inherited::VisitCXXOperatorCallExpr(E); 3445 3446 Visit(Callee); 3447 for (auto Arg : E->arguments()) 3448 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3449 } 3450 3451 void VisitBinaryOperator(BinaryOperator *E) { 3452 // If a field assignment is detected, remove the field from the 3453 // uninitiailized field set. 3454 if (E->getOpcode() == BO_Assign) 3455 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3456 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3457 if (!FD->getType()->isReferenceType()) 3458 DeclsToRemove.push_back(FD); 3459 3460 if (E->isCompoundAssignmentOp()) { 3461 HandleValue(E->getLHS(), false /*AddressOf*/); 3462 Visit(E->getRHS()); 3463 return; 3464 } 3465 3466 Inherited::VisitBinaryOperator(E); 3467 } 3468 3469 void VisitUnaryOperator(UnaryOperator *E) { 3470 if (E->isIncrementDecrementOp()) { 3471 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3472 return; 3473 } 3474 if (E->getOpcode() == UO_AddrOf) { 3475 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3476 HandleValue(ME->getBase(), true /*AddressOf*/); 3477 return; 3478 } 3479 } 3480 3481 Inherited::VisitUnaryOperator(E); 3482 } 3483 }; 3484 3485 // Diagnose value-uses of fields to initialize themselves, e.g. 3486 // foo(foo) 3487 // where foo is not also a parameter to the constructor. 3488 // Also diagnose across field uninitialized use such as 3489 // x(y), y(x) 3490 // TODO: implement -Wuninitialized and fold this into that framework. 3491 static void DiagnoseUninitializedFields( 3492 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3493 3494 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3495 Constructor->getLocation())) { 3496 return; 3497 } 3498 3499 if (Constructor->isInvalidDecl()) 3500 return; 3501 3502 const CXXRecordDecl *RD = Constructor->getParent(); 3503 3504 if (RD->getDescribedClassTemplate()) 3505 return; 3506 3507 // Holds fields that are uninitialized. 3508 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3509 3510 // At the beginning, all fields are uninitialized. 3511 for (auto *I : RD->decls()) { 3512 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3513 UninitializedFields.insert(FD); 3514 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3515 UninitializedFields.insert(IFD->getAnonField()); 3516 } 3517 } 3518 3519 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3520 for (auto I : RD->bases()) 3521 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3522 3523 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3524 return; 3525 3526 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3527 UninitializedFields, 3528 UninitializedBaseClasses); 3529 3530 for (const auto *FieldInit : Constructor->inits()) { 3531 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3532 break; 3533 3534 Expr *InitExpr = FieldInit->getInit(); 3535 if (!InitExpr) 3536 continue; 3537 3538 if (CXXDefaultInitExpr *Default = 3539 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3540 InitExpr = Default->getExpr(); 3541 if (!InitExpr) 3542 continue; 3543 // In class initializers will point to the constructor. 3544 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3545 FieldInit->getAnyMember(), 3546 FieldInit->getBaseClass()); 3547 } else { 3548 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3549 FieldInit->getAnyMember(), 3550 FieldInit->getBaseClass()); 3551 } 3552 } 3553 } 3554 } // namespace 3555 3556 /// \brief Enter a new C++ default initializer scope. After calling this, the 3557 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3558 /// parsing or instantiating the initializer failed. 3559 void Sema::ActOnStartCXXInClassMemberInitializer() { 3560 // Create a synthetic function scope to represent the call to the constructor 3561 // that notionally surrounds a use of this initializer. 3562 PushFunctionScope(); 3563 } 3564 3565 /// \brief This is invoked after parsing an in-class initializer for a 3566 /// non-static C++ class member, and after instantiating an in-class initializer 3567 /// in a class template. Such actions are deferred until the class is complete. 3568 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3569 SourceLocation InitLoc, 3570 Expr *InitExpr) { 3571 // Pop the notional constructor scope we created earlier. 3572 PopFunctionScopeInfo(nullptr, D); 3573 3574 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3575 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3576 "must set init style when field is created"); 3577 3578 if (!InitExpr) { 3579 D->setInvalidDecl(); 3580 if (FD) 3581 FD->removeInClassInitializer(); 3582 return; 3583 } 3584 3585 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3586 FD->setInvalidDecl(); 3587 FD->removeInClassInitializer(); 3588 return; 3589 } 3590 3591 ExprResult Init = InitExpr; 3592 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3593 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3594 InitializationKind Kind = 3595 FD->getInClassInitStyle() == ICIS_ListInit 3596 ? InitializationKind::CreateDirectList(InitExpr->getLocStart(), 3597 InitExpr->getLocStart(), 3598 InitExpr->getLocEnd()) 3599 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3600 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3601 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3602 if (Init.isInvalid()) { 3603 FD->setInvalidDecl(); 3604 return; 3605 } 3606 } 3607 3608 // C++11 [class.base.init]p7: 3609 // The initialization of each base and member constitutes a 3610 // full-expression. 3611 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3612 if (Init.isInvalid()) { 3613 FD->setInvalidDecl(); 3614 return; 3615 } 3616 3617 InitExpr = Init.get(); 3618 3619 FD->setInClassInitializer(InitExpr); 3620 } 3621 3622 /// \brief Find the direct and/or virtual base specifiers that 3623 /// correspond to the given base type, for use in base initialization 3624 /// within a constructor. 3625 static bool FindBaseInitializer(Sema &SemaRef, 3626 CXXRecordDecl *ClassDecl, 3627 QualType BaseType, 3628 const CXXBaseSpecifier *&DirectBaseSpec, 3629 const CXXBaseSpecifier *&VirtualBaseSpec) { 3630 // First, check for a direct base class. 3631 DirectBaseSpec = nullptr; 3632 for (const auto &Base : ClassDecl->bases()) { 3633 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3634 // We found a direct base of this type. That's what we're 3635 // initializing. 3636 DirectBaseSpec = &Base; 3637 break; 3638 } 3639 } 3640 3641 // Check for a virtual base class. 3642 // FIXME: We might be able to short-circuit this if we know in advance that 3643 // there are no virtual bases. 3644 VirtualBaseSpec = nullptr; 3645 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3646 // We haven't found a base yet; search the class hierarchy for a 3647 // virtual base class. 3648 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3649 /*DetectVirtual=*/false); 3650 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3651 SemaRef.Context.getTypeDeclType(ClassDecl), 3652 BaseType, Paths)) { 3653 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3654 Path != Paths.end(); ++Path) { 3655 if (Path->back().Base->isVirtual()) { 3656 VirtualBaseSpec = Path->back().Base; 3657 break; 3658 } 3659 } 3660 } 3661 } 3662 3663 return DirectBaseSpec || VirtualBaseSpec; 3664 } 3665 3666 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3667 MemInitResult 3668 Sema::ActOnMemInitializer(Decl *ConstructorD, 3669 Scope *S, 3670 CXXScopeSpec &SS, 3671 IdentifierInfo *MemberOrBase, 3672 ParsedType TemplateTypeTy, 3673 const DeclSpec &DS, 3674 SourceLocation IdLoc, 3675 Expr *InitList, 3676 SourceLocation EllipsisLoc) { 3677 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3678 DS, IdLoc, InitList, 3679 EllipsisLoc); 3680 } 3681 3682 /// \brief Handle a C++ member initializer using parentheses syntax. 3683 MemInitResult 3684 Sema::ActOnMemInitializer(Decl *ConstructorD, 3685 Scope *S, 3686 CXXScopeSpec &SS, 3687 IdentifierInfo *MemberOrBase, 3688 ParsedType TemplateTypeTy, 3689 const DeclSpec &DS, 3690 SourceLocation IdLoc, 3691 SourceLocation LParenLoc, 3692 ArrayRef<Expr *> Args, 3693 SourceLocation RParenLoc, 3694 SourceLocation EllipsisLoc) { 3695 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3696 Args, RParenLoc); 3697 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3698 DS, IdLoc, List, EllipsisLoc); 3699 } 3700 3701 namespace { 3702 3703 // Callback to only accept typo corrections that can be a valid C++ member 3704 // intializer: either a non-static field member or a base class. 3705 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3706 public: 3707 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3708 : ClassDecl(ClassDecl) {} 3709 3710 bool ValidateCandidate(const TypoCorrection &candidate) override { 3711 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3712 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3713 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3714 return isa<TypeDecl>(ND); 3715 } 3716 return false; 3717 } 3718 3719 private: 3720 CXXRecordDecl *ClassDecl; 3721 }; 3722 3723 } 3724 3725 /// \brief Handle a C++ member initializer. 3726 MemInitResult 3727 Sema::BuildMemInitializer(Decl *ConstructorD, 3728 Scope *S, 3729 CXXScopeSpec &SS, 3730 IdentifierInfo *MemberOrBase, 3731 ParsedType TemplateTypeTy, 3732 const DeclSpec &DS, 3733 SourceLocation IdLoc, 3734 Expr *Init, 3735 SourceLocation EllipsisLoc) { 3736 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3737 if (!Res.isUsable()) 3738 return true; 3739 Init = Res.get(); 3740 3741 if (!ConstructorD) 3742 return true; 3743 3744 AdjustDeclIfTemplate(ConstructorD); 3745 3746 CXXConstructorDecl *Constructor 3747 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3748 if (!Constructor) { 3749 // The user wrote a constructor initializer on a function that is 3750 // not a C++ constructor. Ignore the error for now, because we may 3751 // have more member initializers coming; we'll diagnose it just 3752 // once in ActOnMemInitializers. 3753 return true; 3754 } 3755 3756 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3757 3758 // C++ [class.base.init]p2: 3759 // Names in a mem-initializer-id are looked up in the scope of the 3760 // constructor's class and, if not found in that scope, are looked 3761 // up in the scope containing the constructor's definition. 3762 // [Note: if the constructor's class contains a member with the 3763 // same name as a direct or virtual base class of the class, a 3764 // mem-initializer-id naming the member or base class and composed 3765 // of a single identifier refers to the class member. A 3766 // mem-initializer-id for the hidden base class may be specified 3767 // using a qualified name. ] 3768 if (!SS.getScopeRep() && !TemplateTypeTy) { 3769 // Look for a member, first. 3770 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3771 if (!Result.empty()) { 3772 ValueDecl *Member; 3773 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3774 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3775 if (EllipsisLoc.isValid()) 3776 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3777 << MemberOrBase 3778 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3779 3780 return BuildMemberInitializer(Member, Init, IdLoc); 3781 } 3782 } 3783 } 3784 // It didn't name a member, so see if it names a class. 3785 QualType BaseType; 3786 TypeSourceInfo *TInfo = nullptr; 3787 3788 if (TemplateTypeTy) { 3789 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3790 } else if (DS.getTypeSpecType() == TST_decltype) { 3791 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3792 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3793 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3794 return true; 3795 } else { 3796 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3797 LookupParsedName(R, S, &SS); 3798 3799 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3800 if (!TyD) { 3801 if (R.isAmbiguous()) return true; 3802 3803 // We don't want access-control diagnostics here. 3804 R.suppressDiagnostics(); 3805 3806 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3807 bool NotUnknownSpecialization = false; 3808 DeclContext *DC = computeDeclContext(SS, false); 3809 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3810 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3811 3812 if (!NotUnknownSpecialization) { 3813 // When the scope specifier can refer to a member of an unknown 3814 // specialization, we take it as a type name. 3815 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3816 SS.getWithLocInContext(Context), 3817 *MemberOrBase, IdLoc); 3818 if (BaseType.isNull()) 3819 return true; 3820 3821 TInfo = Context.CreateTypeSourceInfo(BaseType); 3822 DependentNameTypeLoc TL = 3823 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3824 if (!TL.isNull()) { 3825 TL.setNameLoc(IdLoc); 3826 TL.setElaboratedKeywordLoc(SourceLocation()); 3827 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3828 } 3829 3830 R.clear(); 3831 R.setLookupName(MemberOrBase); 3832 } 3833 } 3834 3835 // If no results were found, try to correct typos. 3836 TypoCorrection Corr; 3837 if (R.empty() && BaseType.isNull() && 3838 (Corr = CorrectTypo( 3839 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3840 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3841 CTK_ErrorRecovery, ClassDecl))) { 3842 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3843 // We have found a non-static data member with a similar 3844 // name to what was typed; complain and initialize that 3845 // member. 3846 diagnoseTypo(Corr, 3847 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3848 << MemberOrBase << true); 3849 return BuildMemberInitializer(Member, Init, IdLoc); 3850 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3851 const CXXBaseSpecifier *DirectBaseSpec; 3852 const CXXBaseSpecifier *VirtualBaseSpec; 3853 if (FindBaseInitializer(*this, ClassDecl, 3854 Context.getTypeDeclType(Type), 3855 DirectBaseSpec, VirtualBaseSpec)) { 3856 // We have found a direct or virtual base class with a 3857 // similar name to what was typed; complain and initialize 3858 // that base class. 3859 diagnoseTypo(Corr, 3860 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3861 << MemberOrBase << false, 3862 PDiag() /*Suppress note, we provide our own.*/); 3863 3864 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3865 : VirtualBaseSpec; 3866 Diag(BaseSpec->getLocStart(), 3867 diag::note_base_class_specified_here) 3868 << BaseSpec->getType() 3869 << BaseSpec->getSourceRange(); 3870 3871 TyD = Type; 3872 } 3873 } 3874 } 3875 3876 if (!TyD && BaseType.isNull()) { 3877 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3878 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3879 return true; 3880 } 3881 } 3882 3883 if (BaseType.isNull()) { 3884 BaseType = Context.getTypeDeclType(TyD); 3885 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3886 if (SS.isSet()) { 3887 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3888 BaseType); 3889 TInfo = Context.CreateTypeSourceInfo(BaseType); 3890 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3891 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3892 TL.setElaboratedKeywordLoc(SourceLocation()); 3893 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3894 } 3895 } 3896 } 3897 3898 if (!TInfo) 3899 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3900 3901 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3902 } 3903 3904 /// Checks a member initializer expression for cases where reference (or 3905 /// pointer) members are bound to by-value parameters (or their addresses). 3906 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3907 Expr *Init, 3908 SourceLocation IdLoc) { 3909 QualType MemberTy = Member->getType(); 3910 3911 // We only handle pointers and references currently. 3912 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3913 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3914 return; 3915 3916 const bool IsPointer = MemberTy->isPointerType(); 3917 if (IsPointer) { 3918 if (const UnaryOperator *Op 3919 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3920 // The only case we're worried about with pointers requires taking the 3921 // address. 3922 if (Op->getOpcode() != UO_AddrOf) 3923 return; 3924 3925 Init = Op->getSubExpr(); 3926 } else { 3927 // We only handle address-of expression initializers for pointers. 3928 return; 3929 } 3930 } 3931 3932 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3933 // We only warn when referring to a non-reference parameter declaration. 3934 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3935 if (!Parameter || Parameter->getType()->isReferenceType()) 3936 return; 3937 3938 S.Diag(Init->getExprLoc(), 3939 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3940 : diag::warn_bind_ref_member_to_parameter) 3941 << Member << Parameter << Init->getSourceRange(); 3942 } else { 3943 // Other initializers are fine. 3944 return; 3945 } 3946 3947 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3948 << (unsigned)IsPointer; 3949 } 3950 3951 MemInitResult 3952 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3953 SourceLocation IdLoc) { 3954 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3955 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3956 assert((DirectMember || IndirectMember) && 3957 "Member must be a FieldDecl or IndirectFieldDecl"); 3958 3959 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3960 return true; 3961 3962 if (Member->isInvalidDecl()) 3963 return true; 3964 3965 MultiExprArg Args; 3966 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3967 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3968 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3969 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3970 } else { 3971 // Template instantiation doesn't reconstruct ParenListExprs for us. 3972 Args = Init; 3973 } 3974 3975 SourceRange InitRange = Init->getSourceRange(); 3976 3977 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3978 // Can't check initialization for a member of dependent type or when 3979 // any of the arguments are type-dependent expressions. 3980 DiscardCleanupsInEvaluationContext(); 3981 } else { 3982 bool InitList = false; 3983 if (isa<InitListExpr>(Init)) { 3984 InitList = true; 3985 Args = Init; 3986 } 3987 3988 // Initialize the member. 3989 InitializedEntity MemberEntity = 3990 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3991 : InitializedEntity::InitializeMember(IndirectMember, 3992 nullptr); 3993 InitializationKind Kind = 3994 InitList ? InitializationKind::CreateDirectList( 3995 IdLoc, Init->getLocStart(), Init->getLocEnd()) 3996 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3997 InitRange.getEnd()); 3998 3999 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4000 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4001 nullptr); 4002 if (MemberInit.isInvalid()) 4003 return true; 4004 4005 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 4006 4007 // C++11 [class.base.init]p7: 4008 // The initialization of each base and member constitutes a 4009 // full-expression. 4010 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 4011 if (MemberInit.isInvalid()) 4012 return true; 4013 4014 Init = MemberInit.get(); 4015 } 4016 4017 if (DirectMember) { 4018 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4019 InitRange.getBegin(), Init, 4020 InitRange.getEnd()); 4021 } else { 4022 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4023 InitRange.getBegin(), Init, 4024 InitRange.getEnd()); 4025 } 4026 } 4027 4028 MemInitResult 4029 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4030 CXXRecordDecl *ClassDecl) { 4031 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4032 if (!LangOpts.CPlusPlus11) 4033 return Diag(NameLoc, diag::err_delegating_ctor) 4034 << TInfo->getTypeLoc().getLocalSourceRange(); 4035 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4036 4037 bool InitList = true; 4038 MultiExprArg Args = Init; 4039 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4040 InitList = false; 4041 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4042 } 4043 4044 SourceRange InitRange = Init->getSourceRange(); 4045 // Initialize the object. 4046 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4047 QualType(ClassDecl->getTypeForDecl(), 0)); 4048 InitializationKind Kind = 4049 InitList ? InitializationKind::CreateDirectList( 4050 NameLoc, Init->getLocStart(), Init->getLocEnd()) 4051 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4052 InitRange.getEnd()); 4053 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4054 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4055 Args, nullptr); 4056 if (DelegationInit.isInvalid()) 4057 return true; 4058 4059 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4060 "Delegating constructor with no target?"); 4061 4062 // C++11 [class.base.init]p7: 4063 // The initialization of each base and member constitutes a 4064 // full-expression. 4065 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4066 InitRange.getBegin()); 4067 if (DelegationInit.isInvalid()) 4068 return true; 4069 4070 // If we are in a dependent context, template instantiation will 4071 // perform this type-checking again. Just save the arguments that we 4072 // received in a ParenListExpr. 4073 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4074 // of the information that we have about the base 4075 // initializer. However, deconstructing the ASTs is a dicey process, 4076 // and this approach is far more likely to get the corner cases right. 4077 if (CurContext->isDependentContext()) 4078 DelegationInit = Init; 4079 4080 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4081 DelegationInit.getAs<Expr>(), 4082 InitRange.getEnd()); 4083 } 4084 4085 MemInitResult 4086 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4087 Expr *Init, CXXRecordDecl *ClassDecl, 4088 SourceLocation EllipsisLoc) { 4089 SourceLocation BaseLoc 4090 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4091 4092 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4093 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4094 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4095 4096 // C++ [class.base.init]p2: 4097 // [...] Unless the mem-initializer-id names a nonstatic data 4098 // member of the constructor's class or a direct or virtual base 4099 // of that class, the mem-initializer is ill-formed. A 4100 // mem-initializer-list can initialize a base class using any 4101 // name that denotes that base class type. 4102 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4103 4104 SourceRange InitRange = Init->getSourceRange(); 4105 if (EllipsisLoc.isValid()) { 4106 // This is a pack expansion. 4107 if (!BaseType->containsUnexpandedParameterPack()) { 4108 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4109 << SourceRange(BaseLoc, InitRange.getEnd()); 4110 4111 EllipsisLoc = SourceLocation(); 4112 } 4113 } else { 4114 // Check for any unexpanded parameter packs. 4115 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4116 return true; 4117 4118 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4119 return true; 4120 } 4121 4122 // Check for direct and virtual base classes. 4123 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4124 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4125 if (!Dependent) { 4126 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4127 BaseType)) 4128 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4129 4130 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4131 VirtualBaseSpec); 4132 4133 // C++ [base.class.init]p2: 4134 // Unless the mem-initializer-id names a nonstatic data member of the 4135 // constructor's class or a direct or virtual base of that class, the 4136 // mem-initializer is ill-formed. 4137 if (!DirectBaseSpec && !VirtualBaseSpec) { 4138 // If the class has any dependent bases, then it's possible that 4139 // one of those types will resolve to the same type as 4140 // BaseType. Therefore, just treat this as a dependent base 4141 // class initialization. FIXME: Should we try to check the 4142 // initialization anyway? It seems odd. 4143 if (ClassDecl->hasAnyDependentBases()) 4144 Dependent = true; 4145 else 4146 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4147 << BaseType << Context.getTypeDeclType(ClassDecl) 4148 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4149 } 4150 } 4151 4152 if (Dependent) { 4153 DiscardCleanupsInEvaluationContext(); 4154 4155 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4156 /*IsVirtual=*/false, 4157 InitRange.getBegin(), Init, 4158 InitRange.getEnd(), EllipsisLoc); 4159 } 4160 4161 // C++ [base.class.init]p2: 4162 // If a mem-initializer-id is ambiguous because it designates both 4163 // a direct non-virtual base class and an inherited virtual base 4164 // class, the mem-initializer is ill-formed. 4165 if (DirectBaseSpec && VirtualBaseSpec) 4166 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4167 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4168 4169 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4170 if (!BaseSpec) 4171 BaseSpec = VirtualBaseSpec; 4172 4173 // Initialize the base. 4174 bool InitList = true; 4175 MultiExprArg Args = Init; 4176 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4177 InitList = false; 4178 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4179 } 4180 4181 InitializedEntity BaseEntity = 4182 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4183 InitializationKind Kind = 4184 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4185 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4186 InitRange.getEnd()); 4187 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4188 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4189 if (BaseInit.isInvalid()) 4190 return true; 4191 4192 // C++11 [class.base.init]p7: 4193 // The initialization of each base and member constitutes a 4194 // full-expression. 4195 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4196 if (BaseInit.isInvalid()) 4197 return true; 4198 4199 // If we are in a dependent context, template instantiation will 4200 // perform this type-checking again. Just save the arguments that we 4201 // received in a ParenListExpr. 4202 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4203 // of the information that we have about the base 4204 // initializer. However, deconstructing the ASTs is a dicey process, 4205 // and this approach is far more likely to get the corner cases right. 4206 if (CurContext->isDependentContext()) 4207 BaseInit = Init; 4208 4209 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4210 BaseSpec->isVirtual(), 4211 InitRange.getBegin(), 4212 BaseInit.getAs<Expr>(), 4213 InitRange.getEnd(), EllipsisLoc); 4214 } 4215 4216 // Create a static_cast\<T&&>(expr). 4217 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4218 if (T.isNull()) T = E->getType(); 4219 QualType TargetType = SemaRef.BuildReferenceType( 4220 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4221 SourceLocation ExprLoc = E->getLocStart(); 4222 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4223 TargetType, ExprLoc); 4224 4225 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4226 SourceRange(ExprLoc, ExprLoc), 4227 E->getSourceRange()).get(); 4228 } 4229 4230 /// ImplicitInitializerKind - How an implicit base or member initializer should 4231 /// initialize its base or member. 4232 enum ImplicitInitializerKind { 4233 IIK_Default, 4234 IIK_Copy, 4235 IIK_Move, 4236 IIK_Inherit 4237 }; 4238 4239 static bool 4240 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4241 ImplicitInitializerKind ImplicitInitKind, 4242 CXXBaseSpecifier *BaseSpec, 4243 bool IsInheritedVirtualBase, 4244 CXXCtorInitializer *&CXXBaseInit) { 4245 InitializedEntity InitEntity 4246 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4247 IsInheritedVirtualBase); 4248 4249 ExprResult BaseInit; 4250 4251 switch (ImplicitInitKind) { 4252 case IIK_Inherit: 4253 case IIK_Default: { 4254 InitializationKind InitKind 4255 = InitializationKind::CreateDefault(Constructor->getLocation()); 4256 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4257 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4258 break; 4259 } 4260 4261 case IIK_Move: 4262 case IIK_Copy: { 4263 bool Moving = ImplicitInitKind == IIK_Move; 4264 ParmVarDecl *Param = Constructor->getParamDecl(0); 4265 QualType ParamType = Param->getType().getNonReferenceType(); 4266 4267 Expr *CopyCtorArg = 4268 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4269 SourceLocation(), Param, false, 4270 Constructor->getLocation(), ParamType, 4271 VK_LValue, nullptr); 4272 4273 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4274 4275 // Cast to the base class to avoid ambiguities. 4276 QualType ArgTy = 4277 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4278 ParamType.getQualifiers()); 4279 4280 if (Moving) { 4281 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4282 } 4283 4284 CXXCastPath BasePath; 4285 BasePath.push_back(BaseSpec); 4286 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4287 CK_UncheckedDerivedToBase, 4288 Moving ? VK_XValue : VK_LValue, 4289 &BasePath).get(); 4290 4291 InitializationKind InitKind 4292 = InitializationKind::CreateDirect(Constructor->getLocation(), 4293 SourceLocation(), SourceLocation()); 4294 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4295 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4296 break; 4297 } 4298 } 4299 4300 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4301 if (BaseInit.isInvalid()) 4302 return true; 4303 4304 CXXBaseInit = 4305 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4306 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4307 SourceLocation()), 4308 BaseSpec->isVirtual(), 4309 SourceLocation(), 4310 BaseInit.getAs<Expr>(), 4311 SourceLocation(), 4312 SourceLocation()); 4313 4314 return false; 4315 } 4316 4317 static bool RefersToRValueRef(Expr *MemRef) { 4318 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4319 return Referenced->getType()->isRValueReferenceType(); 4320 } 4321 4322 static bool 4323 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4324 ImplicitInitializerKind ImplicitInitKind, 4325 FieldDecl *Field, IndirectFieldDecl *Indirect, 4326 CXXCtorInitializer *&CXXMemberInit) { 4327 if (Field->isInvalidDecl()) 4328 return true; 4329 4330 SourceLocation Loc = Constructor->getLocation(); 4331 4332 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4333 bool Moving = ImplicitInitKind == IIK_Move; 4334 ParmVarDecl *Param = Constructor->getParamDecl(0); 4335 QualType ParamType = Param->getType().getNonReferenceType(); 4336 4337 // Suppress copying zero-width bitfields. 4338 if (Field->isZeroLengthBitField(SemaRef.Context)) 4339 return false; 4340 4341 Expr *MemberExprBase = 4342 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4343 SourceLocation(), Param, false, 4344 Loc, ParamType, VK_LValue, nullptr); 4345 4346 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4347 4348 if (Moving) { 4349 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4350 } 4351 4352 // Build a reference to this field within the parameter. 4353 CXXScopeSpec SS; 4354 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4355 Sema::LookupMemberName); 4356 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4357 : cast<ValueDecl>(Field), AS_public); 4358 MemberLookup.resolveKind(); 4359 ExprResult CtorArg 4360 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4361 ParamType, Loc, 4362 /*IsArrow=*/false, 4363 SS, 4364 /*TemplateKWLoc=*/SourceLocation(), 4365 /*FirstQualifierInScope=*/nullptr, 4366 MemberLookup, 4367 /*TemplateArgs=*/nullptr, 4368 /*S*/nullptr); 4369 if (CtorArg.isInvalid()) 4370 return true; 4371 4372 // C++11 [class.copy]p15: 4373 // - if a member m has rvalue reference type T&&, it is direct-initialized 4374 // with static_cast<T&&>(x.m); 4375 if (RefersToRValueRef(CtorArg.get())) { 4376 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4377 } 4378 4379 InitializedEntity Entity = 4380 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4381 /*Implicit*/ true) 4382 : InitializedEntity::InitializeMember(Field, nullptr, 4383 /*Implicit*/ true); 4384 4385 // Direct-initialize to use the copy constructor. 4386 InitializationKind InitKind = 4387 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4388 4389 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4390 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4391 ExprResult MemberInit = 4392 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4393 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4394 if (MemberInit.isInvalid()) 4395 return true; 4396 4397 if (Indirect) 4398 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4399 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4400 else 4401 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4402 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4403 return false; 4404 } 4405 4406 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4407 "Unhandled implicit init kind!"); 4408 4409 QualType FieldBaseElementType = 4410 SemaRef.Context.getBaseElementType(Field->getType()); 4411 4412 if (FieldBaseElementType->isRecordType()) { 4413 InitializedEntity InitEntity = 4414 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4415 /*Implicit*/ true) 4416 : InitializedEntity::InitializeMember(Field, nullptr, 4417 /*Implicit*/ true); 4418 InitializationKind InitKind = 4419 InitializationKind::CreateDefault(Loc); 4420 4421 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4422 ExprResult MemberInit = 4423 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4424 4425 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4426 if (MemberInit.isInvalid()) 4427 return true; 4428 4429 if (Indirect) 4430 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4431 Indirect, Loc, 4432 Loc, 4433 MemberInit.get(), 4434 Loc); 4435 else 4436 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4437 Field, Loc, Loc, 4438 MemberInit.get(), 4439 Loc); 4440 return false; 4441 } 4442 4443 if (!Field->getParent()->isUnion()) { 4444 if (FieldBaseElementType->isReferenceType()) { 4445 SemaRef.Diag(Constructor->getLocation(), 4446 diag::err_uninitialized_member_in_ctor) 4447 << (int)Constructor->isImplicit() 4448 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4449 << 0 << Field->getDeclName(); 4450 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4451 return true; 4452 } 4453 4454 if (FieldBaseElementType.isConstQualified()) { 4455 SemaRef.Diag(Constructor->getLocation(), 4456 diag::err_uninitialized_member_in_ctor) 4457 << (int)Constructor->isImplicit() 4458 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4459 << 1 << Field->getDeclName(); 4460 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4461 return true; 4462 } 4463 } 4464 4465 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4466 // ARC and Weak: 4467 // Default-initialize Objective-C pointers to NULL. 4468 CXXMemberInit 4469 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4470 Loc, Loc, 4471 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4472 Loc); 4473 return false; 4474 } 4475 4476 // Nothing to initialize. 4477 CXXMemberInit = nullptr; 4478 return false; 4479 } 4480 4481 namespace { 4482 struct BaseAndFieldInfo { 4483 Sema &S; 4484 CXXConstructorDecl *Ctor; 4485 bool AnyErrorsInInits; 4486 ImplicitInitializerKind IIK; 4487 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4488 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4489 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4490 4491 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4492 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4493 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4494 if (Ctor->getInheritedConstructor()) 4495 IIK = IIK_Inherit; 4496 else if (Generated && Ctor->isCopyConstructor()) 4497 IIK = IIK_Copy; 4498 else if (Generated && Ctor->isMoveConstructor()) 4499 IIK = IIK_Move; 4500 else 4501 IIK = IIK_Default; 4502 } 4503 4504 bool isImplicitCopyOrMove() const { 4505 switch (IIK) { 4506 case IIK_Copy: 4507 case IIK_Move: 4508 return true; 4509 4510 case IIK_Default: 4511 case IIK_Inherit: 4512 return false; 4513 } 4514 4515 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4516 } 4517 4518 bool addFieldInitializer(CXXCtorInitializer *Init) { 4519 AllToInit.push_back(Init); 4520 4521 // Check whether this initializer makes the field "used". 4522 if (Init->getInit()->HasSideEffects(S.Context)) 4523 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4524 4525 return false; 4526 } 4527 4528 bool isInactiveUnionMember(FieldDecl *Field) { 4529 RecordDecl *Record = Field->getParent(); 4530 if (!Record->isUnion()) 4531 return false; 4532 4533 if (FieldDecl *Active = 4534 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4535 return Active != Field->getCanonicalDecl(); 4536 4537 // In an implicit copy or move constructor, ignore any in-class initializer. 4538 if (isImplicitCopyOrMove()) 4539 return true; 4540 4541 // If there's no explicit initialization, the field is active only if it 4542 // has an in-class initializer... 4543 if (Field->hasInClassInitializer()) 4544 return false; 4545 // ... or it's an anonymous struct or union whose class has an in-class 4546 // initializer. 4547 if (!Field->isAnonymousStructOrUnion()) 4548 return true; 4549 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4550 return !FieldRD->hasInClassInitializer(); 4551 } 4552 4553 /// \brief Determine whether the given field is, or is within, a union member 4554 /// that is inactive (because there was an initializer given for a different 4555 /// member of the union, or because the union was not initialized at all). 4556 bool isWithinInactiveUnionMember(FieldDecl *Field, 4557 IndirectFieldDecl *Indirect) { 4558 if (!Indirect) 4559 return isInactiveUnionMember(Field); 4560 4561 for (auto *C : Indirect->chain()) { 4562 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4563 if (Field && isInactiveUnionMember(Field)) 4564 return true; 4565 } 4566 return false; 4567 } 4568 }; 4569 } 4570 4571 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4572 /// array type. 4573 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4574 if (T->isIncompleteArrayType()) 4575 return true; 4576 4577 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4578 if (!ArrayT->getSize()) 4579 return true; 4580 4581 T = ArrayT->getElementType(); 4582 } 4583 4584 return false; 4585 } 4586 4587 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4588 FieldDecl *Field, 4589 IndirectFieldDecl *Indirect = nullptr) { 4590 if (Field->isInvalidDecl()) 4591 return false; 4592 4593 // Overwhelmingly common case: we have a direct initializer for this field. 4594 if (CXXCtorInitializer *Init = 4595 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4596 return Info.addFieldInitializer(Init); 4597 4598 // C++11 [class.base.init]p8: 4599 // if the entity is a non-static data member that has a 4600 // brace-or-equal-initializer and either 4601 // -- the constructor's class is a union and no other variant member of that 4602 // union is designated by a mem-initializer-id or 4603 // -- the constructor's class is not a union, and, if the entity is a member 4604 // of an anonymous union, no other member of that union is designated by 4605 // a mem-initializer-id, 4606 // the entity is initialized as specified in [dcl.init]. 4607 // 4608 // We also apply the same rules to handle anonymous structs within anonymous 4609 // unions. 4610 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4611 return false; 4612 4613 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4614 ExprResult DIE = 4615 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4616 if (DIE.isInvalid()) 4617 return true; 4618 CXXCtorInitializer *Init; 4619 if (Indirect) 4620 Init = new (SemaRef.Context) 4621 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4622 SourceLocation(), DIE.get(), SourceLocation()); 4623 else 4624 Init = new (SemaRef.Context) 4625 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4626 SourceLocation(), DIE.get(), SourceLocation()); 4627 return Info.addFieldInitializer(Init); 4628 } 4629 4630 // Don't initialize incomplete or zero-length arrays. 4631 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4632 return false; 4633 4634 // Don't try to build an implicit initializer if there were semantic 4635 // errors in any of the initializers (and therefore we might be 4636 // missing some that the user actually wrote). 4637 if (Info.AnyErrorsInInits) 4638 return false; 4639 4640 CXXCtorInitializer *Init = nullptr; 4641 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4642 Indirect, Init)) 4643 return true; 4644 4645 if (!Init) 4646 return false; 4647 4648 return Info.addFieldInitializer(Init); 4649 } 4650 4651 bool 4652 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4653 CXXCtorInitializer *Initializer) { 4654 assert(Initializer->isDelegatingInitializer()); 4655 Constructor->setNumCtorInitializers(1); 4656 CXXCtorInitializer **initializer = 4657 new (Context) CXXCtorInitializer*[1]; 4658 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4659 Constructor->setCtorInitializers(initializer); 4660 4661 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4662 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4663 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4664 } 4665 4666 DelegatingCtorDecls.push_back(Constructor); 4667 4668 DiagnoseUninitializedFields(*this, Constructor); 4669 4670 return false; 4671 } 4672 4673 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4674 ArrayRef<CXXCtorInitializer *> Initializers) { 4675 if (Constructor->isDependentContext()) { 4676 // Just store the initializers as written, they will be checked during 4677 // instantiation. 4678 if (!Initializers.empty()) { 4679 Constructor->setNumCtorInitializers(Initializers.size()); 4680 CXXCtorInitializer **baseOrMemberInitializers = 4681 new (Context) CXXCtorInitializer*[Initializers.size()]; 4682 memcpy(baseOrMemberInitializers, Initializers.data(), 4683 Initializers.size() * sizeof(CXXCtorInitializer*)); 4684 Constructor->setCtorInitializers(baseOrMemberInitializers); 4685 } 4686 4687 // Let template instantiation know whether we had errors. 4688 if (AnyErrors) 4689 Constructor->setInvalidDecl(); 4690 4691 return false; 4692 } 4693 4694 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4695 4696 // We need to build the initializer AST according to order of construction 4697 // and not what user specified in the Initializers list. 4698 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4699 if (!ClassDecl) 4700 return true; 4701 4702 bool HadError = false; 4703 4704 for (unsigned i = 0; i < Initializers.size(); i++) { 4705 CXXCtorInitializer *Member = Initializers[i]; 4706 4707 if (Member->isBaseInitializer()) 4708 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4709 else { 4710 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4711 4712 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4713 for (auto *C : F->chain()) { 4714 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4715 if (FD && FD->getParent()->isUnion()) 4716 Info.ActiveUnionMember.insert(std::make_pair( 4717 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4718 } 4719 } else if (FieldDecl *FD = Member->getMember()) { 4720 if (FD->getParent()->isUnion()) 4721 Info.ActiveUnionMember.insert(std::make_pair( 4722 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4723 } 4724 } 4725 } 4726 4727 // Keep track of the direct virtual bases. 4728 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4729 for (auto &I : ClassDecl->bases()) { 4730 if (I.isVirtual()) 4731 DirectVBases.insert(&I); 4732 } 4733 4734 // Push virtual bases before others. 4735 for (auto &VBase : ClassDecl->vbases()) { 4736 if (CXXCtorInitializer *Value 4737 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4738 // [class.base.init]p7, per DR257: 4739 // A mem-initializer where the mem-initializer-id names a virtual base 4740 // class is ignored during execution of a constructor of any class that 4741 // is not the most derived class. 4742 if (ClassDecl->isAbstract()) { 4743 // FIXME: Provide a fixit to remove the base specifier. This requires 4744 // tracking the location of the associated comma for a base specifier. 4745 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4746 << VBase.getType() << ClassDecl; 4747 DiagnoseAbstractType(ClassDecl); 4748 } 4749 4750 Info.AllToInit.push_back(Value); 4751 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4752 // [class.base.init]p8, per DR257: 4753 // If a given [...] base class is not named by a mem-initializer-id 4754 // [...] and the entity is not a virtual base class of an abstract 4755 // class, then [...] the entity is default-initialized. 4756 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4757 CXXCtorInitializer *CXXBaseInit; 4758 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4759 &VBase, IsInheritedVirtualBase, 4760 CXXBaseInit)) { 4761 HadError = true; 4762 continue; 4763 } 4764 4765 Info.AllToInit.push_back(CXXBaseInit); 4766 } 4767 } 4768 4769 // Non-virtual bases. 4770 for (auto &Base : ClassDecl->bases()) { 4771 // Virtuals are in the virtual base list and already constructed. 4772 if (Base.isVirtual()) 4773 continue; 4774 4775 if (CXXCtorInitializer *Value 4776 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4777 Info.AllToInit.push_back(Value); 4778 } else if (!AnyErrors) { 4779 CXXCtorInitializer *CXXBaseInit; 4780 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4781 &Base, /*IsInheritedVirtualBase=*/false, 4782 CXXBaseInit)) { 4783 HadError = true; 4784 continue; 4785 } 4786 4787 Info.AllToInit.push_back(CXXBaseInit); 4788 } 4789 } 4790 4791 // Fields. 4792 for (auto *Mem : ClassDecl->decls()) { 4793 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4794 // C++ [class.bit]p2: 4795 // A declaration for a bit-field that omits the identifier declares an 4796 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4797 // initialized. 4798 if (F->isUnnamedBitfield()) 4799 continue; 4800 4801 // If we're not generating the implicit copy/move constructor, then we'll 4802 // handle anonymous struct/union fields based on their individual 4803 // indirect fields. 4804 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4805 continue; 4806 4807 if (CollectFieldInitializer(*this, Info, F)) 4808 HadError = true; 4809 continue; 4810 } 4811 4812 // Beyond this point, we only consider default initialization. 4813 if (Info.isImplicitCopyOrMove()) 4814 continue; 4815 4816 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4817 if (F->getType()->isIncompleteArrayType()) { 4818 assert(ClassDecl->hasFlexibleArrayMember() && 4819 "Incomplete array type is not valid"); 4820 continue; 4821 } 4822 4823 // Initialize each field of an anonymous struct individually. 4824 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4825 HadError = true; 4826 4827 continue; 4828 } 4829 } 4830 4831 unsigned NumInitializers = Info.AllToInit.size(); 4832 if (NumInitializers > 0) { 4833 Constructor->setNumCtorInitializers(NumInitializers); 4834 CXXCtorInitializer **baseOrMemberInitializers = 4835 new (Context) CXXCtorInitializer*[NumInitializers]; 4836 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4837 NumInitializers * sizeof(CXXCtorInitializer*)); 4838 Constructor->setCtorInitializers(baseOrMemberInitializers); 4839 4840 // Constructors implicitly reference the base and member 4841 // destructors. 4842 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4843 Constructor->getParent()); 4844 } 4845 4846 return HadError; 4847 } 4848 4849 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4850 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4851 const RecordDecl *RD = RT->getDecl(); 4852 if (RD->isAnonymousStructOrUnion()) { 4853 for (auto *Field : RD->fields()) 4854 PopulateKeysForFields(Field, IdealInits); 4855 return; 4856 } 4857 } 4858 IdealInits.push_back(Field->getCanonicalDecl()); 4859 } 4860 4861 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4862 return Context.getCanonicalType(BaseType).getTypePtr(); 4863 } 4864 4865 static const void *GetKeyForMember(ASTContext &Context, 4866 CXXCtorInitializer *Member) { 4867 if (!Member->isAnyMemberInitializer()) 4868 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4869 4870 return Member->getAnyMember()->getCanonicalDecl(); 4871 } 4872 4873 static void DiagnoseBaseOrMemInitializerOrder( 4874 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4875 ArrayRef<CXXCtorInitializer *> Inits) { 4876 if (Constructor->getDeclContext()->isDependentContext()) 4877 return; 4878 4879 // Don't check initializers order unless the warning is enabled at the 4880 // location of at least one initializer. 4881 bool ShouldCheckOrder = false; 4882 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4883 CXXCtorInitializer *Init = Inits[InitIndex]; 4884 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4885 Init->getSourceLocation())) { 4886 ShouldCheckOrder = true; 4887 break; 4888 } 4889 } 4890 if (!ShouldCheckOrder) 4891 return; 4892 4893 // Build the list of bases and members in the order that they'll 4894 // actually be initialized. The explicit initializers should be in 4895 // this same order but may be missing things. 4896 SmallVector<const void*, 32> IdealInitKeys; 4897 4898 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4899 4900 // 1. Virtual bases. 4901 for (const auto &VBase : ClassDecl->vbases()) 4902 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4903 4904 // 2. Non-virtual bases. 4905 for (const auto &Base : ClassDecl->bases()) { 4906 if (Base.isVirtual()) 4907 continue; 4908 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4909 } 4910 4911 // 3. Direct fields. 4912 for (auto *Field : ClassDecl->fields()) { 4913 if (Field->isUnnamedBitfield()) 4914 continue; 4915 4916 PopulateKeysForFields(Field, IdealInitKeys); 4917 } 4918 4919 unsigned NumIdealInits = IdealInitKeys.size(); 4920 unsigned IdealIndex = 0; 4921 4922 CXXCtorInitializer *PrevInit = nullptr; 4923 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4924 CXXCtorInitializer *Init = Inits[InitIndex]; 4925 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4926 4927 // Scan forward to try to find this initializer in the idealized 4928 // initializers list. 4929 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4930 if (InitKey == IdealInitKeys[IdealIndex]) 4931 break; 4932 4933 // If we didn't find this initializer, it must be because we 4934 // scanned past it on a previous iteration. That can only 4935 // happen if we're out of order; emit a warning. 4936 if (IdealIndex == NumIdealInits && PrevInit) { 4937 Sema::SemaDiagnosticBuilder D = 4938 SemaRef.Diag(PrevInit->getSourceLocation(), 4939 diag::warn_initializer_out_of_order); 4940 4941 if (PrevInit->isAnyMemberInitializer()) 4942 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4943 else 4944 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4945 4946 if (Init->isAnyMemberInitializer()) 4947 D << 0 << Init->getAnyMember()->getDeclName(); 4948 else 4949 D << 1 << Init->getTypeSourceInfo()->getType(); 4950 4951 // Move back to the initializer's location in the ideal list. 4952 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4953 if (InitKey == IdealInitKeys[IdealIndex]) 4954 break; 4955 4956 assert(IdealIndex < NumIdealInits && 4957 "initializer not found in initializer list"); 4958 } 4959 4960 PrevInit = Init; 4961 } 4962 } 4963 4964 namespace { 4965 bool CheckRedundantInit(Sema &S, 4966 CXXCtorInitializer *Init, 4967 CXXCtorInitializer *&PrevInit) { 4968 if (!PrevInit) { 4969 PrevInit = Init; 4970 return false; 4971 } 4972 4973 if (FieldDecl *Field = Init->getAnyMember()) 4974 S.Diag(Init->getSourceLocation(), 4975 diag::err_multiple_mem_initialization) 4976 << Field->getDeclName() 4977 << Init->getSourceRange(); 4978 else { 4979 const Type *BaseClass = Init->getBaseClass(); 4980 assert(BaseClass && "neither field nor base"); 4981 S.Diag(Init->getSourceLocation(), 4982 diag::err_multiple_base_initialization) 4983 << QualType(BaseClass, 0) 4984 << Init->getSourceRange(); 4985 } 4986 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4987 << 0 << PrevInit->getSourceRange(); 4988 4989 return true; 4990 } 4991 4992 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4993 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4994 4995 bool CheckRedundantUnionInit(Sema &S, 4996 CXXCtorInitializer *Init, 4997 RedundantUnionMap &Unions) { 4998 FieldDecl *Field = Init->getAnyMember(); 4999 RecordDecl *Parent = Field->getParent(); 5000 NamedDecl *Child = Field; 5001 5002 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5003 if (Parent->isUnion()) { 5004 UnionEntry &En = Unions[Parent]; 5005 if (En.first && En.first != Child) { 5006 S.Diag(Init->getSourceLocation(), 5007 diag::err_multiple_mem_union_initialization) 5008 << Field->getDeclName() 5009 << Init->getSourceRange(); 5010 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5011 << 0 << En.second->getSourceRange(); 5012 return true; 5013 } 5014 if (!En.first) { 5015 En.first = Child; 5016 En.second = Init; 5017 } 5018 if (!Parent->isAnonymousStructOrUnion()) 5019 return false; 5020 } 5021 5022 Child = Parent; 5023 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5024 } 5025 5026 return false; 5027 } 5028 } 5029 5030 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5031 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5032 SourceLocation ColonLoc, 5033 ArrayRef<CXXCtorInitializer*> MemInits, 5034 bool AnyErrors) { 5035 if (!ConstructorDecl) 5036 return; 5037 5038 AdjustDeclIfTemplate(ConstructorDecl); 5039 5040 CXXConstructorDecl *Constructor 5041 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5042 5043 if (!Constructor) { 5044 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5045 return; 5046 } 5047 5048 // Mapping for the duplicate initializers check. 5049 // For member initializers, this is keyed with a FieldDecl*. 5050 // For base initializers, this is keyed with a Type*. 5051 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5052 5053 // Mapping for the inconsistent anonymous-union initializers check. 5054 RedundantUnionMap MemberUnions; 5055 5056 bool HadError = false; 5057 for (unsigned i = 0; i < MemInits.size(); i++) { 5058 CXXCtorInitializer *Init = MemInits[i]; 5059 5060 // Set the source order index. 5061 Init->setSourceOrder(i); 5062 5063 if (Init->isAnyMemberInitializer()) { 5064 const void *Key = GetKeyForMember(Context, Init); 5065 if (CheckRedundantInit(*this, Init, Members[Key]) || 5066 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5067 HadError = true; 5068 } else if (Init->isBaseInitializer()) { 5069 const void *Key = GetKeyForMember(Context, Init); 5070 if (CheckRedundantInit(*this, Init, Members[Key])) 5071 HadError = true; 5072 } else { 5073 assert(Init->isDelegatingInitializer()); 5074 // This must be the only initializer 5075 if (MemInits.size() != 1) { 5076 Diag(Init->getSourceLocation(), 5077 diag::err_delegating_initializer_alone) 5078 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5079 // We will treat this as being the only initializer. 5080 } 5081 SetDelegatingInitializer(Constructor, MemInits[i]); 5082 // Return immediately as the initializer is set. 5083 return; 5084 } 5085 } 5086 5087 if (HadError) 5088 return; 5089 5090 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5091 5092 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5093 5094 DiagnoseUninitializedFields(*this, Constructor); 5095 } 5096 5097 void 5098 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5099 CXXRecordDecl *ClassDecl) { 5100 // Ignore dependent contexts. Also ignore unions, since their members never 5101 // have destructors implicitly called. 5102 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5103 return; 5104 5105 // FIXME: all the access-control diagnostics are positioned on the 5106 // field/base declaration. That's probably good; that said, the 5107 // user might reasonably want to know why the destructor is being 5108 // emitted, and we currently don't say. 5109 5110 // Non-static data members. 5111 for (auto *Field : ClassDecl->fields()) { 5112 if (Field->isInvalidDecl()) 5113 continue; 5114 5115 // Don't destroy incomplete or zero-length arrays. 5116 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5117 continue; 5118 5119 QualType FieldType = Context.getBaseElementType(Field->getType()); 5120 5121 const RecordType* RT = FieldType->getAs<RecordType>(); 5122 if (!RT) 5123 continue; 5124 5125 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5126 if (FieldClassDecl->isInvalidDecl()) 5127 continue; 5128 if (FieldClassDecl->hasIrrelevantDestructor()) 5129 continue; 5130 // The destructor for an implicit anonymous union member is never invoked. 5131 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5132 continue; 5133 5134 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5135 assert(Dtor && "No dtor found for FieldClassDecl!"); 5136 CheckDestructorAccess(Field->getLocation(), Dtor, 5137 PDiag(diag::err_access_dtor_field) 5138 << Field->getDeclName() 5139 << FieldType); 5140 5141 MarkFunctionReferenced(Location, Dtor); 5142 DiagnoseUseOfDecl(Dtor, Location); 5143 } 5144 5145 // We only potentially invoke the destructors of potentially constructed 5146 // subobjects. 5147 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5148 5149 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5150 5151 // Bases. 5152 for (const auto &Base : ClassDecl->bases()) { 5153 // Bases are always records in a well-formed non-dependent class. 5154 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5155 5156 // Remember direct virtual bases. 5157 if (Base.isVirtual()) { 5158 if (!VisitVirtualBases) 5159 continue; 5160 DirectVirtualBases.insert(RT); 5161 } 5162 5163 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5164 // If our base class is invalid, we probably can't get its dtor anyway. 5165 if (BaseClassDecl->isInvalidDecl()) 5166 continue; 5167 if (BaseClassDecl->hasIrrelevantDestructor()) 5168 continue; 5169 5170 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5171 assert(Dtor && "No dtor found for BaseClassDecl!"); 5172 5173 // FIXME: caret should be on the start of the class name 5174 CheckDestructorAccess(Base.getLocStart(), Dtor, 5175 PDiag(diag::err_access_dtor_base) 5176 << Base.getType() 5177 << Base.getSourceRange(), 5178 Context.getTypeDeclType(ClassDecl)); 5179 5180 MarkFunctionReferenced(Location, Dtor); 5181 DiagnoseUseOfDecl(Dtor, Location); 5182 } 5183 5184 if (!VisitVirtualBases) 5185 return; 5186 5187 // Virtual bases. 5188 for (const auto &VBase : ClassDecl->vbases()) { 5189 // Bases are always records in a well-formed non-dependent class. 5190 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5191 5192 // Ignore direct virtual bases. 5193 if (DirectVirtualBases.count(RT)) 5194 continue; 5195 5196 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5197 // If our base class is invalid, we probably can't get its dtor anyway. 5198 if (BaseClassDecl->isInvalidDecl()) 5199 continue; 5200 if (BaseClassDecl->hasIrrelevantDestructor()) 5201 continue; 5202 5203 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5204 assert(Dtor && "No dtor found for BaseClassDecl!"); 5205 if (CheckDestructorAccess( 5206 ClassDecl->getLocation(), Dtor, 5207 PDiag(diag::err_access_dtor_vbase) 5208 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5209 Context.getTypeDeclType(ClassDecl)) == 5210 AR_accessible) { 5211 CheckDerivedToBaseConversion( 5212 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5213 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5214 SourceRange(), DeclarationName(), nullptr); 5215 } 5216 5217 MarkFunctionReferenced(Location, Dtor); 5218 DiagnoseUseOfDecl(Dtor, Location); 5219 } 5220 } 5221 5222 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5223 if (!CDtorDecl) 5224 return; 5225 5226 if (CXXConstructorDecl *Constructor 5227 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5228 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5229 DiagnoseUninitializedFields(*this, Constructor); 5230 } 5231 } 5232 5233 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5234 if (!getLangOpts().CPlusPlus) 5235 return false; 5236 5237 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5238 if (!RD) 5239 return false; 5240 5241 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5242 // class template specialization here, but doing so breaks a lot of code. 5243 5244 // We can't answer whether something is abstract until it has a 5245 // definition. If it's currently being defined, we'll walk back 5246 // over all the declarations when we have a full definition. 5247 const CXXRecordDecl *Def = RD->getDefinition(); 5248 if (!Def || Def->isBeingDefined()) 5249 return false; 5250 5251 return RD->isAbstract(); 5252 } 5253 5254 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5255 TypeDiagnoser &Diagnoser) { 5256 if (!isAbstractType(Loc, T)) 5257 return false; 5258 5259 T = Context.getBaseElementType(T); 5260 Diagnoser.diagnose(*this, Loc, T); 5261 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5262 return true; 5263 } 5264 5265 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5266 // Check if we've already emitted the list of pure virtual functions 5267 // for this class. 5268 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5269 return; 5270 5271 // If the diagnostic is suppressed, don't emit the notes. We're only 5272 // going to emit them once, so try to attach them to a diagnostic we're 5273 // actually going to show. 5274 if (Diags.isLastDiagnosticIgnored()) 5275 return; 5276 5277 CXXFinalOverriderMap FinalOverriders; 5278 RD->getFinalOverriders(FinalOverriders); 5279 5280 // Keep a set of seen pure methods so we won't diagnose the same method 5281 // more than once. 5282 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5283 5284 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5285 MEnd = FinalOverriders.end(); 5286 M != MEnd; 5287 ++M) { 5288 for (OverridingMethods::iterator SO = M->second.begin(), 5289 SOEnd = M->second.end(); 5290 SO != SOEnd; ++SO) { 5291 // C++ [class.abstract]p4: 5292 // A class is abstract if it contains or inherits at least one 5293 // pure virtual function for which the final overrider is pure 5294 // virtual. 5295 5296 // 5297 if (SO->second.size() != 1) 5298 continue; 5299 5300 if (!SO->second.front().Method->isPure()) 5301 continue; 5302 5303 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5304 continue; 5305 5306 Diag(SO->second.front().Method->getLocation(), 5307 diag::note_pure_virtual_function) 5308 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5309 } 5310 } 5311 5312 if (!PureVirtualClassDiagSet) 5313 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5314 PureVirtualClassDiagSet->insert(RD); 5315 } 5316 5317 namespace { 5318 struct AbstractUsageInfo { 5319 Sema &S; 5320 CXXRecordDecl *Record; 5321 CanQualType AbstractType; 5322 bool Invalid; 5323 5324 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5325 : S(S), Record(Record), 5326 AbstractType(S.Context.getCanonicalType( 5327 S.Context.getTypeDeclType(Record))), 5328 Invalid(false) {} 5329 5330 void DiagnoseAbstractType() { 5331 if (Invalid) return; 5332 S.DiagnoseAbstractType(Record); 5333 Invalid = true; 5334 } 5335 5336 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5337 }; 5338 5339 struct CheckAbstractUsage { 5340 AbstractUsageInfo &Info; 5341 const NamedDecl *Ctx; 5342 5343 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5344 : Info(Info), Ctx(Ctx) {} 5345 5346 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5347 switch (TL.getTypeLocClass()) { 5348 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5349 #define TYPELOC(CLASS, PARENT) \ 5350 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5351 #include "clang/AST/TypeLocNodes.def" 5352 } 5353 } 5354 5355 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5356 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5357 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5358 if (!TL.getParam(I)) 5359 continue; 5360 5361 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5362 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5363 } 5364 } 5365 5366 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5367 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5368 } 5369 5370 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5371 // Visit the type parameters from a permissive context. 5372 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5373 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5374 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5375 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5376 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5377 // TODO: other template argument types? 5378 } 5379 } 5380 5381 // Visit pointee types from a permissive context. 5382 #define CheckPolymorphic(Type) \ 5383 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5384 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5385 } 5386 CheckPolymorphic(PointerTypeLoc) 5387 CheckPolymorphic(ReferenceTypeLoc) 5388 CheckPolymorphic(MemberPointerTypeLoc) 5389 CheckPolymorphic(BlockPointerTypeLoc) 5390 CheckPolymorphic(AtomicTypeLoc) 5391 5392 /// Handle all the types we haven't given a more specific 5393 /// implementation for above. 5394 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5395 // Every other kind of type that we haven't called out already 5396 // that has an inner type is either (1) sugar or (2) contains that 5397 // inner type in some way as a subobject. 5398 if (TypeLoc Next = TL.getNextTypeLoc()) 5399 return Visit(Next, Sel); 5400 5401 // If there's no inner type and we're in a permissive context, 5402 // don't diagnose. 5403 if (Sel == Sema::AbstractNone) return; 5404 5405 // Check whether the type matches the abstract type. 5406 QualType T = TL.getType(); 5407 if (T->isArrayType()) { 5408 Sel = Sema::AbstractArrayType; 5409 T = Info.S.Context.getBaseElementType(T); 5410 } 5411 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5412 if (CT != Info.AbstractType) return; 5413 5414 // It matched; do some magic. 5415 if (Sel == Sema::AbstractArrayType) { 5416 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5417 << T << TL.getSourceRange(); 5418 } else { 5419 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5420 << Sel << T << TL.getSourceRange(); 5421 } 5422 Info.DiagnoseAbstractType(); 5423 } 5424 }; 5425 5426 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5427 Sema::AbstractDiagSelID Sel) { 5428 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5429 } 5430 5431 } 5432 5433 /// Check for invalid uses of an abstract type in a method declaration. 5434 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5435 CXXMethodDecl *MD) { 5436 // No need to do the check on definitions, which require that 5437 // the return/param types be complete. 5438 if (MD->doesThisDeclarationHaveABody()) 5439 return; 5440 5441 // For safety's sake, just ignore it if we don't have type source 5442 // information. This should never happen for non-implicit methods, 5443 // but... 5444 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5445 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5446 } 5447 5448 /// Check for invalid uses of an abstract type within a class definition. 5449 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5450 CXXRecordDecl *RD) { 5451 for (auto *D : RD->decls()) { 5452 if (D->isImplicit()) continue; 5453 5454 // Methods and method templates. 5455 if (isa<CXXMethodDecl>(D)) { 5456 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5457 } else if (isa<FunctionTemplateDecl>(D)) { 5458 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5459 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5460 5461 // Fields and static variables. 5462 } else if (isa<FieldDecl>(D)) { 5463 FieldDecl *FD = cast<FieldDecl>(D); 5464 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5465 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5466 } else if (isa<VarDecl>(D)) { 5467 VarDecl *VD = cast<VarDecl>(D); 5468 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5469 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5470 5471 // Nested classes and class templates. 5472 } else if (isa<CXXRecordDecl>(D)) { 5473 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5474 } else if (isa<ClassTemplateDecl>(D)) { 5475 CheckAbstractClassUsage(Info, 5476 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5477 } 5478 } 5479 } 5480 5481 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5482 Attr *ClassAttr = getDLLAttr(Class); 5483 if (!ClassAttr) 5484 return; 5485 5486 assert(ClassAttr->getKind() == attr::DLLExport); 5487 5488 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5489 5490 if (TSK == TSK_ExplicitInstantiationDeclaration) 5491 // Don't go any further if this is just an explicit instantiation 5492 // declaration. 5493 return; 5494 5495 for (Decl *Member : Class->decls()) { 5496 // Defined static variables that are members of an exported base 5497 // class must be marked export too. 5498 auto *VD = dyn_cast<VarDecl>(Member); 5499 if (VD && Member->getAttr<DLLExportAttr>() && 5500 VD->getStorageClass() == SC_Static && 5501 TSK == TSK_ImplicitInstantiation) 5502 S.MarkVariableReferenced(VD->getLocation(), VD); 5503 5504 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5505 if (!MD) 5506 continue; 5507 5508 if (Member->getAttr<DLLExportAttr>()) { 5509 if (MD->isUserProvided()) { 5510 // Instantiate non-default class member functions ... 5511 5512 // .. except for certain kinds of template specializations. 5513 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5514 continue; 5515 5516 S.MarkFunctionReferenced(Class->getLocation(), MD); 5517 5518 // The function will be passed to the consumer when its definition is 5519 // encountered. 5520 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5521 MD->isCopyAssignmentOperator() || 5522 MD->isMoveAssignmentOperator()) { 5523 // Synthesize and instantiate non-trivial implicit methods, explicitly 5524 // defaulted methods, and the copy and move assignment operators. The 5525 // latter are exported even if they are trivial, because the address of 5526 // an operator can be taken and should compare equal across libraries. 5527 DiagnosticErrorTrap Trap(S.Diags); 5528 S.MarkFunctionReferenced(Class->getLocation(), MD); 5529 if (Trap.hasErrorOccurred()) { 5530 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5531 << Class << !S.getLangOpts().CPlusPlus11; 5532 break; 5533 } 5534 5535 // There is no later point when we will see the definition of this 5536 // function, so pass it to the consumer now. 5537 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5538 } 5539 } 5540 } 5541 } 5542 5543 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5544 CXXRecordDecl *Class) { 5545 // Only the MS ABI has default constructor closures, so we don't need to do 5546 // this semantic checking anywhere else. 5547 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5548 return; 5549 5550 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5551 for (Decl *Member : Class->decls()) { 5552 // Look for exported default constructors. 5553 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5554 if (!CD || !CD->isDefaultConstructor()) 5555 continue; 5556 auto *Attr = CD->getAttr<DLLExportAttr>(); 5557 if (!Attr) 5558 continue; 5559 5560 // If the class is non-dependent, mark the default arguments as ODR-used so 5561 // that we can properly codegen the constructor closure. 5562 if (!Class->isDependentContext()) { 5563 for (ParmVarDecl *PD : CD->parameters()) { 5564 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5565 S.DiscardCleanupsInEvaluationContext(); 5566 } 5567 } 5568 5569 if (LastExportedDefaultCtor) { 5570 S.Diag(LastExportedDefaultCtor->getLocation(), 5571 diag::err_attribute_dll_ambiguous_default_ctor) 5572 << Class; 5573 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5574 << CD->getDeclName(); 5575 return; 5576 } 5577 LastExportedDefaultCtor = CD; 5578 } 5579 } 5580 5581 /// \brief Check class-level dllimport/dllexport attribute. 5582 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5583 Attr *ClassAttr = getDLLAttr(Class); 5584 5585 // MSVC inherits DLL attributes to partial class template specializations. 5586 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5587 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5588 if (Attr *TemplateAttr = 5589 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5590 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5591 A->setInherited(true); 5592 ClassAttr = A; 5593 } 5594 } 5595 } 5596 5597 if (!ClassAttr) 5598 return; 5599 5600 if (!Class->isExternallyVisible()) { 5601 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5602 << Class << ClassAttr; 5603 return; 5604 } 5605 5606 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5607 !ClassAttr->isInherited()) { 5608 // Diagnose dll attributes on members of class with dll attribute. 5609 for (Decl *Member : Class->decls()) { 5610 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5611 continue; 5612 InheritableAttr *MemberAttr = getDLLAttr(Member); 5613 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5614 continue; 5615 5616 Diag(MemberAttr->getLocation(), 5617 diag::err_attribute_dll_member_of_dll_class) 5618 << MemberAttr << ClassAttr; 5619 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5620 Member->setInvalidDecl(); 5621 } 5622 } 5623 5624 if (Class->getDescribedClassTemplate()) 5625 // Don't inherit dll attribute until the template is instantiated. 5626 return; 5627 5628 // The class is either imported or exported. 5629 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5630 5631 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5632 5633 // Ignore explicit dllexport on explicit class template instantiation declarations. 5634 if (ClassExported && !ClassAttr->isInherited() && 5635 TSK == TSK_ExplicitInstantiationDeclaration) { 5636 Class->dropAttr<DLLExportAttr>(); 5637 return; 5638 } 5639 5640 // Force declaration of implicit members so they can inherit the attribute. 5641 ForceDeclarationOfImplicitMembers(Class); 5642 5643 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5644 // seem to be true in practice? 5645 5646 for (Decl *Member : Class->decls()) { 5647 VarDecl *VD = dyn_cast<VarDecl>(Member); 5648 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5649 5650 // Only methods and static fields inherit the attributes. 5651 if (!VD && !MD) 5652 continue; 5653 5654 if (MD) { 5655 // Don't process deleted methods. 5656 if (MD->isDeleted()) 5657 continue; 5658 5659 if (MD->isInlined()) { 5660 // MinGW does not import or export inline methods. 5661 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5662 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5663 continue; 5664 5665 // MSVC versions before 2015 don't export the move assignment operators 5666 // and move constructor, so don't attempt to import/export them if 5667 // we have a definition. 5668 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5669 if ((MD->isMoveAssignmentOperator() || 5670 (Ctor && Ctor->isMoveConstructor())) && 5671 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5672 continue; 5673 5674 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5675 // operator is exported anyway. 5676 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5677 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5678 continue; 5679 } 5680 } 5681 5682 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5683 continue; 5684 5685 if (!getDLLAttr(Member)) { 5686 auto *NewAttr = 5687 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5688 NewAttr->setInherited(true); 5689 Member->addAttr(NewAttr); 5690 5691 if (MD) { 5692 // Propagate DLLAttr to friend re-declarations of MD that have already 5693 // been constructed. 5694 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5695 FD = FD->getPreviousDecl()) { 5696 if (FD->getFriendObjectKind() == Decl::FOK_None) 5697 continue; 5698 assert(!getDLLAttr(FD) && 5699 "friend re-decl should not already have a DLLAttr"); 5700 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5701 NewAttr->setInherited(true); 5702 FD->addAttr(NewAttr); 5703 } 5704 } 5705 } 5706 } 5707 5708 if (ClassExported) 5709 DelayedDllExportClasses.push_back(Class); 5710 } 5711 5712 /// \brief Perform propagation of DLL attributes from a derived class to a 5713 /// templated base class for MS compatibility. 5714 void Sema::propagateDLLAttrToBaseClassTemplate( 5715 CXXRecordDecl *Class, Attr *ClassAttr, 5716 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5717 if (getDLLAttr( 5718 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5719 // If the base class template has a DLL attribute, don't try to change it. 5720 return; 5721 } 5722 5723 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5724 if (!getDLLAttr(BaseTemplateSpec) && 5725 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5726 TSK == TSK_ImplicitInstantiation)) { 5727 // The template hasn't been instantiated yet (or it has, but only as an 5728 // explicit instantiation declaration or implicit instantiation, which means 5729 // we haven't codegenned any members yet), so propagate the attribute. 5730 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5731 NewAttr->setInherited(true); 5732 BaseTemplateSpec->addAttr(NewAttr); 5733 5734 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5735 // needs to be run again to work see the new attribute. Otherwise this will 5736 // get run whenever the template is instantiated. 5737 if (TSK != TSK_Undeclared) 5738 checkClassLevelDLLAttribute(BaseTemplateSpec); 5739 5740 return; 5741 } 5742 5743 if (getDLLAttr(BaseTemplateSpec)) { 5744 // The template has already been specialized or instantiated with an 5745 // attribute, explicitly or through propagation. We should not try to change 5746 // it. 5747 return; 5748 } 5749 5750 // The template was previously instantiated or explicitly specialized without 5751 // a dll attribute, It's too late for us to add an attribute, so warn that 5752 // this is unsupported. 5753 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5754 << BaseTemplateSpec->isExplicitSpecialization(); 5755 Diag(ClassAttr->getLocation(), diag::note_attribute); 5756 if (BaseTemplateSpec->isExplicitSpecialization()) { 5757 Diag(BaseTemplateSpec->getLocation(), 5758 diag::note_template_class_explicit_specialization_was_here) 5759 << BaseTemplateSpec; 5760 } else { 5761 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5762 diag::note_template_class_instantiation_was_here) 5763 << BaseTemplateSpec; 5764 } 5765 } 5766 5767 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5768 SourceLocation DefaultLoc) { 5769 switch (S.getSpecialMember(MD)) { 5770 case Sema::CXXDefaultConstructor: 5771 S.DefineImplicitDefaultConstructor(DefaultLoc, 5772 cast<CXXConstructorDecl>(MD)); 5773 break; 5774 case Sema::CXXCopyConstructor: 5775 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5776 break; 5777 case Sema::CXXCopyAssignment: 5778 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5779 break; 5780 case Sema::CXXDestructor: 5781 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5782 break; 5783 case Sema::CXXMoveConstructor: 5784 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5785 break; 5786 case Sema::CXXMoveAssignment: 5787 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5788 break; 5789 case Sema::CXXInvalid: 5790 llvm_unreachable("Invalid special member."); 5791 } 5792 } 5793 5794 /// Determine whether a type would be destructed in the callee if it had a 5795 /// non-trivial destructor. The rules here are based on C++ [class.temporary]p3, 5796 /// which determines whether a struct can be passed to or returned from 5797 /// functions in registers. 5798 static bool paramCanBeDestroyedInCallee(Sema &S, CXXRecordDecl *D, 5799 TargetInfo::CallingConvKind CCK) { 5800 if (D->isDependentType() || D->isInvalidDecl()) 5801 return false; 5802 5803 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 5804 // The PS4 platform ABI follows the behavior of Clang 3.2. 5805 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 5806 return !D->hasNonTrivialDestructorForCall() && 5807 !D->hasNonTrivialCopyConstructorForCall(); 5808 5809 // Per C++ [class.temporary]p3, the relevant condition is: 5810 // each copy constructor, move constructor, and destructor of X is 5811 // either trivial or deleted, and X has at least one non-deleted copy 5812 // or move constructor 5813 bool HasNonDeletedCopyOrMove = false; 5814 5815 if (D->needsImplicitCopyConstructor() && 5816 !D->defaultedCopyConstructorIsDeleted()) { 5817 if (!D->hasTrivialCopyConstructorForCall()) 5818 return false; 5819 HasNonDeletedCopyOrMove = true; 5820 } 5821 5822 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5823 !D->defaultedMoveConstructorIsDeleted()) { 5824 if (!D->hasTrivialMoveConstructorForCall()) 5825 return false; 5826 HasNonDeletedCopyOrMove = true; 5827 } 5828 5829 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5830 !D->hasTrivialDestructorForCall()) 5831 return false; 5832 5833 for (const CXXMethodDecl *MD : D->methods()) { 5834 if (MD->isDeleted()) 5835 continue; 5836 5837 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5838 if (CD && CD->isCopyOrMoveConstructor()) 5839 HasNonDeletedCopyOrMove = true; 5840 else if (!isa<CXXDestructorDecl>(MD)) 5841 continue; 5842 5843 if (!MD->isTrivialForCall()) 5844 return false; 5845 } 5846 5847 return HasNonDeletedCopyOrMove; 5848 } 5849 5850 static RecordDecl::ArgPassingKind 5851 computeArgPassingRestrictions(bool DestroyedInCallee, const CXXRecordDecl *RD, 5852 TargetInfo::CallingConvKind CCK, Sema &S) { 5853 if (RD->isDependentType() || RD->isInvalidDecl()) 5854 return RecordDecl::APK_CanPassInRegs; 5855 5856 // The param cannot be passed in registers if ArgPassingRestrictions is set to 5857 // APK_CanNeverPassInRegs. 5858 if (RD->getArgPassingRestrictions() == RecordDecl::APK_CanNeverPassInRegs) 5859 return RecordDecl::APK_CanNeverPassInRegs; 5860 5861 if (CCK != TargetInfo::CCK_MicrosoftX86_64) 5862 return DestroyedInCallee ? RecordDecl::APK_CanPassInRegs 5863 : RecordDecl::APK_CannotPassInRegs; 5864 5865 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 5866 bool DtorIsTrivialForCall = false; 5867 5868 // If a class has at least one non-deleted, trivial copy constructor, it 5869 // is passed according to the C ABI. Otherwise, it is passed indirectly. 5870 // 5871 // Note: This permits classes with non-trivial copy or move ctors to be 5872 // passed in registers, so long as they *also* have a trivial copy ctor, 5873 // which is non-conforming. 5874 if (RD->needsImplicitCopyConstructor()) { 5875 if (!RD->defaultedCopyConstructorIsDeleted()) { 5876 if (RD->hasTrivialCopyConstructor()) 5877 CopyCtorIsTrivial = true; 5878 if (RD->hasTrivialCopyConstructorForCall()) 5879 CopyCtorIsTrivialForCall = true; 5880 } 5881 } else { 5882 for (const CXXConstructorDecl *CD : RD->ctors()) { 5883 if (CD->isCopyConstructor() && !CD->isDeleted()) { 5884 if (CD->isTrivial()) 5885 CopyCtorIsTrivial = true; 5886 if (CD->isTrivialForCall()) 5887 CopyCtorIsTrivialForCall = true; 5888 } 5889 } 5890 } 5891 5892 if (RD->needsImplicitDestructor()) { 5893 if (!RD->defaultedDestructorIsDeleted() && 5894 RD->hasTrivialDestructorForCall()) 5895 DtorIsTrivialForCall = true; 5896 } else if (const auto *D = RD->getDestructor()) { 5897 if (!D->isDeleted() && D->isTrivialForCall()) 5898 DtorIsTrivialForCall = true; 5899 } 5900 5901 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 5902 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 5903 return RecordDecl::APK_CanPassInRegs; 5904 5905 // If a class has a destructor, we'd really like to pass it indirectly 5906 // because it allows us to elide copies. Unfortunately, MSVC makes that 5907 // impossible for small types, which it will pass in a single register or 5908 // stack slot. Most objects with dtors are large-ish, so handle that early. 5909 // We can't call out all large objects as being indirect because there are 5910 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 5911 // how we pass large POD types. 5912 5913 // Note: This permits small classes with nontrivial destructors to be 5914 // passed in registers, which is non-conforming. 5915 if (CopyCtorIsTrivial && 5916 S.getASTContext().getTypeSize(RD->getTypeForDecl()) <= 64) 5917 return RecordDecl::APK_CanPassInRegs; 5918 return RecordDecl::APK_CannotPassInRegs; 5919 } 5920 5921 /// \brief Perform semantic checks on a class definition that has been 5922 /// completing, introducing implicitly-declared members, checking for 5923 /// abstract types, etc. 5924 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5925 if (!Record) 5926 return; 5927 5928 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5929 AbstractUsageInfo Info(*this, Record); 5930 CheckAbstractClassUsage(Info, Record); 5931 } 5932 5933 // If this is not an aggregate type and has no user-declared constructor, 5934 // complain about any non-static data members of reference or const scalar 5935 // type, since they will never get initializers. 5936 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5937 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5938 !Record->isLambda()) { 5939 bool Complained = false; 5940 for (const auto *F : Record->fields()) { 5941 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5942 continue; 5943 5944 if (F->getType()->isReferenceType() || 5945 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5946 if (!Complained) { 5947 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5948 << Record->getTagKind() << Record; 5949 Complained = true; 5950 } 5951 5952 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5953 << F->getType()->isReferenceType() 5954 << F->getDeclName(); 5955 } 5956 } 5957 } 5958 5959 if (Record->getIdentifier()) { 5960 // C++ [class.mem]p13: 5961 // If T is the name of a class, then each of the following shall have a 5962 // name different from T: 5963 // - every member of every anonymous union that is a member of class T. 5964 // 5965 // C++ [class.mem]p14: 5966 // In addition, if class T has a user-declared constructor (12.1), every 5967 // non-static data member of class T shall have a name different from T. 5968 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5969 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5970 ++I) { 5971 NamedDecl *D = *I; 5972 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5973 isa<IndirectFieldDecl>(D)) { 5974 Diag(D->getLocation(), diag::err_member_name_of_class) 5975 << D->getDeclName(); 5976 break; 5977 } 5978 } 5979 } 5980 5981 // Warn if the class has virtual methods but non-virtual public destructor. 5982 if (Record->isPolymorphic() && !Record->isDependentType()) { 5983 CXXDestructorDecl *dtor = Record->getDestructor(); 5984 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5985 !Record->hasAttr<FinalAttr>()) 5986 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5987 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5988 } 5989 5990 if (Record->isAbstract()) { 5991 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5992 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5993 << FA->isSpelledAsSealed(); 5994 DiagnoseAbstractType(Record); 5995 } 5996 } 5997 5998 // Set HasTrivialSpecialMemberForCall if the record has attribute 5999 // "trivial_abi". 6000 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6001 6002 if (HasTrivialABI) 6003 Record->setHasTrivialSpecialMemberForCall(); 6004 6005 bool HasMethodWithOverrideControl = false, 6006 HasOverridingMethodWithoutOverrideControl = false; 6007 if (!Record->isDependentType()) { 6008 for (auto *M : Record->methods()) { 6009 // See if a method overloads virtual methods in a base 6010 // class without overriding any. 6011 if (!M->isStatic()) 6012 DiagnoseHiddenVirtualMethods(M); 6013 if (M->hasAttr<OverrideAttr>()) 6014 HasMethodWithOverrideControl = true; 6015 else if (M->size_overridden_methods() > 0) 6016 HasOverridingMethodWithoutOverrideControl = true; 6017 // Check whether the explicitly-defaulted special members are valid. 6018 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6019 CheckExplicitlyDefaultedSpecialMember(M); 6020 6021 // For an explicitly defaulted or deleted special member, we defer 6022 // determining triviality until the class is complete. That time is now! 6023 CXXSpecialMember CSM = getSpecialMember(M); 6024 if (!M->isImplicit() && !M->isUserProvided()) { 6025 if (CSM != CXXInvalid) { 6026 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6027 // Inform the class that we've finished declaring this member. 6028 Record->finishedDefaultedOrDeletedMember(M); 6029 M->setTrivialForCall( 6030 HasTrivialABI || 6031 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6032 Record->setTrivialForCallFlags(M); 6033 } 6034 } 6035 6036 // Set triviality for the purpose of calls if this is a user-provided 6037 // copy/move constructor or destructor. 6038 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6039 CSM == CXXDestructor) && M->isUserProvided()) { 6040 M->setTrivialForCall(HasTrivialABI); 6041 Record->setTrivialForCallFlags(M); 6042 } 6043 6044 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6045 M->hasAttr<DLLExportAttr>()) { 6046 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6047 M->isTrivial() && 6048 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6049 CSM == CXXDestructor)) 6050 M->dropAttr<DLLExportAttr>(); 6051 6052 if (M->hasAttr<DLLExportAttr>()) { 6053 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6054 ActOnFinishInlineFunctionDef(M); 6055 } 6056 } 6057 } 6058 } 6059 6060 if (HasMethodWithOverrideControl && 6061 HasOverridingMethodWithoutOverrideControl) { 6062 // At least one method has the 'override' control declared. 6063 // Diagnose all other overridden methods which do not have 'override' specified on them. 6064 for (auto *M : Record->methods()) 6065 DiagnoseAbsenceOfOverrideControl(M); 6066 } 6067 6068 // ms_struct is a request to use the same ABI rules as MSVC. Check 6069 // whether this class uses any C++ features that are implemented 6070 // completely differently in MSVC, and if so, emit a diagnostic. 6071 // That diagnostic defaults to an error, but we allow projects to 6072 // map it down to a warning (or ignore it). It's a fairly common 6073 // practice among users of the ms_struct pragma to mass-annotate 6074 // headers, sweeping up a bunch of types that the project doesn't 6075 // really rely on MSVC-compatible layout for. We must therefore 6076 // support "ms_struct except for C++ stuff" as a secondary ABI. 6077 if (Record->isMsStruct(Context) && 6078 (Record->isPolymorphic() || Record->getNumBases())) { 6079 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6080 } 6081 6082 checkClassLevelDLLAttribute(Record); 6083 6084 bool ClangABICompat4 = 6085 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6086 TargetInfo::CallingConvKind CCK = 6087 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6088 bool DestroyedInCallee = paramCanBeDestroyedInCallee(*this, Record, CCK); 6089 6090 if (Record->hasNonTrivialDestructor()) 6091 Record->setParamDestroyedInCallee(DestroyedInCallee); 6092 6093 Record->setArgPassingRestrictions( 6094 computeArgPassingRestrictions(DestroyedInCallee, Record, CCK, *this)); 6095 } 6096 6097 /// Look up the special member function that would be called by a special 6098 /// member function for a subobject of class type. 6099 /// 6100 /// \param Class The class type of the subobject. 6101 /// \param CSM The kind of special member function. 6102 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6103 /// \param ConstRHS True if this is a copy operation with a const object 6104 /// on its RHS, that is, if the argument to the outer special member 6105 /// function is 'const' and this is not a field marked 'mutable'. 6106 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6107 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6108 unsigned FieldQuals, bool ConstRHS) { 6109 unsigned LHSQuals = 0; 6110 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6111 LHSQuals = FieldQuals; 6112 6113 unsigned RHSQuals = FieldQuals; 6114 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6115 RHSQuals = 0; 6116 else if (ConstRHS) 6117 RHSQuals |= Qualifiers::Const; 6118 6119 return S.LookupSpecialMember(Class, CSM, 6120 RHSQuals & Qualifiers::Const, 6121 RHSQuals & Qualifiers::Volatile, 6122 false, 6123 LHSQuals & Qualifiers::Const, 6124 LHSQuals & Qualifiers::Volatile); 6125 } 6126 6127 class Sema::InheritedConstructorInfo { 6128 Sema &S; 6129 SourceLocation UseLoc; 6130 6131 /// A mapping from the base classes through which the constructor was 6132 /// inherited to the using shadow declaration in that base class (or a null 6133 /// pointer if the constructor was declared in that base class). 6134 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6135 InheritedFromBases; 6136 6137 public: 6138 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6139 ConstructorUsingShadowDecl *Shadow) 6140 : S(S), UseLoc(UseLoc) { 6141 bool DiagnosedMultipleConstructedBases = false; 6142 CXXRecordDecl *ConstructedBase = nullptr; 6143 UsingDecl *ConstructedBaseUsing = nullptr; 6144 6145 // Find the set of such base class subobjects and check that there's a 6146 // unique constructed subobject. 6147 for (auto *D : Shadow->redecls()) { 6148 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6149 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6150 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6151 6152 InheritedFromBases.insert( 6153 std::make_pair(DNominatedBase->getCanonicalDecl(), 6154 DShadow->getNominatedBaseClassShadowDecl())); 6155 if (DShadow->constructsVirtualBase()) 6156 InheritedFromBases.insert( 6157 std::make_pair(DConstructedBase->getCanonicalDecl(), 6158 DShadow->getConstructedBaseClassShadowDecl())); 6159 else 6160 assert(DNominatedBase == DConstructedBase); 6161 6162 // [class.inhctor.init]p2: 6163 // If the constructor was inherited from multiple base class subobjects 6164 // of type B, the program is ill-formed. 6165 if (!ConstructedBase) { 6166 ConstructedBase = DConstructedBase; 6167 ConstructedBaseUsing = D->getUsingDecl(); 6168 } else if (ConstructedBase != DConstructedBase && 6169 !Shadow->isInvalidDecl()) { 6170 if (!DiagnosedMultipleConstructedBases) { 6171 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6172 << Shadow->getTargetDecl(); 6173 S.Diag(ConstructedBaseUsing->getLocation(), 6174 diag::note_ambiguous_inherited_constructor_using) 6175 << ConstructedBase; 6176 DiagnosedMultipleConstructedBases = true; 6177 } 6178 S.Diag(D->getUsingDecl()->getLocation(), 6179 diag::note_ambiguous_inherited_constructor_using) 6180 << DConstructedBase; 6181 } 6182 } 6183 6184 if (DiagnosedMultipleConstructedBases) 6185 Shadow->setInvalidDecl(); 6186 } 6187 6188 /// Find the constructor to use for inherited construction of a base class, 6189 /// and whether that base class constructor inherits the constructor from a 6190 /// virtual base class (in which case it won't actually invoke it). 6191 std::pair<CXXConstructorDecl *, bool> 6192 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6193 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6194 if (It == InheritedFromBases.end()) 6195 return std::make_pair(nullptr, false); 6196 6197 // This is an intermediary class. 6198 if (It->second) 6199 return std::make_pair( 6200 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6201 It->second->constructsVirtualBase()); 6202 6203 // This is the base class from which the constructor was inherited. 6204 return std::make_pair(Ctor, false); 6205 } 6206 }; 6207 6208 /// Is the special member function which would be selected to perform the 6209 /// specified operation on the specified class type a constexpr constructor? 6210 static bool 6211 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6212 Sema::CXXSpecialMember CSM, unsigned Quals, 6213 bool ConstRHS, 6214 CXXConstructorDecl *InheritedCtor = nullptr, 6215 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6216 // If we're inheriting a constructor, see if we need to call it for this base 6217 // class. 6218 if (InheritedCtor) { 6219 assert(CSM == Sema::CXXDefaultConstructor); 6220 auto BaseCtor = 6221 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6222 if (BaseCtor) 6223 return BaseCtor->isConstexpr(); 6224 } 6225 6226 if (CSM == Sema::CXXDefaultConstructor) 6227 return ClassDecl->hasConstexprDefaultConstructor(); 6228 6229 Sema::SpecialMemberOverloadResult SMOR = 6230 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6231 if (!SMOR.getMethod()) 6232 // A constructor we wouldn't select can't be "involved in initializing" 6233 // anything. 6234 return true; 6235 return SMOR.getMethod()->isConstexpr(); 6236 } 6237 6238 /// Determine whether the specified special member function would be constexpr 6239 /// if it were implicitly defined. 6240 static bool defaultedSpecialMemberIsConstexpr( 6241 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6242 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6243 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6244 if (!S.getLangOpts().CPlusPlus11) 6245 return false; 6246 6247 // C++11 [dcl.constexpr]p4: 6248 // In the definition of a constexpr constructor [...] 6249 bool Ctor = true; 6250 switch (CSM) { 6251 case Sema::CXXDefaultConstructor: 6252 if (Inherited) 6253 break; 6254 // Since default constructor lookup is essentially trivial (and cannot 6255 // involve, for instance, template instantiation), we compute whether a 6256 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6257 // 6258 // This is important for performance; we need to know whether the default 6259 // constructor is constexpr to determine whether the type is a literal type. 6260 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6261 6262 case Sema::CXXCopyConstructor: 6263 case Sema::CXXMoveConstructor: 6264 // For copy or move constructors, we need to perform overload resolution. 6265 break; 6266 6267 case Sema::CXXCopyAssignment: 6268 case Sema::CXXMoveAssignment: 6269 if (!S.getLangOpts().CPlusPlus14) 6270 return false; 6271 // In C++1y, we need to perform overload resolution. 6272 Ctor = false; 6273 break; 6274 6275 case Sema::CXXDestructor: 6276 case Sema::CXXInvalid: 6277 return false; 6278 } 6279 6280 // -- if the class is a non-empty union, or for each non-empty anonymous 6281 // union member of a non-union class, exactly one non-static data member 6282 // shall be initialized; [DR1359] 6283 // 6284 // If we squint, this is guaranteed, since exactly one non-static data member 6285 // will be initialized (if the constructor isn't deleted), we just don't know 6286 // which one. 6287 if (Ctor && ClassDecl->isUnion()) 6288 return CSM == Sema::CXXDefaultConstructor 6289 ? ClassDecl->hasInClassInitializer() || 6290 !ClassDecl->hasVariantMembers() 6291 : true; 6292 6293 // -- the class shall not have any virtual base classes; 6294 if (Ctor && ClassDecl->getNumVBases()) 6295 return false; 6296 6297 // C++1y [class.copy]p26: 6298 // -- [the class] is a literal type, and 6299 if (!Ctor && !ClassDecl->isLiteral()) 6300 return false; 6301 6302 // -- every constructor involved in initializing [...] base class 6303 // sub-objects shall be a constexpr constructor; 6304 // -- the assignment operator selected to copy/move each direct base 6305 // class is a constexpr function, and 6306 for (const auto &B : ClassDecl->bases()) { 6307 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6308 if (!BaseType) continue; 6309 6310 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6311 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6312 InheritedCtor, Inherited)) 6313 return false; 6314 } 6315 6316 // -- every constructor involved in initializing non-static data members 6317 // [...] shall be a constexpr constructor; 6318 // -- every non-static data member and base class sub-object shall be 6319 // initialized 6320 // -- for each non-static data member of X that is of class type (or array 6321 // thereof), the assignment operator selected to copy/move that member is 6322 // a constexpr function 6323 for (const auto *F : ClassDecl->fields()) { 6324 if (F->isInvalidDecl()) 6325 continue; 6326 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6327 continue; 6328 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6329 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6330 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6331 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6332 BaseType.getCVRQualifiers(), 6333 ConstArg && !F->isMutable())) 6334 return false; 6335 } else if (CSM == Sema::CXXDefaultConstructor) { 6336 return false; 6337 } 6338 } 6339 6340 // All OK, it's constexpr! 6341 return true; 6342 } 6343 6344 static Sema::ImplicitExceptionSpecification 6345 ComputeDefaultedSpecialMemberExceptionSpec( 6346 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6347 Sema::InheritedConstructorInfo *ICI); 6348 6349 static Sema::ImplicitExceptionSpecification 6350 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6351 auto CSM = S.getSpecialMember(MD); 6352 if (CSM != Sema::CXXInvalid) 6353 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6354 6355 auto *CD = cast<CXXConstructorDecl>(MD); 6356 assert(CD->getInheritedConstructor() && 6357 "only special members have implicit exception specs"); 6358 Sema::InheritedConstructorInfo ICI( 6359 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6360 return ComputeDefaultedSpecialMemberExceptionSpec( 6361 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6362 } 6363 6364 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6365 CXXMethodDecl *MD) { 6366 FunctionProtoType::ExtProtoInfo EPI; 6367 6368 // Build an exception specification pointing back at this member. 6369 EPI.ExceptionSpec.Type = EST_Unevaluated; 6370 EPI.ExceptionSpec.SourceDecl = MD; 6371 6372 // Set the calling convention to the default for C++ instance methods. 6373 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6374 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6375 /*IsCXXMethod=*/true)); 6376 return EPI; 6377 } 6378 6379 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6380 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6381 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6382 return; 6383 6384 // Evaluate the exception specification. 6385 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6386 auto ESI = IES.getExceptionSpec(); 6387 6388 // Update the type of the special member to use it. 6389 UpdateExceptionSpec(MD, ESI); 6390 6391 // A user-provided destructor can be defined outside the class. When that 6392 // happens, be sure to update the exception specification on both 6393 // declarations. 6394 const FunctionProtoType *CanonicalFPT = 6395 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6396 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6397 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6398 } 6399 6400 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6401 CXXRecordDecl *RD = MD->getParent(); 6402 CXXSpecialMember CSM = getSpecialMember(MD); 6403 6404 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6405 "not an explicitly-defaulted special member"); 6406 6407 // Whether this was the first-declared instance of the constructor. 6408 // This affects whether we implicitly add an exception spec and constexpr. 6409 bool First = MD == MD->getCanonicalDecl(); 6410 6411 bool HadError = false; 6412 6413 // C++11 [dcl.fct.def.default]p1: 6414 // A function that is explicitly defaulted shall 6415 // -- be a special member function (checked elsewhere), 6416 // -- have the same type (except for ref-qualifiers, and except that a 6417 // copy operation can take a non-const reference) as an implicit 6418 // declaration, and 6419 // -- not have default arguments. 6420 unsigned ExpectedParams = 1; 6421 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6422 ExpectedParams = 0; 6423 if (MD->getNumParams() != ExpectedParams) { 6424 // This also checks for default arguments: a copy or move constructor with a 6425 // default argument is classified as a default constructor, and assignment 6426 // operations and destructors can't have default arguments. 6427 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6428 << CSM << MD->getSourceRange(); 6429 HadError = true; 6430 } else if (MD->isVariadic()) { 6431 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6432 << CSM << MD->getSourceRange(); 6433 HadError = true; 6434 } 6435 6436 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6437 6438 bool CanHaveConstParam = false; 6439 if (CSM == CXXCopyConstructor) 6440 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6441 else if (CSM == CXXCopyAssignment) 6442 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6443 6444 QualType ReturnType = Context.VoidTy; 6445 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6446 // Check for return type matching. 6447 ReturnType = Type->getReturnType(); 6448 QualType ExpectedReturnType = 6449 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6450 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6451 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6452 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6453 HadError = true; 6454 } 6455 6456 // A defaulted special member cannot have cv-qualifiers. 6457 if (Type->getTypeQuals()) { 6458 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6459 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6460 HadError = true; 6461 } 6462 } 6463 6464 // Check for parameter type matching. 6465 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6466 bool HasConstParam = false; 6467 if (ExpectedParams && ArgType->isReferenceType()) { 6468 // Argument must be reference to possibly-const T. 6469 QualType ReferentType = ArgType->getPointeeType(); 6470 HasConstParam = ReferentType.isConstQualified(); 6471 6472 if (ReferentType.isVolatileQualified()) { 6473 Diag(MD->getLocation(), 6474 diag::err_defaulted_special_member_volatile_param) << CSM; 6475 HadError = true; 6476 } 6477 6478 if (HasConstParam && !CanHaveConstParam) { 6479 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6480 Diag(MD->getLocation(), 6481 diag::err_defaulted_special_member_copy_const_param) 6482 << (CSM == CXXCopyAssignment); 6483 // FIXME: Explain why this special member can't be const. 6484 } else { 6485 Diag(MD->getLocation(), 6486 diag::err_defaulted_special_member_move_const_param) 6487 << (CSM == CXXMoveAssignment); 6488 } 6489 HadError = true; 6490 } 6491 } else if (ExpectedParams) { 6492 // A copy assignment operator can take its argument by value, but a 6493 // defaulted one cannot. 6494 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6495 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6496 HadError = true; 6497 } 6498 6499 // C++11 [dcl.fct.def.default]p2: 6500 // An explicitly-defaulted function may be declared constexpr only if it 6501 // would have been implicitly declared as constexpr, 6502 // Do not apply this rule to members of class templates, since core issue 1358 6503 // makes such functions always instantiate to constexpr functions. For 6504 // functions which cannot be constexpr (for non-constructors in C++11 and for 6505 // destructors in C++1y), this is checked elsewhere. 6506 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6507 HasConstParam); 6508 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6509 : isa<CXXConstructorDecl>(MD)) && 6510 MD->isConstexpr() && !Constexpr && 6511 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6512 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6513 // FIXME: Explain why the special member can't be constexpr. 6514 HadError = true; 6515 } 6516 6517 // and may have an explicit exception-specification only if it is compatible 6518 // with the exception-specification on the implicit declaration. 6519 if (Type->hasExceptionSpec()) { 6520 // Delay the check if this is the first declaration of the special member, 6521 // since we may not have parsed some necessary in-class initializers yet. 6522 if (First) { 6523 // If the exception specification needs to be instantiated, do so now, 6524 // before we clobber it with an EST_Unevaluated specification below. 6525 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6526 InstantiateExceptionSpec(MD->getLocStart(), MD); 6527 Type = MD->getType()->getAs<FunctionProtoType>(); 6528 } 6529 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6530 } else 6531 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6532 } 6533 6534 // If a function is explicitly defaulted on its first declaration, 6535 if (First) { 6536 // -- it is implicitly considered to be constexpr if the implicit 6537 // definition would be, 6538 MD->setConstexpr(Constexpr); 6539 6540 // -- it is implicitly considered to have the same exception-specification 6541 // as if it had been implicitly declared, 6542 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6543 EPI.ExceptionSpec.Type = EST_Unevaluated; 6544 EPI.ExceptionSpec.SourceDecl = MD; 6545 MD->setType(Context.getFunctionType(ReturnType, 6546 llvm::makeArrayRef(&ArgType, 6547 ExpectedParams), 6548 EPI)); 6549 } 6550 6551 if (ShouldDeleteSpecialMember(MD, CSM)) { 6552 if (First) { 6553 SetDeclDeleted(MD, MD->getLocation()); 6554 } else { 6555 // C++11 [dcl.fct.def.default]p4: 6556 // [For a] user-provided explicitly-defaulted function [...] if such a 6557 // function is implicitly defined as deleted, the program is ill-formed. 6558 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6559 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6560 HadError = true; 6561 } 6562 } 6563 6564 if (HadError) 6565 MD->setInvalidDecl(); 6566 } 6567 6568 /// Check whether the exception specification provided for an 6569 /// explicitly-defaulted special member matches the exception specification 6570 /// that would have been generated for an implicit special member, per 6571 /// C++11 [dcl.fct.def.default]p2. 6572 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6573 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6574 // If the exception specification was explicitly specified but hadn't been 6575 // parsed when the method was defaulted, grab it now. 6576 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6577 SpecifiedType = 6578 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6579 6580 // Compute the implicit exception specification. 6581 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6582 /*IsCXXMethod=*/true); 6583 FunctionProtoType::ExtProtoInfo EPI(CC); 6584 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6585 EPI.ExceptionSpec = IES.getExceptionSpec(); 6586 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6587 Context.getFunctionType(Context.VoidTy, None, EPI)); 6588 6589 // Ensure that it matches. 6590 CheckEquivalentExceptionSpec( 6591 PDiag(diag::err_incorrect_defaulted_exception_spec) 6592 << getSpecialMember(MD), PDiag(), 6593 ImplicitType, SourceLocation(), 6594 SpecifiedType, MD->getLocation()); 6595 } 6596 6597 void Sema::CheckDelayedMemberExceptionSpecs() { 6598 decltype(DelayedExceptionSpecChecks) Checks; 6599 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6600 6601 std::swap(Checks, DelayedExceptionSpecChecks); 6602 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6603 6604 // Perform any deferred checking of exception specifications for virtual 6605 // destructors. 6606 for (auto &Check : Checks) 6607 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6608 6609 // Check that any explicitly-defaulted methods have exception specifications 6610 // compatible with their implicit exception specifications. 6611 for (auto &Spec : Specs) 6612 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6613 } 6614 6615 namespace { 6616 /// CRTP base class for visiting operations performed by a special member 6617 /// function (or inherited constructor). 6618 template<typename Derived> 6619 struct SpecialMemberVisitor { 6620 Sema &S; 6621 CXXMethodDecl *MD; 6622 Sema::CXXSpecialMember CSM; 6623 Sema::InheritedConstructorInfo *ICI; 6624 6625 // Properties of the special member, computed for convenience. 6626 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6627 6628 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6629 Sema::InheritedConstructorInfo *ICI) 6630 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6631 switch (CSM) { 6632 case Sema::CXXDefaultConstructor: 6633 case Sema::CXXCopyConstructor: 6634 case Sema::CXXMoveConstructor: 6635 IsConstructor = true; 6636 break; 6637 case Sema::CXXCopyAssignment: 6638 case Sema::CXXMoveAssignment: 6639 IsAssignment = true; 6640 break; 6641 case Sema::CXXDestructor: 6642 break; 6643 case Sema::CXXInvalid: 6644 llvm_unreachable("invalid special member kind"); 6645 } 6646 6647 if (MD->getNumParams()) { 6648 if (const ReferenceType *RT = 6649 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6650 ConstArg = RT->getPointeeType().isConstQualified(); 6651 } 6652 } 6653 6654 Derived &getDerived() { return static_cast<Derived&>(*this); } 6655 6656 /// Is this a "move" special member? 6657 bool isMove() const { 6658 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6659 } 6660 6661 /// Look up the corresponding special member in the given class. 6662 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6663 unsigned Quals, bool IsMutable) { 6664 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6665 ConstArg && !IsMutable); 6666 } 6667 6668 /// Look up the constructor for the specified base class to see if it's 6669 /// overridden due to this being an inherited constructor. 6670 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6671 if (!ICI) 6672 return {}; 6673 assert(CSM == Sema::CXXDefaultConstructor); 6674 auto *BaseCtor = 6675 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6676 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6677 return MD; 6678 return {}; 6679 } 6680 6681 /// A base or member subobject. 6682 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6683 6684 /// Get the location to use for a subobject in diagnostics. 6685 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6686 // FIXME: For an indirect virtual base, the direct base leading to 6687 // the indirect virtual base would be a more useful choice. 6688 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6689 return B->getBaseTypeLoc(); 6690 else 6691 return Subobj.get<FieldDecl*>()->getLocation(); 6692 } 6693 6694 enum BasesToVisit { 6695 /// Visit all non-virtual (direct) bases. 6696 VisitNonVirtualBases, 6697 /// Visit all direct bases, virtual or not. 6698 VisitDirectBases, 6699 /// Visit all non-virtual bases, and all virtual bases if the class 6700 /// is not abstract. 6701 VisitPotentiallyConstructedBases, 6702 /// Visit all direct or virtual bases. 6703 VisitAllBases 6704 }; 6705 6706 // Visit the bases and members of the class. 6707 bool visit(BasesToVisit Bases) { 6708 CXXRecordDecl *RD = MD->getParent(); 6709 6710 if (Bases == VisitPotentiallyConstructedBases) 6711 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6712 6713 for (auto &B : RD->bases()) 6714 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6715 getDerived().visitBase(&B)) 6716 return true; 6717 6718 if (Bases == VisitAllBases) 6719 for (auto &B : RD->vbases()) 6720 if (getDerived().visitBase(&B)) 6721 return true; 6722 6723 for (auto *F : RD->fields()) 6724 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6725 getDerived().visitField(F)) 6726 return true; 6727 6728 return false; 6729 } 6730 }; 6731 } 6732 6733 namespace { 6734 struct SpecialMemberDeletionInfo 6735 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6736 bool Diagnose; 6737 6738 SourceLocation Loc; 6739 6740 bool AllFieldsAreConst; 6741 6742 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6743 Sema::CXXSpecialMember CSM, 6744 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6745 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6746 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6747 6748 bool inUnion() const { return MD->getParent()->isUnion(); } 6749 6750 Sema::CXXSpecialMember getEffectiveCSM() { 6751 return ICI ? Sema::CXXInvalid : CSM; 6752 } 6753 6754 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6755 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6756 6757 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6758 bool shouldDeleteForField(FieldDecl *FD); 6759 bool shouldDeleteForAllConstMembers(); 6760 6761 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6762 unsigned Quals); 6763 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6764 Sema::SpecialMemberOverloadResult SMOR, 6765 bool IsDtorCallInCtor); 6766 6767 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6768 }; 6769 } 6770 6771 /// Is the given special member inaccessible when used on the given 6772 /// sub-object. 6773 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6774 CXXMethodDecl *target) { 6775 /// If we're operating on a base class, the object type is the 6776 /// type of this special member. 6777 QualType objectTy; 6778 AccessSpecifier access = target->getAccess(); 6779 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6780 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6781 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6782 6783 // If we're operating on a field, the object type is the type of the field. 6784 } else { 6785 objectTy = S.Context.getTypeDeclType(target->getParent()); 6786 } 6787 6788 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6789 } 6790 6791 /// Check whether we should delete a special member due to the implicit 6792 /// definition containing a call to a special member of a subobject. 6793 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6794 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6795 bool IsDtorCallInCtor) { 6796 CXXMethodDecl *Decl = SMOR.getMethod(); 6797 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6798 6799 int DiagKind = -1; 6800 6801 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6802 DiagKind = !Decl ? 0 : 1; 6803 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6804 DiagKind = 2; 6805 else if (!isAccessible(Subobj, Decl)) 6806 DiagKind = 3; 6807 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6808 !Decl->isTrivial()) { 6809 // A member of a union must have a trivial corresponding special member. 6810 // As a weird special case, a destructor call from a union's constructor 6811 // must be accessible and non-deleted, but need not be trivial. Such a 6812 // destructor is never actually called, but is semantically checked as 6813 // if it were. 6814 DiagKind = 4; 6815 } 6816 6817 if (DiagKind == -1) 6818 return false; 6819 6820 if (Diagnose) { 6821 if (Field) { 6822 S.Diag(Field->getLocation(), 6823 diag::note_deleted_special_member_class_subobject) 6824 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6825 << Field << DiagKind << IsDtorCallInCtor; 6826 } else { 6827 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6828 S.Diag(Base->getLocStart(), 6829 diag::note_deleted_special_member_class_subobject) 6830 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6831 << Base->getType() << DiagKind << IsDtorCallInCtor; 6832 } 6833 6834 if (DiagKind == 1) 6835 S.NoteDeletedFunction(Decl); 6836 // FIXME: Explain inaccessibility if DiagKind == 3. 6837 } 6838 6839 return true; 6840 } 6841 6842 /// Check whether we should delete a special member function due to having a 6843 /// direct or virtual base class or non-static data member of class type M. 6844 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6845 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6846 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6847 bool IsMutable = Field && Field->isMutable(); 6848 6849 // C++11 [class.ctor]p5: 6850 // -- any direct or virtual base class, or non-static data member with no 6851 // brace-or-equal-initializer, has class type M (or array thereof) and 6852 // either M has no default constructor or overload resolution as applied 6853 // to M's default constructor results in an ambiguity or in a function 6854 // that is deleted or inaccessible 6855 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6856 // -- a direct or virtual base class B that cannot be copied/moved because 6857 // overload resolution, as applied to B's corresponding special member, 6858 // results in an ambiguity or a function that is deleted or inaccessible 6859 // from the defaulted special member 6860 // C++11 [class.dtor]p5: 6861 // -- any direct or virtual base class [...] has a type with a destructor 6862 // that is deleted or inaccessible 6863 if (!(CSM == Sema::CXXDefaultConstructor && 6864 Field && Field->hasInClassInitializer()) && 6865 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6866 false)) 6867 return true; 6868 6869 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6870 // -- any direct or virtual base class or non-static data member has a 6871 // type with a destructor that is deleted or inaccessible 6872 if (IsConstructor) { 6873 Sema::SpecialMemberOverloadResult SMOR = 6874 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6875 false, false, false, false, false); 6876 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6877 return true; 6878 } 6879 6880 return false; 6881 } 6882 6883 /// Check whether we should delete a special member function due to the class 6884 /// having a particular direct or virtual base class. 6885 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6886 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6887 // If program is correct, BaseClass cannot be null, but if it is, the error 6888 // must be reported elsewhere. 6889 if (!BaseClass) 6890 return false; 6891 // If we have an inheriting constructor, check whether we're calling an 6892 // inherited constructor instead of a default constructor. 6893 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6894 if (auto *BaseCtor = SMOR.getMethod()) { 6895 // Note that we do not check access along this path; other than that, 6896 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6897 // FIXME: Check that the base has a usable destructor! Sink this into 6898 // shouldDeleteForClassSubobject. 6899 if (BaseCtor->isDeleted() && Diagnose) { 6900 S.Diag(Base->getLocStart(), 6901 diag::note_deleted_special_member_class_subobject) 6902 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6903 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6904 S.NoteDeletedFunction(BaseCtor); 6905 } 6906 return BaseCtor->isDeleted(); 6907 } 6908 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6909 } 6910 6911 /// Check whether we should delete a special member function due to the class 6912 /// having a particular non-static data member. 6913 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6914 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6915 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6916 6917 if (CSM == Sema::CXXDefaultConstructor) { 6918 // For a default constructor, all references must be initialized in-class 6919 // and, if a union, it must have a non-const member. 6920 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6921 if (Diagnose) 6922 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6923 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6924 return true; 6925 } 6926 // C++11 [class.ctor]p5: any non-variant non-static data member of 6927 // const-qualified type (or array thereof) with no 6928 // brace-or-equal-initializer does not have a user-provided default 6929 // constructor. 6930 if (!inUnion() && FieldType.isConstQualified() && 6931 !FD->hasInClassInitializer() && 6932 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6933 if (Diagnose) 6934 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6935 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6936 return true; 6937 } 6938 6939 if (inUnion() && !FieldType.isConstQualified()) 6940 AllFieldsAreConst = false; 6941 } else if (CSM == Sema::CXXCopyConstructor) { 6942 // For a copy constructor, data members must not be of rvalue reference 6943 // type. 6944 if (FieldType->isRValueReferenceType()) { 6945 if (Diagnose) 6946 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6947 << MD->getParent() << FD << FieldType; 6948 return true; 6949 } 6950 } else if (IsAssignment) { 6951 // For an assignment operator, data members must not be of reference type. 6952 if (FieldType->isReferenceType()) { 6953 if (Diagnose) 6954 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6955 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6956 return true; 6957 } 6958 if (!FieldRecord && FieldType.isConstQualified()) { 6959 // C++11 [class.copy]p23: 6960 // -- a non-static data member of const non-class type (or array thereof) 6961 if (Diagnose) 6962 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6963 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6964 return true; 6965 } 6966 } 6967 6968 if (FieldRecord) { 6969 // Some additional restrictions exist on the variant members. 6970 if (!inUnion() && FieldRecord->isUnion() && 6971 FieldRecord->isAnonymousStructOrUnion()) { 6972 bool AllVariantFieldsAreConst = true; 6973 6974 // FIXME: Handle anonymous unions declared within anonymous unions. 6975 for (auto *UI : FieldRecord->fields()) { 6976 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6977 6978 if (!UnionFieldType.isConstQualified()) 6979 AllVariantFieldsAreConst = false; 6980 6981 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6982 if (UnionFieldRecord && 6983 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6984 UnionFieldType.getCVRQualifiers())) 6985 return true; 6986 } 6987 6988 // At least one member in each anonymous union must be non-const 6989 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6990 !FieldRecord->field_empty()) { 6991 if (Diagnose) 6992 S.Diag(FieldRecord->getLocation(), 6993 diag::note_deleted_default_ctor_all_const) 6994 << !!ICI << MD->getParent() << /*anonymous union*/1; 6995 return true; 6996 } 6997 6998 // Don't check the implicit member of the anonymous union type. 6999 // This is technically non-conformant, but sanity demands it. 7000 return false; 7001 } 7002 7003 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7004 FieldType.getCVRQualifiers())) 7005 return true; 7006 } 7007 7008 return false; 7009 } 7010 7011 /// C++11 [class.ctor] p5: 7012 /// A defaulted default constructor for a class X is defined as deleted if 7013 /// X is a union and all of its variant members are of const-qualified type. 7014 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7015 // This is a silly definition, because it gives an empty union a deleted 7016 // default constructor. Don't do that. 7017 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7018 bool AnyFields = false; 7019 for (auto *F : MD->getParent()->fields()) 7020 if ((AnyFields = !F->isUnnamedBitfield())) 7021 break; 7022 if (!AnyFields) 7023 return false; 7024 if (Diagnose) 7025 S.Diag(MD->getParent()->getLocation(), 7026 diag::note_deleted_default_ctor_all_const) 7027 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7028 return true; 7029 } 7030 return false; 7031 } 7032 7033 /// Determine whether a defaulted special member function should be defined as 7034 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7035 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7036 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7037 InheritedConstructorInfo *ICI, 7038 bool Diagnose) { 7039 if (MD->isInvalidDecl()) 7040 return false; 7041 CXXRecordDecl *RD = MD->getParent(); 7042 assert(!RD->isDependentType() && "do deletion after instantiation"); 7043 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7044 return false; 7045 7046 // C++11 [expr.lambda.prim]p19: 7047 // The closure type associated with a lambda-expression has a 7048 // deleted (8.4.3) default constructor and a deleted copy 7049 // assignment operator. 7050 if (RD->isLambda() && 7051 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7052 if (Diagnose) 7053 Diag(RD->getLocation(), diag::note_lambda_decl); 7054 return true; 7055 } 7056 7057 // For an anonymous struct or union, the copy and assignment special members 7058 // will never be used, so skip the check. For an anonymous union declared at 7059 // namespace scope, the constructor and destructor are used. 7060 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7061 RD->isAnonymousStructOrUnion()) 7062 return false; 7063 7064 // C++11 [class.copy]p7, p18: 7065 // If the class definition declares a move constructor or move assignment 7066 // operator, an implicitly declared copy constructor or copy assignment 7067 // operator is defined as deleted. 7068 if (MD->isImplicit() && 7069 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7070 CXXMethodDecl *UserDeclaredMove = nullptr; 7071 7072 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7073 // deletion of the corresponding copy operation, not both copy operations. 7074 // MSVC 2015 has adopted the standards conforming behavior. 7075 bool DeletesOnlyMatchingCopy = 7076 getLangOpts().MSVCCompat && 7077 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7078 7079 if (RD->hasUserDeclaredMoveConstructor() && 7080 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7081 if (!Diagnose) return true; 7082 7083 // Find any user-declared move constructor. 7084 for (auto *I : RD->ctors()) { 7085 if (I->isMoveConstructor()) { 7086 UserDeclaredMove = I; 7087 break; 7088 } 7089 } 7090 assert(UserDeclaredMove); 7091 } else if (RD->hasUserDeclaredMoveAssignment() && 7092 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7093 if (!Diagnose) return true; 7094 7095 // Find any user-declared move assignment operator. 7096 for (auto *I : RD->methods()) { 7097 if (I->isMoveAssignmentOperator()) { 7098 UserDeclaredMove = I; 7099 break; 7100 } 7101 } 7102 assert(UserDeclaredMove); 7103 } 7104 7105 if (UserDeclaredMove) { 7106 Diag(UserDeclaredMove->getLocation(), 7107 diag::note_deleted_copy_user_declared_move) 7108 << (CSM == CXXCopyAssignment) << RD 7109 << UserDeclaredMove->isMoveAssignmentOperator(); 7110 return true; 7111 } 7112 } 7113 7114 // Do access control from the special member function 7115 ContextRAII MethodContext(*this, MD); 7116 7117 // C++11 [class.dtor]p5: 7118 // -- for a virtual destructor, lookup of the non-array deallocation function 7119 // results in an ambiguity or in a function that is deleted or inaccessible 7120 if (CSM == CXXDestructor && MD->isVirtual()) { 7121 FunctionDecl *OperatorDelete = nullptr; 7122 DeclarationName Name = 7123 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7124 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7125 OperatorDelete, /*Diagnose*/false)) { 7126 if (Diagnose) 7127 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7128 return true; 7129 } 7130 } 7131 7132 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7133 7134 // Per DR1611, do not consider virtual bases of constructors of abstract 7135 // classes, since we are not going to construct them. 7136 // Per DR1658, do not consider virtual bases of destructors of abstract 7137 // classes either. 7138 // Per DR2180, for assignment operators we only assign (and thus only 7139 // consider) direct bases. 7140 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7141 : SMI.VisitPotentiallyConstructedBases)) 7142 return true; 7143 7144 if (SMI.shouldDeleteForAllConstMembers()) 7145 return true; 7146 7147 if (getLangOpts().CUDA) { 7148 // We should delete the special member in CUDA mode if target inference 7149 // failed. 7150 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 7151 Diagnose); 7152 } 7153 7154 return false; 7155 } 7156 7157 /// Perform lookup for a special member of the specified kind, and determine 7158 /// whether it is trivial. If the triviality can be determined without the 7159 /// lookup, skip it. This is intended for use when determining whether a 7160 /// special member of a containing object is trivial, and thus does not ever 7161 /// perform overload resolution for default constructors. 7162 /// 7163 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7164 /// member that was most likely to be intended to be trivial, if any. 7165 /// 7166 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7167 /// determine whether the special member is trivial. 7168 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7169 Sema::CXXSpecialMember CSM, unsigned Quals, 7170 bool ConstRHS, 7171 Sema::TrivialABIHandling TAH, 7172 CXXMethodDecl **Selected) { 7173 if (Selected) 7174 *Selected = nullptr; 7175 7176 switch (CSM) { 7177 case Sema::CXXInvalid: 7178 llvm_unreachable("not a special member"); 7179 7180 case Sema::CXXDefaultConstructor: 7181 // C++11 [class.ctor]p5: 7182 // A default constructor is trivial if: 7183 // - all the [direct subobjects] have trivial default constructors 7184 // 7185 // Note, no overload resolution is performed in this case. 7186 if (RD->hasTrivialDefaultConstructor()) 7187 return true; 7188 7189 if (Selected) { 7190 // If there's a default constructor which could have been trivial, dig it 7191 // out. Otherwise, if there's any user-provided default constructor, point 7192 // to that as an example of why there's not a trivial one. 7193 CXXConstructorDecl *DefCtor = nullptr; 7194 if (RD->needsImplicitDefaultConstructor()) 7195 S.DeclareImplicitDefaultConstructor(RD); 7196 for (auto *CI : RD->ctors()) { 7197 if (!CI->isDefaultConstructor()) 7198 continue; 7199 DefCtor = CI; 7200 if (!DefCtor->isUserProvided()) 7201 break; 7202 } 7203 7204 *Selected = DefCtor; 7205 } 7206 7207 return false; 7208 7209 case Sema::CXXDestructor: 7210 // C++11 [class.dtor]p5: 7211 // A destructor is trivial if: 7212 // - all the direct [subobjects] have trivial destructors 7213 if (RD->hasTrivialDestructor() || 7214 (TAH == Sema::TAH_ConsiderTrivialABI && 7215 RD->hasTrivialDestructorForCall())) 7216 return true; 7217 7218 if (Selected) { 7219 if (RD->needsImplicitDestructor()) 7220 S.DeclareImplicitDestructor(RD); 7221 *Selected = RD->getDestructor(); 7222 } 7223 7224 return false; 7225 7226 case Sema::CXXCopyConstructor: 7227 // C++11 [class.copy]p12: 7228 // A copy constructor is trivial if: 7229 // - the constructor selected to copy each direct [subobject] is trivial 7230 if (RD->hasTrivialCopyConstructor() || 7231 (TAH == Sema::TAH_ConsiderTrivialABI && 7232 RD->hasTrivialCopyConstructorForCall())) { 7233 if (Quals == Qualifiers::Const) 7234 // We must either select the trivial copy constructor or reach an 7235 // ambiguity; no need to actually perform overload resolution. 7236 return true; 7237 } else if (!Selected) { 7238 return false; 7239 } 7240 // In C++98, we are not supposed to perform overload resolution here, but we 7241 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7242 // cases like B as having a non-trivial copy constructor: 7243 // struct A { template<typename T> A(T&); }; 7244 // struct B { mutable A a; }; 7245 goto NeedOverloadResolution; 7246 7247 case Sema::CXXCopyAssignment: 7248 // C++11 [class.copy]p25: 7249 // A copy assignment operator is trivial if: 7250 // - the assignment operator selected to copy each direct [subobject] is 7251 // trivial 7252 if (RD->hasTrivialCopyAssignment()) { 7253 if (Quals == Qualifiers::Const) 7254 return true; 7255 } else if (!Selected) { 7256 return false; 7257 } 7258 // In C++98, we are not supposed to perform overload resolution here, but we 7259 // treat that as a language defect. 7260 goto NeedOverloadResolution; 7261 7262 case Sema::CXXMoveConstructor: 7263 case Sema::CXXMoveAssignment: 7264 NeedOverloadResolution: 7265 Sema::SpecialMemberOverloadResult SMOR = 7266 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7267 7268 // The standard doesn't describe how to behave if the lookup is ambiguous. 7269 // We treat it as not making the member non-trivial, just like the standard 7270 // mandates for the default constructor. This should rarely matter, because 7271 // the member will also be deleted. 7272 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7273 return true; 7274 7275 if (!SMOR.getMethod()) { 7276 assert(SMOR.getKind() == 7277 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7278 return false; 7279 } 7280 7281 // We deliberately don't check if we found a deleted special member. We're 7282 // not supposed to! 7283 if (Selected) 7284 *Selected = SMOR.getMethod(); 7285 7286 if (TAH == Sema::TAH_ConsiderTrivialABI && 7287 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7288 return SMOR.getMethod()->isTrivialForCall(); 7289 return SMOR.getMethod()->isTrivial(); 7290 } 7291 7292 llvm_unreachable("unknown special method kind"); 7293 } 7294 7295 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7296 for (auto *CI : RD->ctors()) 7297 if (!CI->isImplicit()) 7298 return CI; 7299 7300 // Look for constructor templates. 7301 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7302 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7303 if (CXXConstructorDecl *CD = 7304 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7305 return CD; 7306 } 7307 7308 return nullptr; 7309 } 7310 7311 /// The kind of subobject we are checking for triviality. The values of this 7312 /// enumeration are used in diagnostics. 7313 enum TrivialSubobjectKind { 7314 /// The subobject is a base class. 7315 TSK_BaseClass, 7316 /// The subobject is a non-static data member. 7317 TSK_Field, 7318 /// The object is actually the complete object. 7319 TSK_CompleteObject 7320 }; 7321 7322 /// Check whether the special member selected for a given type would be trivial. 7323 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7324 QualType SubType, bool ConstRHS, 7325 Sema::CXXSpecialMember CSM, 7326 TrivialSubobjectKind Kind, 7327 Sema::TrivialABIHandling TAH, bool Diagnose) { 7328 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7329 if (!SubRD) 7330 return true; 7331 7332 CXXMethodDecl *Selected; 7333 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7334 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7335 return true; 7336 7337 if (Diagnose) { 7338 if (ConstRHS) 7339 SubType.addConst(); 7340 7341 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7342 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7343 << Kind << SubType.getUnqualifiedType(); 7344 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7345 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7346 } else if (!Selected) 7347 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7348 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7349 else if (Selected->isUserProvided()) { 7350 if (Kind == TSK_CompleteObject) 7351 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7352 << Kind << SubType.getUnqualifiedType() << CSM; 7353 else { 7354 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7355 << Kind << SubType.getUnqualifiedType() << CSM; 7356 S.Diag(Selected->getLocation(), diag::note_declared_at); 7357 } 7358 } else { 7359 if (Kind != TSK_CompleteObject) 7360 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7361 << Kind << SubType.getUnqualifiedType() << CSM; 7362 7363 // Explain why the defaulted or deleted special member isn't trivial. 7364 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7365 Diagnose); 7366 } 7367 } 7368 7369 return false; 7370 } 7371 7372 /// Check whether the members of a class type allow a special member to be 7373 /// trivial. 7374 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7375 Sema::CXXSpecialMember CSM, 7376 bool ConstArg, 7377 Sema::TrivialABIHandling TAH, 7378 bool Diagnose) { 7379 for (const auto *FI : RD->fields()) { 7380 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7381 continue; 7382 7383 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7384 7385 // Pretend anonymous struct or union members are members of this class. 7386 if (FI->isAnonymousStructOrUnion()) { 7387 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7388 CSM, ConstArg, TAH, Diagnose)) 7389 return false; 7390 continue; 7391 } 7392 7393 // C++11 [class.ctor]p5: 7394 // A default constructor is trivial if [...] 7395 // -- no non-static data member of its class has a 7396 // brace-or-equal-initializer 7397 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7398 if (Diagnose) 7399 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7400 return false; 7401 } 7402 7403 // Objective C ARC 4.3.5: 7404 // [...] nontrivally ownership-qualified types are [...] not trivially 7405 // default constructible, copy constructible, move constructible, copy 7406 // assignable, move assignable, or destructible [...] 7407 if (FieldType.hasNonTrivialObjCLifetime()) { 7408 if (Diagnose) 7409 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7410 << RD << FieldType.getObjCLifetime(); 7411 return false; 7412 } 7413 7414 bool ConstRHS = ConstArg && !FI->isMutable(); 7415 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7416 CSM, TSK_Field, TAH, Diagnose)) 7417 return false; 7418 } 7419 7420 return true; 7421 } 7422 7423 /// Diagnose why the specified class does not have a trivial special member of 7424 /// the given kind. 7425 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7426 QualType Ty = Context.getRecordType(RD); 7427 7428 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7429 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7430 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7431 /*Diagnose*/true); 7432 } 7433 7434 /// Determine whether a defaulted or deleted special member function is trivial, 7435 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7436 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7437 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7438 TrivialABIHandling TAH, bool Diagnose) { 7439 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7440 7441 CXXRecordDecl *RD = MD->getParent(); 7442 7443 bool ConstArg = false; 7444 7445 // C++11 [class.copy]p12, p25: [DR1593] 7446 // A [special member] is trivial if [...] its parameter-type-list is 7447 // equivalent to the parameter-type-list of an implicit declaration [...] 7448 switch (CSM) { 7449 case CXXDefaultConstructor: 7450 case CXXDestructor: 7451 // Trivial default constructors and destructors cannot have parameters. 7452 break; 7453 7454 case CXXCopyConstructor: 7455 case CXXCopyAssignment: { 7456 // Trivial copy operations always have const, non-volatile parameter types. 7457 ConstArg = true; 7458 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7459 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7460 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7461 if (Diagnose) 7462 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7463 << Param0->getSourceRange() << Param0->getType() 7464 << Context.getLValueReferenceType( 7465 Context.getRecordType(RD).withConst()); 7466 return false; 7467 } 7468 break; 7469 } 7470 7471 case CXXMoveConstructor: 7472 case CXXMoveAssignment: { 7473 // Trivial move operations always have non-cv-qualified parameters. 7474 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7475 const RValueReferenceType *RT = 7476 Param0->getType()->getAs<RValueReferenceType>(); 7477 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7478 if (Diagnose) 7479 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7480 << Param0->getSourceRange() << Param0->getType() 7481 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7482 return false; 7483 } 7484 break; 7485 } 7486 7487 case CXXInvalid: 7488 llvm_unreachable("not a special member"); 7489 } 7490 7491 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7492 if (Diagnose) 7493 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7494 diag::note_nontrivial_default_arg) 7495 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7496 return false; 7497 } 7498 if (MD->isVariadic()) { 7499 if (Diagnose) 7500 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7501 return false; 7502 } 7503 7504 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7505 // A copy/move [constructor or assignment operator] is trivial if 7506 // -- the [member] selected to copy/move each direct base class subobject 7507 // is trivial 7508 // 7509 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7510 // A [default constructor or destructor] is trivial if 7511 // -- all the direct base classes have trivial [default constructors or 7512 // destructors] 7513 for (const auto &BI : RD->bases()) 7514 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7515 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7516 return false; 7517 7518 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7519 // A copy/move [constructor or assignment operator] for a class X is 7520 // trivial if 7521 // -- for each non-static data member of X that is of class type (or array 7522 // thereof), the constructor selected to copy/move that member is 7523 // trivial 7524 // 7525 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7526 // A [default constructor or destructor] is trivial if 7527 // -- for all of the non-static data members of its class that are of class 7528 // type (or array thereof), each such class has a trivial [default 7529 // constructor or destructor] 7530 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7531 return false; 7532 7533 // C++11 [class.dtor]p5: 7534 // A destructor is trivial if [...] 7535 // -- the destructor is not virtual 7536 if (CSM == CXXDestructor && MD->isVirtual()) { 7537 if (Diagnose) 7538 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7539 return false; 7540 } 7541 7542 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7543 // A [special member] for class X is trivial if [...] 7544 // -- class X has no virtual functions and no virtual base classes 7545 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7546 if (!Diagnose) 7547 return false; 7548 7549 if (RD->getNumVBases()) { 7550 // Check for virtual bases. We already know that the corresponding 7551 // member in all bases is trivial, so vbases must all be direct. 7552 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7553 assert(BS.isVirtual()); 7554 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7555 return false; 7556 } 7557 7558 // Must have a virtual method. 7559 for (const auto *MI : RD->methods()) { 7560 if (MI->isVirtual()) { 7561 SourceLocation MLoc = MI->getLocStart(); 7562 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7563 return false; 7564 } 7565 } 7566 7567 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7568 } 7569 7570 // Looks like it's trivial! 7571 return true; 7572 } 7573 7574 namespace { 7575 struct FindHiddenVirtualMethod { 7576 Sema *S; 7577 CXXMethodDecl *Method; 7578 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7579 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7580 7581 private: 7582 /// Check whether any most overriden method from MD in Methods 7583 static bool CheckMostOverridenMethods( 7584 const CXXMethodDecl *MD, 7585 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7586 if (MD->size_overridden_methods() == 0) 7587 return Methods.count(MD->getCanonicalDecl()); 7588 for (const CXXMethodDecl *O : MD->overridden_methods()) 7589 if (CheckMostOverridenMethods(O, Methods)) 7590 return true; 7591 return false; 7592 } 7593 7594 public: 7595 /// Member lookup function that determines whether a given C++ 7596 /// method overloads virtual methods in a base class without overriding any, 7597 /// to be used with CXXRecordDecl::lookupInBases(). 7598 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7599 RecordDecl *BaseRecord = 7600 Specifier->getType()->getAs<RecordType>()->getDecl(); 7601 7602 DeclarationName Name = Method->getDeclName(); 7603 assert(Name.getNameKind() == DeclarationName::Identifier); 7604 7605 bool foundSameNameMethod = false; 7606 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7607 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7608 Path.Decls = Path.Decls.slice(1)) { 7609 NamedDecl *D = Path.Decls.front(); 7610 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7611 MD = MD->getCanonicalDecl(); 7612 foundSameNameMethod = true; 7613 // Interested only in hidden virtual methods. 7614 if (!MD->isVirtual()) 7615 continue; 7616 // If the method we are checking overrides a method from its base 7617 // don't warn about the other overloaded methods. Clang deviates from 7618 // GCC by only diagnosing overloads of inherited virtual functions that 7619 // do not override any other virtual functions in the base. GCC's 7620 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7621 // function from a base class. These cases may be better served by a 7622 // warning (not specific to virtual functions) on call sites when the 7623 // call would select a different function from the base class, were it 7624 // visible. 7625 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7626 if (!S->IsOverload(Method, MD, false)) 7627 return true; 7628 // Collect the overload only if its hidden. 7629 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7630 overloadedMethods.push_back(MD); 7631 } 7632 } 7633 7634 if (foundSameNameMethod) 7635 OverloadedMethods.append(overloadedMethods.begin(), 7636 overloadedMethods.end()); 7637 return foundSameNameMethod; 7638 } 7639 }; 7640 } // end anonymous namespace 7641 7642 /// \brief Add the most overriden methods from MD to Methods 7643 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7644 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7645 if (MD->size_overridden_methods() == 0) 7646 Methods.insert(MD->getCanonicalDecl()); 7647 else 7648 for (const CXXMethodDecl *O : MD->overridden_methods()) 7649 AddMostOverridenMethods(O, Methods); 7650 } 7651 7652 /// \brief Check if a method overloads virtual methods in a base class without 7653 /// overriding any. 7654 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7655 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7656 if (!MD->getDeclName().isIdentifier()) 7657 return; 7658 7659 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7660 /*bool RecordPaths=*/false, 7661 /*bool DetectVirtual=*/false); 7662 FindHiddenVirtualMethod FHVM; 7663 FHVM.Method = MD; 7664 FHVM.S = this; 7665 7666 // Keep the base methods that were overriden or introduced in the subclass 7667 // by 'using' in a set. A base method not in this set is hidden. 7668 CXXRecordDecl *DC = MD->getParent(); 7669 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7670 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7671 NamedDecl *ND = *I; 7672 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7673 ND = shad->getTargetDecl(); 7674 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7675 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7676 } 7677 7678 if (DC->lookupInBases(FHVM, Paths)) 7679 OverloadedMethods = FHVM.OverloadedMethods; 7680 } 7681 7682 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7683 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7684 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7685 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7686 PartialDiagnostic PD = PDiag( 7687 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7688 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7689 Diag(overloadedMD->getLocation(), PD); 7690 } 7691 } 7692 7693 /// \brief Diagnose methods which overload virtual methods in a base class 7694 /// without overriding any. 7695 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7696 if (MD->isInvalidDecl()) 7697 return; 7698 7699 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7700 return; 7701 7702 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7703 FindHiddenVirtualMethods(MD, OverloadedMethods); 7704 if (!OverloadedMethods.empty()) { 7705 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7706 << MD << (OverloadedMethods.size() > 1); 7707 7708 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7709 } 7710 } 7711 7712 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7713 auto PrintDiagAndRemoveAttr = [&]() { 7714 // No diagnostics if this is a template instantiation. 7715 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7716 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7717 diag::ext_cannot_use_trivial_abi) << &RD; 7718 RD.dropAttr<TrivialABIAttr>(); 7719 }; 7720 7721 // Ill-formed if the struct has virtual functions. 7722 if (RD.isPolymorphic()) { 7723 PrintDiagAndRemoveAttr(); 7724 return; 7725 } 7726 7727 for (const auto &B : RD.bases()) { 7728 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7729 // virtual base. 7730 if ((!B.getType()->isDependentType() && 7731 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7732 B.isVirtual()) { 7733 PrintDiagAndRemoveAttr(); 7734 return; 7735 } 7736 } 7737 7738 for (const auto *FD : RD.fields()) { 7739 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7740 // non-trivial for the purpose of calls. 7741 QualType FT = FD->getType(); 7742 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7743 PrintDiagAndRemoveAttr(); 7744 return; 7745 } 7746 7747 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7748 if (!RT->isDependentType() && 7749 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7750 PrintDiagAndRemoveAttr(); 7751 return; 7752 } 7753 } 7754 } 7755 7756 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7757 Decl *TagDecl, 7758 SourceLocation LBrac, 7759 SourceLocation RBrac, 7760 AttributeList *AttrList) { 7761 if (!TagDecl) 7762 return; 7763 7764 AdjustDeclIfTemplate(TagDecl); 7765 7766 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7767 if (l->getKind() != AttributeList::AT_Visibility) 7768 continue; 7769 l->setInvalid(); 7770 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7771 l->getName(); 7772 } 7773 7774 // See if trivial_abi has to be dropped. 7775 auto *RD = dyn_cast<CXXRecordDecl>(TagDecl); 7776 if (RD && RD->hasAttr<TrivialABIAttr>()) 7777 checkIllFormedTrivialABIStruct(*RD); 7778 7779 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7780 // strict aliasing violation! 7781 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7782 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7783 7784 CheckCompletedCXXClass(RD); 7785 } 7786 7787 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7788 /// special functions, such as the default constructor, copy 7789 /// constructor, or destructor, to the given C++ class (C++ 7790 /// [special]p1). This routine can only be executed just before the 7791 /// definition of the class is complete. 7792 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7793 if (ClassDecl->needsImplicitDefaultConstructor()) { 7794 ++ASTContext::NumImplicitDefaultConstructors; 7795 7796 if (ClassDecl->hasInheritedConstructor()) 7797 DeclareImplicitDefaultConstructor(ClassDecl); 7798 } 7799 7800 if (ClassDecl->needsImplicitCopyConstructor()) { 7801 ++ASTContext::NumImplicitCopyConstructors; 7802 7803 // If the properties or semantics of the copy constructor couldn't be 7804 // determined while the class was being declared, force a declaration 7805 // of it now. 7806 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7807 ClassDecl->hasInheritedConstructor()) 7808 DeclareImplicitCopyConstructor(ClassDecl); 7809 // For the MS ABI we need to know whether the copy ctor is deleted. A 7810 // prerequisite for deleting the implicit copy ctor is that the class has a 7811 // move ctor or move assignment that is either user-declared or whose 7812 // semantics are inherited from a subobject. FIXME: We should provide a more 7813 // direct way for CodeGen to ask whether the constructor was deleted. 7814 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7815 (ClassDecl->hasUserDeclaredMoveConstructor() || 7816 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7817 ClassDecl->hasUserDeclaredMoveAssignment() || 7818 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7819 DeclareImplicitCopyConstructor(ClassDecl); 7820 } 7821 7822 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7823 ++ASTContext::NumImplicitMoveConstructors; 7824 7825 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7826 ClassDecl->hasInheritedConstructor()) 7827 DeclareImplicitMoveConstructor(ClassDecl); 7828 } 7829 7830 if (ClassDecl->needsImplicitCopyAssignment()) { 7831 ++ASTContext::NumImplicitCopyAssignmentOperators; 7832 7833 // If we have a dynamic class, then the copy assignment operator may be 7834 // virtual, so we have to declare it immediately. This ensures that, e.g., 7835 // it shows up in the right place in the vtable and that we diagnose 7836 // problems with the implicit exception specification. 7837 if (ClassDecl->isDynamicClass() || 7838 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7839 ClassDecl->hasInheritedAssignment()) 7840 DeclareImplicitCopyAssignment(ClassDecl); 7841 } 7842 7843 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7844 ++ASTContext::NumImplicitMoveAssignmentOperators; 7845 7846 // Likewise for the move assignment operator. 7847 if (ClassDecl->isDynamicClass() || 7848 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7849 ClassDecl->hasInheritedAssignment()) 7850 DeclareImplicitMoveAssignment(ClassDecl); 7851 } 7852 7853 if (ClassDecl->needsImplicitDestructor()) { 7854 ++ASTContext::NumImplicitDestructors; 7855 7856 // If we have a dynamic class, then the destructor may be virtual, so we 7857 // have to declare the destructor immediately. This ensures that, e.g., it 7858 // shows up in the right place in the vtable and that we diagnose problems 7859 // with the implicit exception specification. 7860 if (ClassDecl->isDynamicClass() || 7861 ClassDecl->needsOverloadResolutionForDestructor()) 7862 DeclareImplicitDestructor(ClassDecl); 7863 } 7864 } 7865 7866 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7867 if (!D) 7868 return 0; 7869 7870 // The order of template parameters is not important here. All names 7871 // get added to the same scope. 7872 SmallVector<TemplateParameterList *, 4> ParameterLists; 7873 7874 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7875 D = TD->getTemplatedDecl(); 7876 7877 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7878 ParameterLists.push_back(PSD->getTemplateParameters()); 7879 7880 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7881 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7882 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7883 7884 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7885 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7886 ParameterLists.push_back(FTD->getTemplateParameters()); 7887 } 7888 } 7889 7890 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7891 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7892 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7893 7894 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7895 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7896 ParameterLists.push_back(CTD->getTemplateParameters()); 7897 } 7898 } 7899 7900 unsigned Count = 0; 7901 for (TemplateParameterList *Params : ParameterLists) { 7902 if (Params->size() > 0) 7903 // Ignore explicit specializations; they don't contribute to the template 7904 // depth. 7905 ++Count; 7906 for (NamedDecl *Param : *Params) { 7907 if (Param->getDeclName()) { 7908 S->AddDecl(Param); 7909 IdResolver.AddDecl(Param); 7910 } 7911 } 7912 } 7913 7914 return Count; 7915 } 7916 7917 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7918 if (!RecordD) return; 7919 AdjustDeclIfTemplate(RecordD); 7920 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7921 PushDeclContext(S, Record); 7922 } 7923 7924 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7925 if (!RecordD) return; 7926 PopDeclContext(); 7927 } 7928 7929 /// This is used to implement the constant expression evaluation part of the 7930 /// attribute enable_if extension. There is nothing in standard C++ which would 7931 /// require reentering parameters. 7932 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7933 if (!Param) 7934 return; 7935 7936 S->AddDecl(Param); 7937 if (Param->getDeclName()) 7938 IdResolver.AddDecl(Param); 7939 } 7940 7941 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7942 /// parsing a top-level (non-nested) C++ class, and we are now 7943 /// parsing those parts of the given Method declaration that could 7944 /// not be parsed earlier (C++ [class.mem]p2), such as default 7945 /// arguments. This action should enter the scope of the given 7946 /// Method declaration as if we had just parsed the qualified method 7947 /// name. However, it should not bring the parameters into scope; 7948 /// that will be performed by ActOnDelayedCXXMethodParameter. 7949 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7950 } 7951 7952 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7953 /// C++ method declaration. We're (re-)introducing the given 7954 /// function parameter into scope for use in parsing later parts of 7955 /// the method declaration. For example, we could see an 7956 /// ActOnParamDefaultArgument event for this parameter. 7957 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7958 if (!ParamD) 7959 return; 7960 7961 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7962 7963 // If this parameter has an unparsed default argument, clear it out 7964 // to make way for the parsed default argument. 7965 if (Param->hasUnparsedDefaultArg()) 7966 Param->setDefaultArg(nullptr); 7967 7968 S->AddDecl(Param); 7969 if (Param->getDeclName()) 7970 IdResolver.AddDecl(Param); 7971 } 7972 7973 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7974 /// processing the delayed method declaration for Method. The method 7975 /// declaration is now considered finished. There may be a separate 7976 /// ActOnStartOfFunctionDef action later (not necessarily 7977 /// immediately!) for this method, if it was also defined inside the 7978 /// class body. 7979 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7980 if (!MethodD) 7981 return; 7982 7983 AdjustDeclIfTemplate(MethodD); 7984 7985 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7986 7987 // Now that we have our default arguments, check the constructor 7988 // again. It could produce additional diagnostics or affect whether 7989 // the class has implicitly-declared destructors, among other 7990 // things. 7991 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7992 CheckConstructor(Constructor); 7993 7994 // Check the default arguments, which we may have added. 7995 if (!Method->isInvalidDecl()) 7996 CheckCXXDefaultArguments(Method); 7997 } 7998 7999 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8000 /// the well-formedness of the constructor declarator @p D with type @p 8001 /// R. If there are any errors in the declarator, this routine will 8002 /// emit diagnostics and set the invalid bit to true. In any case, the type 8003 /// will be updated to reflect a well-formed type for the constructor and 8004 /// returned. 8005 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8006 StorageClass &SC) { 8007 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8008 8009 // C++ [class.ctor]p3: 8010 // A constructor shall not be virtual (10.3) or static (9.4). A 8011 // constructor can be invoked for a const, volatile or const 8012 // volatile object. A constructor shall not be declared const, 8013 // volatile, or const volatile (9.3.2). 8014 if (isVirtual) { 8015 if (!D.isInvalidType()) 8016 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8017 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8018 << SourceRange(D.getIdentifierLoc()); 8019 D.setInvalidType(); 8020 } 8021 if (SC == SC_Static) { 8022 if (!D.isInvalidType()) 8023 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8024 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8025 << SourceRange(D.getIdentifierLoc()); 8026 D.setInvalidType(); 8027 SC = SC_None; 8028 } 8029 8030 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8031 diagnoseIgnoredQualifiers( 8032 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8033 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8034 D.getDeclSpec().getRestrictSpecLoc(), 8035 D.getDeclSpec().getAtomicSpecLoc()); 8036 D.setInvalidType(); 8037 } 8038 8039 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8040 if (FTI.TypeQuals != 0) { 8041 if (FTI.TypeQuals & Qualifiers::Const) 8042 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8043 << "const" << SourceRange(D.getIdentifierLoc()); 8044 if (FTI.TypeQuals & Qualifiers::Volatile) 8045 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8046 << "volatile" << SourceRange(D.getIdentifierLoc()); 8047 if (FTI.TypeQuals & Qualifiers::Restrict) 8048 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8049 << "restrict" << SourceRange(D.getIdentifierLoc()); 8050 D.setInvalidType(); 8051 } 8052 8053 // C++0x [class.ctor]p4: 8054 // A constructor shall not be declared with a ref-qualifier. 8055 if (FTI.hasRefQualifier()) { 8056 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8057 << FTI.RefQualifierIsLValueRef 8058 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8059 D.setInvalidType(); 8060 } 8061 8062 // Rebuild the function type "R" without any type qualifiers (in 8063 // case any of the errors above fired) and with "void" as the 8064 // return type, since constructors don't have return types. 8065 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8066 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8067 return R; 8068 8069 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8070 EPI.TypeQuals = 0; 8071 EPI.RefQualifier = RQ_None; 8072 8073 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8074 } 8075 8076 /// CheckConstructor - Checks a fully-formed constructor for 8077 /// well-formedness, issuing any diagnostics required. Returns true if 8078 /// the constructor declarator is invalid. 8079 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8080 CXXRecordDecl *ClassDecl 8081 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8082 if (!ClassDecl) 8083 return Constructor->setInvalidDecl(); 8084 8085 // C++ [class.copy]p3: 8086 // A declaration of a constructor for a class X is ill-formed if 8087 // its first parameter is of type (optionally cv-qualified) X and 8088 // either there are no other parameters or else all other 8089 // parameters have default arguments. 8090 if (!Constructor->isInvalidDecl() && 8091 ((Constructor->getNumParams() == 1) || 8092 (Constructor->getNumParams() > 1 && 8093 Constructor->getParamDecl(1)->hasDefaultArg())) && 8094 Constructor->getTemplateSpecializationKind() 8095 != TSK_ImplicitInstantiation) { 8096 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8097 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8098 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8099 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8100 const char *ConstRef 8101 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8102 : " const &"; 8103 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8104 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8105 8106 // FIXME: Rather that making the constructor invalid, we should endeavor 8107 // to fix the type. 8108 Constructor->setInvalidDecl(); 8109 } 8110 } 8111 } 8112 8113 /// CheckDestructor - Checks a fully-formed destructor definition for 8114 /// well-formedness, issuing any diagnostics required. Returns true 8115 /// on error. 8116 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8117 CXXRecordDecl *RD = Destructor->getParent(); 8118 8119 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8120 SourceLocation Loc; 8121 8122 if (!Destructor->isImplicit()) 8123 Loc = Destructor->getLocation(); 8124 else 8125 Loc = RD->getLocation(); 8126 8127 // If we have a virtual destructor, look up the deallocation function 8128 if (FunctionDecl *OperatorDelete = 8129 FindDeallocationFunctionForDestructor(Loc, RD)) { 8130 Expr *ThisArg = nullptr; 8131 8132 // If the notional 'delete this' expression requires a non-trivial 8133 // conversion from 'this' to the type of a destroying operator delete's 8134 // first parameter, perform that conversion now. 8135 if (OperatorDelete->isDestroyingOperatorDelete()) { 8136 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8137 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8138 // C++ [class.dtor]p13: 8139 // ... as if for the expression 'delete this' appearing in a 8140 // non-virtual destructor of the destructor's class. 8141 ContextRAII SwitchContext(*this, Destructor); 8142 ExprResult This = 8143 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8144 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8145 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8146 if (This.isInvalid()) { 8147 // FIXME: Register this as a context note so that it comes out 8148 // in the right order. 8149 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8150 return true; 8151 } 8152 ThisArg = This.get(); 8153 } 8154 } 8155 8156 MarkFunctionReferenced(Loc, OperatorDelete); 8157 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8158 } 8159 } 8160 8161 return false; 8162 } 8163 8164 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8165 /// the well-formednes of the destructor declarator @p D with type @p 8166 /// R. If there are any errors in the declarator, this routine will 8167 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8168 /// will be updated to reflect a well-formed type for the destructor and 8169 /// returned. 8170 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8171 StorageClass& SC) { 8172 // C++ [class.dtor]p1: 8173 // [...] A typedef-name that names a class is a class-name 8174 // (7.1.3); however, a typedef-name that names a class shall not 8175 // be used as the identifier in the declarator for a destructor 8176 // declaration. 8177 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8178 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8179 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8180 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8181 else if (const TemplateSpecializationType *TST = 8182 DeclaratorType->getAs<TemplateSpecializationType>()) 8183 if (TST->isTypeAlias()) 8184 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8185 << DeclaratorType << 1; 8186 8187 // C++ [class.dtor]p2: 8188 // A destructor is used to destroy objects of its class type. A 8189 // destructor takes no parameters, and no return type can be 8190 // specified for it (not even void). The address of a destructor 8191 // shall not be taken. A destructor shall not be static. A 8192 // destructor can be invoked for a const, volatile or const 8193 // volatile object. A destructor shall not be declared const, 8194 // volatile or const volatile (9.3.2). 8195 if (SC == SC_Static) { 8196 if (!D.isInvalidType()) 8197 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8198 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8199 << SourceRange(D.getIdentifierLoc()) 8200 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8201 8202 SC = SC_None; 8203 } 8204 if (!D.isInvalidType()) { 8205 // Destructors don't have return types, but the parser will 8206 // happily parse something like: 8207 // 8208 // class X { 8209 // float ~X(); 8210 // }; 8211 // 8212 // The return type will be eliminated later. 8213 if (D.getDeclSpec().hasTypeSpecifier()) 8214 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8215 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8216 << SourceRange(D.getIdentifierLoc()); 8217 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8218 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8219 SourceLocation(), 8220 D.getDeclSpec().getConstSpecLoc(), 8221 D.getDeclSpec().getVolatileSpecLoc(), 8222 D.getDeclSpec().getRestrictSpecLoc(), 8223 D.getDeclSpec().getAtomicSpecLoc()); 8224 D.setInvalidType(); 8225 } 8226 } 8227 8228 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8229 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 8230 if (FTI.TypeQuals & Qualifiers::Const) 8231 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8232 << "const" << SourceRange(D.getIdentifierLoc()); 8233 if (FTI.TypeQuals & Qualifiers::Volatile) 8234 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8235 << "volatile" << SourceRange(D.getIdentifierLoc()); 8236 if (FTI.TypeQuals & Qualifiers::Restrict) 8237 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8238 << "restrict" << SourceRange(D.getIdentifierLoc()); 8239 D.setInvalidType(); 8240 } 8241 8242 // C++0x [class.dtor]p2: 8243 // A destructor shall not be declared with a ref-qualifier. 8244 if (FTI.hasRefQualifier()) { 8245 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8246 << FTI.RefQualifierIsLValueRef 8247 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8248 D.setInvalidType(); 8249 } 8250 8251 // Make sure we don't have any parameters. 8252 if (FTIHasNonVoidParameters(FTI)) { 8253 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8254 8255 // Delete the parameters. 8256 FTI.freeParams(); 8257 D.setInvalidType(); 8258 } 8259 8260 // Make sure the destructor isn't variadic. 8261 if (FTI.isVariadic) { 8262 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8263 D.setInvalidType(); 8264 } 8265 8266 // Rebuild the function type "R" without any type qualifiers or 8267 // parameters (in case any of the errors above fired) and with 8268 // "void" as the return type, since destructors don't have return 8269 // types. 8270 if (!D.isInvalidType()) 8271 return R; 8272 8273 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8274 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8275 EPI.Variadic = false; 8276 EPI.TypeQuals = 0; 8277 EPI.RefQualifier = RQ_None; 8278 return Context.getFunctionType(Context.VoidTy, None, EPI); 8279 } 8280 8281 static void extendLeft(SourceRange &R, SourceRange Before) { 8282 if (Before.isInvalid()) 8283 return; 8284 R.setBegin(Before.getBegin()); 8285 if (R.getEnd().isInvalid()) 8286 R.setEnd(Before.getEnd()); 8287 } 8288 8289 static void extendRight(SourceRange &R, SourceRange After) { 8290 if (After.isInvalid()) 8291 return; 8292 if (R.getBegin().isInvalid()) 8293 R.setBegin(After.getBegin()); 8294 R.setEnd(After.getEnd()); 8295 } 8296 8297 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8298 /// well-formednes of the conversion function declarator @p D with 8299 /// type @p R. If there are any errors in the declarator, this routine 8300 /// will emit diagnostics and return true. Otherwise, it will return 8301 /// false. Either way, the type @p R will be updated to reflect a 8302 /// well-formed type for the conversion operator. 8303 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8304 StorageClass& SC) { 8305 // C++ [class.conv.fct]p1: 8306 // Neither parameter types nor return type can be specified. The 8307 // type of a conversion function (8.3.5) is "function taking no 8308 // parameter returning conversion-type-id." 8309 if (SC == SC_Static) { 8310 if (!D.isInvalidType()) 8311 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8312 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8313 << D.getName().getSourceRange(); 8314 D.setInvalidType(); 8315 SC = SC_None; 8316 } 8317 8318 TypeSourceInfo *ConvTSI = nullptr; 8319 QualType ConvType = 8320 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8321 8322 const DeclSpec &DS = D.getDeclSpec(); 8323 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8324 // Conversion functions don't have return types, but the parser will 8325 // happily parse something like: 8326 // 8327 // class X { 8328 // float operator bool(); 8329 // }; 8330 // 8331 // The return type will be changed later anyway. 8332 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8333 << SourceRange(DS.getTypeSpecTypeLoc()) 8334 << SourceRange(D.getIdentifierLoc()); 8335 D.setInvalidType(); 8336 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8337 // It's also plausible that the user writes type qualifiers in the wrong 8338 // place, such as: 8339 // struct S { const operator int(); }; 8340 // FIXME: we could provide a fixit to move the qualifiers onto the 8341 // conversion type. 8342 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8343 << SourceRange(D.getIdentifierLoc()) << 0; 8344 D.setInvalidType(); 8345 } 8346 8347 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8348 8349 // Make sure we don't have any parameters. 8350 if (Proto->getNumParams() > 0) { 8351 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8352 8353 // Delete the parameters. 8354 D.getFunctionTypeInfo().freeParams(); 8355 D.setInvalidType(); 8356 } else if (Proto->isVariadic()) { 8357 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8358 D.setInvalidType(); 8359 } 8360 8361 // Diagnose "&operator bool()" and other such nonsense. This 8362 // is actually a gcc extension which we don't support. 8363 if (Proto->getReturnType() != ConvType) { 8364 bool NeedsTypedef = false; 8365 SourceRange Before, After; 8366 8367 // Walk the chunks and extract information on them for our diagnostic. 8368 bool PastFunctionChunk = false; 8369 for (auto &Chunk : D.type_objects()) { 8370 switch (Chunk.Kind) { 8371 case DeclaratorChunk::Function: 8372 if (!PastFunctionChunk) { 8373 if (Chunk.Fun.HasTrailingReturnType) { 8374 TypeSourceInfo *TRT = nullptr; 8375 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8376 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8377 } 8378 PastFunctionChunk = true; 8379 break; 8380 } 8381 LLVM_FALLTHROUGH; 8382 case DeclaratorChunk::Array: 8383 NeedsTypedef = true; 8384 extendRight(After, Chunk.getSourceRange()); 8385 break; 8386 8387 case DeclaratorChunk::Pointer: 8388 case DeclaratorChunk::BlockPointer: 8389 case DeclaratorChunk::Reference: 8390 case DeclaratorChunk::MemberPointer: 8391 case DeclaratorChunk::Pipe: 8392 extendLeft(Before, Chunk.getSourceRange()); 8393 break; 8394 8395 case DeclaratorChunk::Paren: 8396 extendLeft(Before, Chunk.Loc); 8397 extendRight(After, Chunk.EndLoc); 8398 break; 8399 } 8400 } 8401 8402 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8403 After.isValid() ? After.getBegin() : 8404 D.getIdentifierLoc(); 8405 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8406 DB << Before << After; 8407 8408 if (!NeedsTypedef) { 8409 DB << /*don't need a typedef*/0; 8410 8411 // If we can provide a correct fix-it hint, do so. 8412 if (After.isInvalid() && ConvTSI) { 8413 SourceLocation InsertLoc = 8414 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8415 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8416 << FixItHint::CreateInsertionFromRange( 8417 InsertLoc, CharSourceRange::getTokenRange(Before)) 8418 << FixItHint::CreateRemoval(Before); 8419 } 8420 } else if (!Proto->getReturnType()->isDependentType()) { 8421 DB << /*typedef*/1 << Proto->getReturnType(); 8422 } else if (getLangOpts().CPlusPlus11) { 8423 DB << /*alias template*/2 << Proto->getReturnType(); 8424 } else { 8425 DB << /*might not be fixable*/3; 8426 } 8427 8428 // Recover by incorporating the other type chunks into the result type. 8429 // Note, this does *not* change the name of the function. This is compatible 8430 // with the GCC extension: 8431 // struct S { &operator int(); } s; 8432 // int &r = s.operator int(); // ok in GCC 8433 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8434 ConvType = Proto->getReturnType(); 8435 } 8436 8437 // C++ [class.conv.fct]p4: 8438 // The conversion-type-id shall not represent a function type nor 8439 // an array type. 8440 if (ConvType->isArrayType()) { 8441 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8442 ConvType = Context.getPointerType(ConvType); 8443 D.setInvalidType(); 8444 } else if (ConvType->isFunctionType()) { 8445 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8446 ConvType = Context.getPointerType(ConvType); 8447 D.setInvalidType(); 8448 } 8449 8450 // Rebuild the function type "R" without any parameters (in case any 8451 // of the errors above fired) and with the conversion type as the 8452 // return type. 8453 if (D.isInvalidType()) 8454 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8455 8456 // C++0x explicit conversion operators. 8457 if (DS.isExplicitSpecified()) 8458 Diag(DS.getExplicitSpecLoc(), 8459 getLangOpts().CPlusPlus11 8460 ? diag::warn_cxx98_compat_explicit_conversion_functions 8461 : diag::ext_explicit_conversion_functions) 8462 << SourceRange(DS.getExplicitSpecLoc()); 8463 } 8464 8465 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8466 /// the declaration of the given C++ conversion function. This routine 8467 /// is responsible for recording the conversion function in the C++ 8468 /// class, if possible. 8469 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8470 assert(Conversion && "Expected to receive a conversion function declaration"); 8471 8472 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8473 8474 // Make sure we aren't redeclaring the conversion function. 8475 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8476 8477 // C++ [class.conv.fct]p1: 8478 // [...] A conversion function is never used to convert a 8479 // (possibly cv-qualified) object to the (possibly cv-qualified) 8480 // same object type (or a reference to it), to a (possibly 8481 // cv-qualified) base class of that type (or a reference to it), 8482 // or to (possibly cv-qualified) void. 8483 // FIXME: Suppress this warning if the conversion function ends up being a 8484 // virtual function that overrides a virtual function in a base class. 8485 QualType ClassType 8486 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8487 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8488 ConvType = ConvTypeRef->getPointeeType(); 8489 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8490 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8491 /* Suppress diagnostics for instantiations. */; 8492 else if (ConvType->isRecordType()) { 8493 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8494 if (ConvType == ClassType) 8495 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8496 << ClassType; 8497 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8498 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8499 << ClassType << ConvType; 8500 } else if (ConvType->isVoidType()) { 8501 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8502 << ClassType << ConvType; 8503 } 8504 8505 if (FunctionTemplateDecl *ConversionTemplate 8506 = Conversion->getDescribedFunctionTemplate()) 8507 return ConversionTemplate; 8508 8509 return Conversion; 8510 } 8511 8512 namespace { 8513 /// Utility class to accumulate and print a diagnostic listing the invalid 8514 /// specifier(s) on a declaration. 8515 struct BadSpecifierDiagnoser { 8516 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8517 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8518 ~BadSpecifierDiagnoser() { 8519 Diagnostic << Specifiers; 8520 } 8521 8522 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8523 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8524 } 8525 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8526 return check(SpecLoc, 8527 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8528 } 8529 void check(SourceLocation SpecLoc, const char *Spec) { 8530 if (SpecLoc.isInvalid()) return; 8531 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8532 if (!Specifiers.empty()) Specifiers += " "; 8533 Specifiers += Spec; 8534 } 8535 8536 Sema &S; 8537 Sema::SemaDiagnosticBuilder Diagnostic; 8538 std::string Specifiers; 8539 }; 8540 } 8541 8542 /// Check the validity of a declarator that we parsed for a deduction-guide. 8543 /// These aren't actually declarators in the grammar, so we need to check that 8544 /// the user didn't specify any pieces that are not part of the deduction-guide 8545 /// grammar. 8546 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8547 StorageClass &SC) { 8548 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8549 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8550 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8551 8552 // C++ [temp.deduct.guide]p3: 8553 // A deduction-gide shall be declared in the same scope as the 8554 // corresponding class template. 8555 if (!CurContext->getRedeclContext()->Equals( 8556 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8557 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8558 << GuidedTemplateDecl; 8559 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8560 } 8561 8562 auto &DS = D.getMutableDeclSpec(); 8563 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8564 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8565 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8566 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8567 BadSpecifierDiagnoser Diagnoser( 8568 *this, D.getIdentifierLoc(), 8569 diag::err_deduction_guide_invalid_specifier); 8570 8571 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8572 DS.ClearStorageClassSpecs(); 8573 SC = SC_None; 8574 8575 // 'explicit' is permitted. 8576 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8577 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8578 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8579 DS.ClearConstexprSpec(); 8580 8581 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8582 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8583 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8584 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8585 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8586 DS.ClearTypeQualifiers(); 8587 8588 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8589 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8590 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8591 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8592 DS.ClearTypeSpecType(); 8593 } 8594 8595 if (D.isInvalidType()) 8596 return; 8597 8598 // Check the declarator is simple enough. 8599 bool FoundFunction = false; 8600 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8601 if (Chunk.Kind == DeclaratorChunk::Paren) 8602 continue; 8603 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8604 Diag(D.getDeclSpec().getLocStart(), 8605 diag::err_deduction_guide_with_complex_decl) 8606 << D.getSourceRange(); 8607 break; 8608 } 8609 if (!Chunk.Fun.hasTrailingReturnType()) { 8610 Diag(D.getName().getLocStart(), 8611 diag::err_deduction_guide_no_trailing_return_type); 8612 break; 8613 } 8614 8615 // Check that the return type is written as a specialization of 8616 // the template specified as the deduction-guide's name. 8617 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8618 TypeSourceInfo *TSI = nullptr; 8619 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8620 assert(TSI && "deduction guide has valid type but invalid return type?"); 8621 bool AcceptableReturnType = false; 8622 bool MightInstantiateToSpecialization = false; 8623 if (auto RetTST = 8624 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8625 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8626 bool TemplateMatches = 8627 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8628 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8629 AcceptableReturnType = true; 8630 else { 8631 // This could still instantiate to the right type, unless we know it 8632 // names the wrong class template. 8633 auto *TD = SpecifiedName.getAsTemplateDecl(); 8634 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8635 !TemplateMatches); 8636 } 8637 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8638 MightInstantiateToSpecialization = true; 8639 } 8640 8641 if (!AcceptableReturnType) { 8642 Diag(TSI->getTypeLoc().getLocStart(), 8643 diag::err_deduction_guide_bad_trailing_return_type) 8644 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8645 << TSI->getTypeLoc().getSourceRange(); 8646 } 8647 8648 // Keep going to check that we don't have any inner declarator pieces (we 8649 // could still have a function returning a pointer to a function). 8650 FoundFunction = true; 8651 } 8652 8653 if (D.isFunctionDefinition()) 8654 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8655 } 8656 8657 //===----------------------------------------------------------------------===// 8658 // Namespace Handling 8659 //===----------------------------------------------------------------------===// 8660 8661 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8662 /// reopened. 8663 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8664 SourceLocation Loc, 8665 IdentifierInfo *II, bool *IsInline, 8666 NamespaceDecl *PrevNS) { 8667 assert(*IsInline != PrevNS->isInline()); 8668 8669 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8670 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8671 // inline namespaces, with the intention of bringing names into namespace std. 8672 // 8673 // We support this just well enough to get that case working; this is not 8674 // sufficient to support reopening namespaces as inline in general. 8675 if (*IsInline && II && II->getName().startswith("__atomic") && 8676 S.getSourceManager().isInSystemHeader(Loc)) { 8677 // Mark all prior declarations of the namespace as inline. 8678 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8679 NS = NS->getPreviousDecl()) 8680 NS->setInline(*IsInline); 8681 // Patch up the lookup table for the containing namespace. This isn't really 8682 // correct, but it's good enough for this particular case. 8683 for (auto *I : PrevNS->decls()) 8684 if (auto *ND = dyn_cast<NamedDecl>(I)) 8685 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8686 return; 8687 } 8688 8689 if (PrevNS->isInline()) 8690 // The user probably just forgot the 'inline', so suggest that it 8691 // be added back. 8692 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8693 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8694 else 8695 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8696 8697 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8698 *IsInline = PrevNS->isInline(); 8699 } 8700 8701 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8702 /// definition. 8703 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8704 SourceLocation InlineLoc, 8705 SourceLocation NamespaceLoc, 8706 SourceLocation IdentLoc, 8707 IdentifierInfo *II, 8708 SourceLocation LBrace, 8709 AttributeList *AttrList, 8710 UsingDirectiveDecl *&UD) { 8711 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8712 // For anonymous namespace, take the location of the left brace. 8713 SourceLocation Loc = II ? IdentLoc : LBrace; 8714 bool IsInline = InlineLoc.isValid(); 8715 bool IsInvalid = false; 8716 bool IsStd = false; 8717 bool AddToKnown = false; 8718 Scope *DeclRegionScope = NamespcScope->getParent(); 8719 8720 NamespaceDecl *PrevNS = nullptr; 8721 if (II) { 8722 // C++ [namespace.def]p2: 8723 // The identifier in an original-namespace-definition shall not 8724 // have been previously defined in the declarative region in 8725 // which the original-namespace-definition appears. The 8726 // identifier in an original-namespace-definition is the name of 8727 // the namespace. Subsequently in that declarative region, it is 8728 // treated as an original-namespace-name. 8729 // 8730 // Since namespace names are unique in their scope, and we don't 8731 // look through using directives, just look for any ordinary names 8732 // as if by qualified name lookup. 8733 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8734 ForExternalRedeclaration); 8735 LookupQualifiedName(R, CurContext->getRedeclContext()); 8736 NamedDecl *PrevDecl = 8737 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8738 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8739 8740 if (PrevNS) { 8741 // This is an extended namespace definition. 8742 if (IsInline != PrevNS->isInline()) 8743 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8744 &IsInline, PrevNS); 8745 } else if (PrevDecl) { 8746 // This is an invalid name redefinition. 8747 Diag(Loc, diag::err_redefinition_different_kind) 8748 << II; 8749 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8750 IsInvalid = true; 8751 // Continue on to push Namespc as current DeclContext and return it. 8752 } else if (II->isStr("std") && 8753 CurContext->getRedeclContext()->isTranslationUnit()) { 8754 // This is the first "real" definition of the namespace "std", so update 8755 // our cache of the "std" namespace to point at this definition. 8756 PrevNS = getStdNamespace(); 8757 IsStd = true; 8758 AddToKnown = !IsInline; 8759 } else { 8760 // We've seen this namespace for the first time. 8761 AddToKnown = !IsInline; 8762 } 8763 } else { 8764 // Anonymous namespaces. 8765 8766 // Determine whether the parent already has an anonymous namespace. 8767 DeclContext *Parent = CurContext->getRedeclContext(); 8768 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8769 PrevNS = TU->getAnonymousNamespace(); 8770 } else { 8771 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8772 PrevNS = ND->getAnonymousNamespace(); 8773 } 8774 8775 if (PrevNS && IsInline != PrevNS->isInline()) 8776 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8777 &IsInline, PrevNS); 8778 } 8779 8780 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8781 StartLoc, Loc, II, PrevNS); 8782 if (IsInvalid) 8783 Namespc->setInvalidDecl(); 8784 8785 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8786 AddPragmaAttributes(DeclRegionScope, Namespc); 8787 8788 // FIXME: Should we be merging attributes? 8789 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8790 PushNamespaceVisibilityAttr(Attr, Loc); 8791 8792 if (IsStd) 8793 StdNamespace = Namespc; 8794 if (AddToKnown) 8795 KnownNamespaces[Namespc] = false; 8796 8797 if (II) { 8798 PushOnScopeChains(Namespc, DeclRegionScope); 8799 } else { 8800 // Link the anonymous namespace into its parent. 8801 DeclContext *Parent = CurContext->getRedeclContext(); 8802 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8803 TU->setAnonymousNamespace(Namespc); 8804 } else { 8805 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8806 } 8807 8808 CurContext->addDecl(Namespc); 8809 8810 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8811 // behaves as if it were replaced by 8812 // namespace unique { /* empty body */ } 8813 // using namespace unique; 8814 // namespace unique { namespace-body } 8815 // where all occurrences of 'unique' in a translation unit are 8816 // replaced by the same identifier and this identifier differs 8817 // from all other identifiers in the entire program. 8818 8819 // We just create the namespace with an empty name and then add an 8820 // implicit using declaration, just like the standard suggests. 8821 // 8822 // CodeGen enforces the "universally unique" aspect by giving all 8823 // declarations semantically contained within an anonymous 8824 // namespace internal linkage. 8825 8826 if (!PrevNS) { 8827 UD = UsingDirectiveDecl::Create(Context, Parent, 8828 /* 'using' */ LBrace, 8829 /* 'namespace' */ SourceLocation(), 8830 /* qualifier */ NestedNameSpecifierLoc(), 8831 /* identifier */ SourceLocation(), 8832 Namespc, 8833 /* Ancestor */ Parent); 8834 UD->setImplicit(); 8835 Parent->addDecl(UD); 8836 } 8837 } 8838 8839 ActOnDocumentableDecl(Namespc); 8840 8841 // Although we could have an invalid decl (i.e. the namespace name is a 8842 // redefinition), push it as current DeclContext and try to continue parsing. 8843 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8844 // for the namespace has the declarations that showed up in that particular 8845 // namespace definition. 8846 PushDeclContext(NamespcScope, Namespc); 8847 return Namespc; 8848 } 8849 8850 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8851 /// is a namespace alias, returns the namespace it points to. 8852 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8853 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8854 return AD->getNamespace(); 8855 return dyn_cast_or_null<NamespaceDecl>(D); 8856 } 8857 8858 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8859 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8860 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8861 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8862 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8863 Namespc->setRBraceLoc(RBrace); 8864 PopDeclContext(); 8865 if (Namespc->hasAttr<VisibilityAttr>()) 8866 PopPragmaVisibility(true, RBrace); 8867 } 8868 8869 CXXRecordDecl *Sema::getStdBadAlloc() const { 8870 return cast_or_null<CXXRecordDecl>( 8871 StdBadAlloc.get(Context.getExternalSource())); 8872 } 8873 8874 EnumDecl *Sema::getStdAlignValT() const { 8875 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8876 } 8877 8878 NamespaceDecl *Sema::getStdNamespace() const { 8879 return cast_or_null<NamespaceDecl>( 8880 StdNamespace.get(Context.getExternalSource())); 8881 } 8882 8883 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8884 if (!StdExperimentalNamespaceCache) { 8885 if (auto Std = getStdNamespace()) { 8886 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8887 SourceLocation(), LookupNamespaceName); 8888 if (!LookupQualifiedName(Result, Std) || 8889 !(StdExperimentalNamespaceCache = 8890 Result.getAsSingle<NamespaceDecl>())) 8891 Result.suppressDiagnostics(); 8892 } 8893 } 8894 return StdExperimentalNamespaceCache; 8895 } 8896 8897 /// \brief Retrieve the special "std" namespace, which may require us to 8898 /// implicitly define the namespace. 8899 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8900 if (!StdNamespace) { 8901 // The "std" namespace has not yet been defined, so build one implicitly. 8902 StdNamespace = NamespaceDecl::Create(Context, 8903 Context.getTranslationUnitDecl(), 8904 /*Inline=*/false, 8905 SourceLocation(), SourceLocation(), 8906 &PP.getIdentifierTable().get("std"), 8907 /*PrevDecl=*/nullptr); 8908 getStdNamespace()->setImplicit(true); 8909 } 8910 8911 return getStdNamespace(); 8912 } 8913 8914 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8915 assert(getLangOpts().CPlusPlus && 8916 "Looking for std::initializer_list outside of C++."); 8917 8918 // We're looking for implicit instantiations of 8919 // template <typename E> class std::initializer_list. 8920 8921 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8922 return false; 8923 8924 ClassTemplateDecl *Template = nullptr; 8925 const TemplateArgument *Arguments = nullptr; 8926 8927 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8928 8929 ClassTemplateSpecializationDecl *Specialization = 8930 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8931 if (!Specialization) 8932 return false; 8933 8934 Template = Specialization->getSpecializedTemplate(); 8935 Arguments = Specialization->getTemplateArgs().data(); 8936 } else if (const TemplateSpecializationType *TST = 8937 Ty->getAs<TemplateSpecializationType>()) { 8938 Template = dyn_cast_or_null<ClassTemplateDecl>( 8939 TST->getTemplateName().getAsTemplateDecl()); 8940 Arguments = TST->getArgs(); 8941 } 8942 if (!Template) 8943 return false; 8944 8945 if (!StdInitializerList) { 8946 // Haven't recognized std::initializer_list yet, maybe this is it. 8947 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8948 if (TemplateClass->getIdentifier() != 8949 &PP.getIdentifierTable().get("initializer_list") || 8950 !getStdNamespace()->InEnclosingNamespaceSetOf( 8951 TemplateClass->getDeclContext())) 8952 return false; 8953 // This is a template called std::initializer_list, but is it the right 8954 // template? 8955 TemplateParameterList *Params = Template->getTemplateParameters(); 8956 if (Params->getMinRequiredArguments() != 1) 8957 return false; 8958 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8959 return false; 8960 8961 // It's the right template. 8962 StdInitializerList = Template; 8963 } 8964 8965 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8966 return false; 8967 8968 // This is an instance of std::initializer_list. Find the argument type. 8969 if (Element) 8970 *Element = Arguments[0].getAsType(); 8971 return true; 8972 } 8973 8974 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8975 NamespaceDecl *Std = S.getStdNamespace(); 8976 if (!Std) { 8977 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8978 return nullptr; 8979 } 8980 8981 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8982 Loc, Sema::LookupOrdinaryName); 8983 if (!S.LookupQualifiedName(Result, Std)) { 8984 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8985 return nullptr; 8986 } 8987 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8988 if (!Template) { 8989 Result.suppressDiagnostics(); 8990 // We found something weird. Complain about the first thing we found. 8991 NamedDecl *Found = *Result.begin(); 8992 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8993 return nullptr; 8994 } 8995 8996 // We found some template called std::initializer_list. Now verify that it's 8997 // correct. 8998 TemplateParameterList *Params = Template->getTemplateParameters(); 8999 if (Params->getMinRequiredArguments() != 1 || 9000 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9001 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9002 return nullptr; 9003 } 9004 9005 return Template; 9006 } 9007 9008 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9009 if (!StdInitializerList) { 9010 StdInitializerList = LookupStdInitializerList(*this, Loc); 9011 if (!StdInitializerList) 9012 return QualType(); 9013 } 9014 9015 TemplateArgumentListInfo Args(Loc, Loc); 9016 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9017 Context.getTrivialTypeSourceInfo(Element, 9018 Loc))); 9019 return Context.getCanonicalType( 9020 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9021 } 9022 9023 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9024 // C++ [dcl.init.list]p2: 9025 // A constructor is an initializer-list constructor if its first parameter 9026 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9027 // std::initializer_list<E> for some type E, and either there are no other 9028 // parameters or else all other parameters have default arguments. 9029 if (Ctor->getNumParams() < 1 || 9030 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9031 return false; 9032 9033 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9034 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9035 ArgType = RT->getPointeeType().getUnqualifiedType(); 9036 9037 return isStdInitializerList(ArgType, nullptr); 9038 } 9039 9040 /// \brief Determine whether a using statement is in a context where it will be 9041 /// apply in all contexts. 9042 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9043 switch (CurContext->getDeclKind()) { 9044 case Decl::TranslationUnit: 9045 return true; 9046 case Decl::LinkageSpec: 9047 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9048 default: 9049 return false; 9050 } 9051 } 9052 9053 namespace { 9054 9055 // Callback to only accept typo corrections that are namespaces. 9056 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 9057 public: 9058 bool ValidateCandidate(const TypoCorrection &candidate) override { 9059 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9060 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9061 return false; 9062 } 9063 }; 9064 9065 } 9066 9067 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9068 CXXScopeSpec &SS, 9069 SourceLocation IdentLoc, 9070 IdentifierInfo *Ident) { 9071 R.clear(); 9072 if (TypoCorrection Corrected = 9073 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 9074 llvm::make_unique<NamespaceValidatorCCC>(), 9075 Sema::CTK_ErrorRecovery)) { 9076 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9077 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9078 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9079 Ident->getName().equals(CorrectedStr); 9080 S.diagnoseTypo(Corrected, 9081 S.PDiag(diag::err_using_directive_member_suggest) 9082 << Ident << DC << DroppedSpecifier << SS.getRange(), 9083 S.PDiag(diag::note_namespace_defined_here)); 9084 } else { 9085 S.diagnoseTypo(Corrected, 9086 S.PDiag(diag::err_using_directive_suggest) << Ident, 9087 S.PDiag(diag::note_namespace_defined_here)); 9088 } 9089 R.addDecl(Corrected.getFoundDecl()); 9090 return true; 9091 } 9092 return false; 9093 } 9094 9095 Decl *Sema::ActOnUsingDirective(Scope *S, 9096 SourceLocation UsingLoc, 9097 SourceLocation NamespcLoc, 9098 CXXScopeSpec &SS, 9099 SourceLocation IdentLoc, 9100 IdentifierInfo *NamespcName, 9101 AttributeList *AttrList) { 9102 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9103 assert(NamespcName && "Invalid NamespcName."); 9104 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9105 9106 // This can only happen along a recovery path. 9107 while (S->isTemplateParamScope()) 9108 S = S->getParent(); 9109 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9110 9111 UsingDirectiveDecl *UDir = nullptr; 9112 NestedNameSpecifier *Qualifier = nullptr; 9113 if (SS.isSet()) 9114 Qualifier = SS.getScopeRep(); 9115 9116 // Lookup namespace name. 9117 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9118 LookupParsedName(R, S, &SS); 9119 if (R.isAmbiguous()) 9120 return nullptr; 9121 9122 if (R.empty()) { 9123 R.clear(); 9124 // Allow "using namespace std;" or "using namespace ::std;" even if 9125 // "std" hasn't been defined yet, for GCC compatibility. 9126 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9127 NamespcName->isStr("std")) { 9128 Diag(IdentLoc, diag::ext_using_undefined_std); 9129 R.addDecl(getOrCreateStdNamespace()); 9130 R.resolveKind(); 9131 } 9132 // Otherwise, attempt typo correction. 9133 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9134 } 9135 9136 if (!R.empty()) { 9137 NamedDecl *Named = R.getRepresentativeDecl(); 9138 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9139 assert(NS && "expected namespace decl"); 9140 9141 // The use of a nested name specifier may trigger deprecation warnings. 9142 DiagnoseUseOfDecl(Named, IdentLoc); 9143 9144 // C++ [namespace.udir]p1: 9145 // A using-directive specifies that the names in the nominated 9146 // namespace can be used in the scope in which the 9147 // using-directive appears after the using-directive. During 9148 // unqualified name lookup (3.4.1), the names appear as if they 9149 // were declared in the nearest enclosing namespace which 9150 // contains both the using-directive and the nominated 9151 // namespace. [Note: in this context, "contains" means "contains 9152 // directly or indirectly". ] 9153 9154 // Find enclosing context containing both using-directive and 9155 // nominated namespace. 9156 DeclContext *CommonAncestor = NS; 9157 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9158 CommonAncestor = CommonAncestor->getParent(); 9159 9160 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9161 SS.getWithLocInContext(Context), 9162 IdentLoc, Named, CommonAncestor); 9163 9164 if (IsUsingDirectiveInToplevelContext(CurContext) && 9165 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9166 Diag(IdentLoc, diag::warn_using_directive_in_header); 9167 } 9168 9169 PushUsingDirective(S, UDir); 9170 } else { 9171 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9172 } 9173 9174 if (UDir) 9175 ProcessDeclAttributeList(S, UDir, AttrList); 9176 9177 return UDir; 9178 } 9179 9180 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9181 // If the scope has an associated entity and the using directive is at 9182 // namespace or translation unit scope, add the UsingDirectiveDecl into 9183 // its lookup structure so qualified name lookup can find it. 9184 DeclContext *Ctx = S->getEntity(); 9185 if (Ctx && !Ctx->isFunctionOrMethod()) 9186 Ctx->addDecl(UDir); 9187 else 9188 // Otherwise, it is at block scope. The using-directives will affect lookup 9189 // only to the end of the scope. 9190 S->PushUsingDirective(UDir); 9191 } 9192 9193 9194 Decl *Sema::ActOnUsingDeclaration(Scope *S, 9195 AccessSpecifier AS, 9196 SourceLocation UsingLoc, 9197 SourceLocation TypenameLoc, 9198 CXXScopeSpec &SS, 9199 UnqualifiedId &Name, 9200 SourceLocation EllipsisLoc, 9201 AttributeList *AttrList) { 9202 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9203 9204 if (SS.isEmpty()) { 9205 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 9206 return nullptr; 9207 } 9208 9209 switch (Name.getKind()) { 9210 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9211 case UnqualifiedIdKind::IK_Identifier: 9212 case UnqualifiedIdKind::IK_OperatorFunctionId: 9213 case UnqualifiedIdKind::IK_LiteralOperatorId: 9214 case UnqualifiedIdKind::IK_ConversionFunctionId: 9215 break; 9216 9217 case UnqualifiedIdKind::IK_ConstructorName: 9218 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9219 // C++11 inheriting constructors. 9220 Diag(Name.getLocStart(), 9221 getLangOpts().CPlusPlus11 ? 9222 diag::warn_cxx98_compat_using_decl_constructor : 9223 diag::err_using_decl_constructor) 9224 << SS.getRange(); 9225 9226 if (getLangOpts().CPlusPlus11) break; 9227 9228 return nullptr; 9229 9230 case UnqualifiedIdKind::IK_DestructorName: 9231 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 9232 << SS.getRange(); 9233 return nullptr; 9234 9235 case UnqualifiedIdKind::IK_TemplateId: 9236 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 9237 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9238 return nullptr; 9239 9240 case UnqualifiedIdKind::IK_DeductionGuideName: 9241 llvm_unreachable("cannot parse qualified deduction guide name"); 9242 } 9243 9244 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9245 DeclarationName TargetName = TargetNameInfo.getName(); 9246 if (!TargetName) 9247 return nullptr; 9248 9249 // Warn about access declarations. 9250 if (UsingLoc.isInvalid()) { 9251 Diag(Name.getLocStart(), 9252 getLangOpts().CPlusPlus11 ? diag::err_access_decl 9253 : diag::warn_access_decl_deprecated) 9254 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9255 } 9256 9257 if (EllipsisLoc.isInvalid()) { 9258 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9259 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9260 return nullptr; 9261 } else { 9262 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9263 !TargetNameInfo.containsUnexpandedParameterPack()) { 9264 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9265 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9266 EllipsisLoc = SourceLocation(); 9267 } 9268 } 9269 9270 NamedDecl *UD = 9271 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9272 SS, TargetNameInfo, EllipsisLoc, AttrList, 9273 /*IsInstantiation*/false); 9274 if (UD) 9275 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9276 9277 return UD; 9278 } 9279 9280 /// \brief Determine whether a using declaration considers the given 9281 /// declarations as "equivalent", e.g., if they are redeclarations of 9282 /// the same entity or are both typedefs of the same type. 9283 static bool 9284 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9285 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9286 return true; 9287 9288 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9289 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9290 return Context.hasSameType(TD1->getUnderlyingType(), 9291 TD2->getUnderlyingType()); 9292 9293 return false; 9294 } 9295 9296 9297 /// Determines whether to create a using shadow decl for a particular 9298 /// decl, given the set of decls existing prior to this using lookup. 9299 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9300 const LookupResult &Previous, 9301 UsingShadowDecl *&PrevShadow) { 9302 // Diagnose finding a decl which is not from a base class of the 9303 // current class. We do this now because there are cases where this 9304 // function will silently decide not to build a shadow decl, which 9305 // will pre-empt further diagnostics. 9306 // 9307 // We don't need to do this in C++11 because we do the check once on 9308 // the qualifier. 9309 // 9310 // FIXME: diagnose the following if we care enough: 9311 // struct A { int foo; }; 9312 // struct B : A { using A::foo; }; 9313 // template <class T> struct C : A {}; 9314 // template <class T> struct D : C<T> { using B::foo; } // <--- 9315 // This is invalid (during instantiation) in C++03 because B::foo 9316 // resolves to the using decl in B, which is not a base class of D<T>. 9317 // We can't diagnose it immediately because C<T> is an unknown 9318 // specialization. The UsingShadowDecl in D<T> then points directly 9319 // to A::foo, which will look well-formed when we instantiate. 9320 // The right solution is to not collapse the shadow-decl chain. 9321 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9322 DeclContext *OrigDC = Orig->getDeclContext(); 9323 9324 // Handle enums and anonymous structs. 9325 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9326 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9327 while (OrigRec->isAnonymousStructOrUnion()) 9328 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9329 9330 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9331 if (OrigDC == CurContext) { 9332 Diag(Using->getLocation(), 9333 diag::err_using_decl_nested_name_specifier_is_current_class) 9334 << Using->getQualifierLoc().getSourceRange(); 9335 Diag(Orig->getLocation(), diag::note_using_decl_target); 9336 Using->setInvalidDecl(); 9337 return true; 9338 } 9339 9340 Diag(Using->getQualifierLoc().getBeginLoc(), 9341 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9342 << Using->getQualifier() 9343 << cast<CXXRecordDecl>(CurContext) 9344 << Using->getQualifierLoc().getSourceRange(); 9345 Diag(Orig->getLocation(), diag::note_using_decl_target); 9346 Using->setInvalidDecl(); 9347 return true; 9348 } 9349 } 9350 9351 if (Previous.empty()) return false; 9352 9353 NamedDecl *Target = Orig; 9354 if (isa<UsingShadowDecl>(Target)) 9355 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9356 9357 // If the target happens to be one of the previous declarations, we 9358 // don't have a conflict. 9359 // 9360 // FIXME: but we might be increasing its access, in which case we 9361 // should redeclare it. 9362 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9363 bool FoundEquivalentDecl = false; 9364 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9365 I != E; ++I) { 9366 NamedDecl *D = (*I)->getUnderlyingDecl(); 9367 // We can have UsingDecls in our Previous results because we use the same 9368 // LookupResult for checking whether the UsingDecl itself is a valid 9369 // redeclaration. 9370 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9371 continue; 9372 9373 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9374 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9375 PrevShadow = Shadow; 9376 FoundEquivalentDecl = true; 9377 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9378 // We don't conflict with an existing using shadow decl of an equivalent 9379 // declaration, but we're not a redeclaration of it. 9380 FoundEquivalentDecl = true; 9381 } 9382 9383 if (isVisible(D)) 9384 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9385 } 9386 9387 if (FoundEquivalentDecl) 9388 return false; 9389 9390 if (FunctionDecl *FD = Target->getAsFunction()) { 9391 NamedDecl *OldDecl = nullptr; 9392 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9393 /*IsForUsingDecl*/ true)) { 9394 case Ovl_Overload: 9395 return false; 9396 9397 case Ovl_NonFunction: 9398 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9399 break; 9400 9401 // We found a decl with the exact signature. 9402 case Ovl_Match: 9403 // If we're in a record, we want to hide the target, so we 9404 // return true (without a diagnostic) to tell the caller not to 9405 // build a shadow decl. 9406 if (CurContext->isRecord()) 9407 return true; 9408 9409 // If we're not in a record, this is an error. 9410 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9411 break; 9412 } 9413 9414 Diag(Target->getLocation(), diag::note_using_decl_target); 9415 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9416 Using->setInvalidDecl(); 9417 return true; 9418 } 9419 9420 // Target is not a function. 9421 9422 if (isa<TagDecl>(Target)) { 9423 // No conflict between a tag and a non-tag. 9424 if (!Tag) return false; 9425 9426 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9427 Diag(Target->getLocation(), diag::note_using_decl_target); 9428 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9429 Using->setInvalidDecl(); 9430 return true; 9431 } 9432 9433 // No conflict between a tag and a non-tag. 9434 if (!NonTag) return false; 9435 9436 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9437 Diag(Target->getLocation(), diag::note_using_decl_target); 9438 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9439 Using->setInvalidDecl(); 9440 return true; 9441 } 9442 9443 /// Determine whether a direct base class is a virtual base class. 9444 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9445 if (!Derived->getNumVBases()) 9446 return false; 9447 for (auto &B : Derived->bases()) 9448 if (B.getType()->getAsCXXRecordDecl() == Base) 9449 return B.isVirtual(); 9450 llvm_unreachable("not a direct base class"); 9451 } 9452 9453 /// Builds a shadow declaration corresponding to a 'using' declaration. 9454 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9455 UsingDecl *UD, 9456 NamedDecl *Orig, 9457 UsingShadowDecl *PrevDecl) { 9458 // If we resolved to another shadow declaration, just coalesce them. 9459 NamedDecl *Target = Orig; 9460 if (isa<UsingShadowDecl>(Target)) { 9461 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9462 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9463 } 9464 9465 NamedDecl *NonTemplateTarget = Target; 9466 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9467 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9468 9469 UsingShadowDecl *Shadow; 9470 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9471 bool IsVirtualBase = 9472 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9473 UD->getQualifier()->getAsRecordDecl()); 9474 Shadow = ConstructorUsingShadowDecl::Create( 9475 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9476 } else { 9477 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9478 Target); 9479 } 9480 UD->addShadowDecl(Shadow); 9481 9482 Shadow->setAccess(UD->getAccess()); 9483 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9484 Shadow->setInvalidDecl(); 9485 9486 Shadow->setPreviousDecl(PrevDecl); 9487 9488 if (S) 9489 PushOnScopeChains(Shadow, S); 9490 else 9491 CurContext->addDecl(Shadow); 9492 9493 9494 return Shadow; 9495 } 9496 9497 /// Hides a using shadow declaration. This is required by the current 9498 /// using-decl implementation when a resolvable using declaration in a 9499 /// class is followed by a declaration which would hide or override 9500 /// one or more of the using decl's targets; for example: 9501 /// 9502 /// struct Base { void foo(int); }; 9503 /// struct Derived : Base { 9504 /// using Base::foo; 9505 /// void foo(int); 9506 /// }; 9507 /// 9508 /// The governing language is C++03 [namespace.udecl]p12: 9509 /// 9510 /// When a using-declaration brings names from a base class into a 9511 /// derived class scope, member functions in the derived class 9512 /// override and/or hide member functions with the same name and 9513 /// parameter types in a base class (rather than conflicting). 9514 /// 9515 /// There are two ways to implement this: 9516 /// (1) optimistically create shadow decls when they're not hidden 9517 /// by existing declarations, or 9518 /// (2) don't create any shadow decls (or at least don't make them 9519 /// visible) until we've fully parsed/instantiated the class. 9520 /// The problem with (1) is that we might have to retroactively remove 9521 /// a shadow decl, which requires several O(n) operations because the 9522 /// decl structures are (very reasonably) not designed for removal. 9523 /// (2) avoids this but is very fiddly and phase-dependent. 9524 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9525 if (Shadow->getDeclName().getNameKind() == 9526 DeclarationName::CXXConversionFunctionName) 9527 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9528 9529 // Remove it from the DeclContext... 9530 Shadow->getDeclContext()->removeDecl(Shadow); 9531 9532 // ...and the scope, if applicable... 9533 if (S) { 9534 S->RemoveDecl(Shadow); 9535 IdResolver.RemoveDecl(Shadow); 9536 } 9537 9538 // ...and the using decl. 9539 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9540 9541 // TODO: complain somehow if Shadow was used. It shouldn't 9542 // be possible for this to happen, because...? 9543 } 9544 9545 /// Find the base specifier for a base class with the given type. 9546 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9547 QualType DesiredBase, 9548 bool &AnyDependentBases) { 9549 // Check whether the named type is a direct base class. 9550 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9551 for (auto &Base : Derived->bases()) { 9552 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9553 if (CanonicalDesiredBase == BaseType) 9554 return &Base; 9555 if (BaseType->isDependentType()) 9556 AnyDependentBases = true; 9557 } 9558 return nullptr; 9559 } 9560 9561 namespace { 9562 class UsingValidatorCCC : public CorrectionCandidateCallback { 9563 public: 9564 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9565 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9566 : HasTypenameKeyword(HasTypenameKeyword), 9567 IsInstantiation(IsInstantiation), OldNNS(NNS), 9568 RequireMemberOf(RequireMemberOf) {} 9569 9570 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9571 NamedDecl *ND = Candidate.getCorrectionDecl(); 9572 9573 // Keywords are not valid here. 9574 if (!ND || isa<NamespaceDecl>(ND)) 9575 return false; 9576 9577 // Completely unqualified names are invalid for a 'using' declaration. 9578 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9579 return false; 9580 9581 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9582 // reject. 9583 9584 if (RequireMemberOf) { 9585 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9586 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9587 // No-one ever wants a using-declaration to name an injected-class-name 9588 // of a base class, unless they're declaring an inheriting constructor. 9589 ASTContext &Ctx = ND->getASTContext(); 9590 if (!Ctx.getLangOpts().CPlusPlus11) 9591 return false; 9592 QualType FoundType = Ctx.getRecordType(FoundRecord); 9593 9594 // Check that the injected-class-name is named as a member of its own 9595 // type; we don't want to suggest 'using Derived::Base;', since that 9596 // means something else. 9597 NestedNameSpecifier *Specifier = 9598 Candidate.WillReplaceSpecifier() 9599 ? Candidate.getCorrectionSpecifier() 9600 : OldNNS; 9601 if (!Specifier->getAsType() || 9602 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9603 return false; 9604 9605 // Check that this inheriting constructor declaration actually names a 9606 // direct base class of the current class. 9607 bool AnyDependentBases = false; 9608 if (!findDirectBaseWithType(RequireMemberOf, 9609 Ctx.getRecordType(FoundRecord), 9610 AnyDependentBases) && 9611 !AnyDependentBases) 9612 return false; 9613 } else { 9614 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9615 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9616 return false; 9617 9618 // FIXME: Check that the base class member is accessible? 9619 } 9620 } else { 9621 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9622 if (FoundRecord && FoundRecord->isInjectedClassName()) 9623 return false; 9624 } 9625 9626 if (isa<TypeDecl>(ND)) 9627 return HasTypenameKeyword || !IsInstantiation; 9628 9629 return !HasTypenameKeyword; 9630 } 9631 9632 private: 9633 bool HasTypenameKeyword; 9634 bool IsInstantiation; 9635 NestedNameSpecifier *OldNNS; 9636 CXXRecordDecl *RequireMemberOf; 9637 }; 9638 } // end anonymous namespace 9639 9640 /// Builds a using declaration. 9641 /// 9642 /// \param IsInstantiation - Whether this call arises from an 9643 /// instantiation of an unresolved using declaration. We treat 9644 /// the lookup differently for these declarations. 9645 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9646 SourceLocation UsingLoc, 9647 bool HasTypenameKeyword, 9648 SourceLocation TypenameLoc, 9649 CXXScopeSpec &SS, 9650 DeclarationNameInfo NameInfo, 9651 SourceLocation EllipsisLoc, 9652 AttributeList *AttrList, 9653 bool IsInstantiation) { 9654 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9655 SourceLocation IdentLoc = NameInfo.getLoc(); 9656 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9657 9658 // FIXME: We ignore attributes for now. 9659 9660 // For an inheriting constructor declaration, the name of the using 9661 // declaration is the name of a constructor in this class, not in the 9662 // base class. 9663 DeclarationNameInfo UsingName = NameInfo; 9664 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9665 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9666 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9667 Context.getCanonicalType(Context.getRecordType(RD)))); 9668 9669 // Do the redeclaration lookup in the current scope. 9670 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9671 ForVisibleRedeclaration); 9672 Previous.setHideTags(false); 9673 if (S) { 9674 LookupName(Previous, S); 9675 9676 // It is really dumb that we have to do this. 9677 LookupResult::Filter F = Previous.makeFilter(); 9678 while (F.hasNext()) { 9679 NamedDecl *D = F.next(); 9680 if (!isDeclInScope(D, CurContext, S)) 9681 F.erase(); 9682 // If we found a local extern declaration that's not ordinarily visible, 9683 // and this declaration is being added to a non-block scope, ignore it. 9684 // We're only checking for scope conflicts here, not also for violations 9685 // of the linkage rules. 9686 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9687 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9688 F.erase(); 9689 } 9690 F.done(); 9691 } else { 9692 assert(IsInstantiation && "no scope in non-instantiation"); 9693 if (CurContext->isRecord()) 9694 LookupQualifiedName(Previous, CurContext); 9695 else { 9696 // No redeclaration check is needed here; in non-member contexts we 9697 // diagnosed all possible conflicts with other using-declarations when 9698 // building the template: 9699 // 9700 // For a dependent non-type using declaration, the only valid case is 9701 // if we instantiate to a single enumerator. We check for conflicts 9702 // between shadow declarations we introduce, and we check in the template 9703 // definition for conflicts between a non-type using declaration and any 9704 // other declaration, which together covers all cases. 9705 // 9706 // A dependent typename using declaration will never successfully 9707 // instantiate, since it will always name a class member, so we reject 9708 // that in the template definition. 9709 } 9710 } 9711 9712 // Check for invalid redeclarations. 9713 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9714 SS, IdentLoc, Previous)) 9715 return nullptr; 9716 9717 // Check for bad qualifiers. 9718 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9719 IdentLoc)) 9720 return nullptr; 9721 9722 DeclContext *LookupContext = computeDeclContext(SS); 9723 NamedDecl *D; 9724 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9725 if (!LookupContext || EllipsisLoc.isValid()) { 9726 if (HasTypenameKeyword) { 9727 // FIXME: not all declaration name kinds are legal here 9728 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9729 UsingLoc, TypenameLoc, 9730 QualifierLoc, 9731 IdentLoc, NameInfo.getName(), 9732 EllipsisLoc); 9733 } else { 9734 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9735 QualifierLoc, NameInfo, EllipsisLoc); 9736 } 9737 D->setAccess(AS); 9738 CurContext->addDecl(D); 9739 return D; 9740 } 9741 9742 auto Build = [&](bool Invalid) { 9743 UsingDecl *UD = 9744 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9745 UsingName, HasTypenameKeyword); 9746 UD->setAccess(AS); 9747 CurContext->addDecl(UD); 9748 UD->setInvalidDecl(Invalid); 9749 return UD; 9750 }; 9751 auto BuildInvalid = [&]{ return Build(true); }; 9752 auto BuildValid = [&]{ return Build(false); }; 9753 9754 if (RequireCompleteDeclContext(SS, LookupContext)) 9755 return BuildInvalid(); 9756 9757 // Look up the target name. 9758 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9759 9760 // Unlike most lookups, we don't always want to hide tag 9761 // declarations: tag names are visible through the using declaration 9762 // even if hidden by ordinary names, *except* in a dependent context 9763 // where it's important for the sanity of two-phase lookup. 9764 if (!IsInstantiation) 9765 R.setHideTags(false); 9766 9767 // For the purposes of this lookup, we have a base object type 9768 // equal to that of the current context. 9769 if (CurContext->isRecord()) { 9770 R.setBaseObjectType( 9771 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9772 } 9773 9774 LookupQualifiedName(R, LookupContext); 9775 9776 // Try to correct typos if possible. If constructor name lookup finds no 9777 // results, that means the named class has no explicit constructors, and we 9778 // suppressed declaring implicit ones (probably because it's dependent or 9779 // invalid). 9780 if (R.empty() && 9781 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9782 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9783 // it will believe that glibc provides a ::gets in cases where it does not, 9784 // and will try to pull it into namespace std with a using-declaration. 9785 // Just ignore the using-declaration in that case. 9786 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9787 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9788 CurContext->isStdNamespace() && 9789 isa<TranslationUnitDecl>(LookupContext) && 9790 getSourceManager().isInSystemHeader(UsingLoc)) 9791 return nullptr; 9792 if (TypoCorrection Corrected = CorrectTypo( 9793 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9794 llvm::make_unique<UsingValidatorCCC>( 9795 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9796 dyn_cast<CXXRecordDecl>(CurContext)), 9797 CTK_ErrorRecovery)) { 9798 // We reject candidates where DroppedSpecifier == true, hence the 9799 // literal '0' below. 9800 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9801 << NameInfo.getName() << LookupContext << 0 9802 << SS.getRange()); 9803 9804 // If we picked a correction with no attached Decl we can't do anything 9805 // useful with it, bail out. 9806 NamedDecl *ND = Corrected.getCorrectionDecl(); 9807 if (!ND) 9808 return BuildInvalid(); 9809 9810 // If we corrected to an inheriting constructor, handle it as one. 9811 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9812 if (RD && RD->isInjectedClassName()) { 9813 // The parent of the injected class name is the class itself. 9814 RD = cast<CXXRecordDecl>(RD->getParent()); 9815 9816 // Fix up the information we'll use to build the using declaration. 9817 if (Corrected.WillReplaceSpecifier()) { 9818 NestedNameSpecifierLocBuilder Builder; 9819 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9820 QualifierLoc.getSourceRange()); 9821 QualifierLoc = Builder.getWithLocInContext(Context); 9822 } 9823 9824 // In this case, the name we introduce is the name of a derived class 9825 // constructor. 9826 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9827 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9828 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9829 UsingName.setNamedTypeInfo(nullptr); 9830 for (auto *Ctor : LookupConstructors(RD)) 9831 R.addDecl(Ctor); 9832 R.resolveKind(); 9833 } else { 9834 // FIXME: Pick up all the declarations if we found an overloaded 9835 // function. 9836 UsingName.setName(ND->getDeclName()); 9837 R.addDecl(ND); 9838 } 9839 } else { 9840 Diag(IdentLoc, diag::err_no_member) 9841 << NameInfo.getName() << LookupContext << SS.getRange(); 9842 return BuildInvalid(); 9843 } 9844 } 9845 9846 if (R.isAmbiguous()) 9847 return BuildInvalid(); 9848 9849 if (HasTypenameKeyword) { 9850 // If we asked for a typename and got a non-type decl, error out. 9851 if (!R.getAsSingle<TypeDecl>()) { 9852 Diag(IdentLoc, diag::err_using_typename_non_type); 9853 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9854 Diag((*I)->getUnderlyingDecl()->getLocation(), 9855 diag::note_using_decl_target); 9856 return BuildInvalid(); 9857 } 9858 } else { 9859 // If we asked for a non-typename and we got a type, error out, 9860 // but only if this is an instantiation of an unresolved using 9861 // decl. Otherwise just silently find the type name. 9862 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9863 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9864 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9865 return BuildInvalid(); 9866 } 9867 } 9868 9869 // C++14 [namespace.udecl]p6: 9870 // A using-declaration shall not name a namespace. 9871 if (R.getAsSingle<NamespaceDecl>()) { 9872 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9873 << SS.getRange(); 9874 return BuildInvalid(); 9875 } 9876 9877 // C++14 [namespace.udecl]p7: 9878 // A using-declaration shall not name a scoped enumerator. 9879 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9880 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9881 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9882 << SS.getRange(); 9883 return BuildInvalid(); 9884 } 9885 } 9886 9887 UsingDecl *UD = BuildValid(); 9888 9889 // Some additional rules apply to inheriting constructors. 9890 if (UsingName.getName().getNameKind() == 9891 DeclarationName::CXXConstructorName) { 9892 // Suppress access diagnostics; the access check is instead performed at the 9893 // point of use for an inheriting constructor. 9894 R.suppressDiagnostics(); 9895 if (CheckInheritingConstructorUsingDecl(UD)) 9896 return UD; 9897 } 9898 9899 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9900 UsingShadowDecl *PrevDecl = nullptr; 9901 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9902 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9903 } 9904 9905 return UD; 9906 } 9907 9908 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 9909 ArrayRef<NamedDecl *> Expansions) { 9910 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 9911 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 9912 isa<UsingPackDecl>(InstantiatedFrom)); 9913 9914 auto *UPD = 9915 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 9916 UPD->setAccess(InstantiatedFrom->getAccess()); 9917 CurContext->addDecl(UPD); 9918 return UPD; 9919 } 9920 9921 /// Additional checks for a using declaration referring to a constructor name. 9922 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9923 assert(!UD->hasTypename() && "expecting a constructor name"); 9924 9925 const Type *SourceType = UD->getQualifier()->getAsType(); 9926 assert(SourceType && 9927 "Using decl naming constructor doesn't have type in scope spec."); 9928 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9929 9930 // Check whether the named type is a direct base class. 9931 bool AnyDependentBases = false; 9932 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9933 AnyDependentBases); 9934 if (!Base && !AnyDependentBases) { 9935 Diag(UD->getUsingLoc(), 9936 diag::err_using_decl_constructor_not_in_direct_base) 9937 << UD->getNameInfo().getSourceRange() 9938 << QualType(SourceType, 0) << TargetClass; 9939 UD->setInvalidDecl(); 9940 return true; 9941 } 9942 9943 if (Base) 9944 Base->setInheritConstructors(); 9945 9946 return false; 9947 } 9948 9949 /// Checks that the given using declaration is not an invalid 9950 /// redeclaration. Note that this is checking only for the using decl 9951 /// itself, not for any ill-formedness among the UsingShadowDecls. 9952 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9953 bool HasTypenameKeyword, 9954 const CXXScopeSpec &SS, 9955 SourceLocation NameLoc, 9956 const LookupResult &Prev) { 9957 NestedNameSpecifier *Qual = SS.getScopeRep(); 9958 9959 // C++03 [namespace.udecl]p8: 9960 // C++0x [namespace.udecl]p10: 9961 // A using-declaration is a declaration and can therefore be used 9962 // repeatedly where (and only where) multiple declarations are 9963 // allowed. 9964 // 9965 // That's in non-member contexts. 9966 if (!CurContext->getRedeclContext()->isRecord()) { 9967 // A dependent qualifier outside a class can only ever resolve to an 9968 // enumeration type. Therefore it conflicts with any other non-type 9969 // declaration in the same scope. 9970 // FIXME: How should we check for dependent type-type conflicts at block 9971 // scope? 9972 if (Qual->isDependent() && !HasTypenameKeyword) { 9973 for (auto *D : Prev) { 9974 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 9975 bool OldCouldBeEnumerator = 9976 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 9977 Diag(NameLoc, 9978 OldCouldBeEnumerator ? diag::err_redefinition 9979 : diag::err_redefinition_different_kind) 9980 << Prev.getLookupName(); 9981 Diag(D->getLocation(), diag::note_previous_definition); 9982 return true; 9983 } 9984 } 9985 } 9986 return false; 9987 } 9988 9989 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9990 NamedDecl *D = *I; 9991 9992 bool DTypename; 9993 NestedNameSpecifier *DQual; 9994 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9995 DTypename = UD->hasTypename(); 9996 DQual = UD->getQualifier(); 9997 } else if (UnresolvedUsingValueDecl *UD 9998 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9999 DTypename = false; 10000 DQual = UD->getQualifier(); 10001 } else if (UnresolvedUsingTypenameDecl *UD 10002 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10003 DTypename = true; 10004 DQual = UD->getQualifier(); 10005 } else continue; 10006 10007 // using decls differ if one says 'typename' and the other doesn't. 10008 // FIXME: non-dependent using decls? 10009 if (HasTypenameKeyword != DTypename) continue; 10010 10011 // using decls differ if they name different scopes (but note that 10012 // template instantiation can cause this check to trigger when it 10013 // didn't before instantiation). 10014 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10015 Context.getCanonicalNestedNameSpecifier(DQual)) 10016 continue; 10017 10018 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10019 Diag(D->getLocation(), diag::note_using_decl) << 1; 10020 return true; 10021 } 10022 10023 return false; 10024 } 10025 10026 10027 /// Checks that the given nested-name qualifier used in a using decl 10028 /// in the current context is appropriately related to the current 10029 /// scope. If an error is found, diagnoses it and returns true. 10030 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10031 bool HasTypename, 10032 const CXXScopeSpec &SS, 10033 const DeclarationNameInfo &NameInfo, 10034 SourceLocation NameLoc) { 10035 DeclContext *NamedContext = computeDeclContext(SS); 10036 10037 if (!CurContext->isRecord()) { 10038 // C++03 [namespace.udecl]p3: 10039 // C++0x [namespace.udecl]p8: 10040 // A using-declaration for a class member shall be a member-declaration. 10041 10042 // If we weren't able to compute a valid scope, it might validly be a 10043 // dependent class scope or a dependent enumeration unscoped scope. If 10044 // we have a 'typename' keyword, the scope must resolve to a class type. 10045 if ((HasTypename && !NamedContext) || 10046 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10047 auto *RD = NamedContext 10048 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10049 : nullptr; 10050 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10051 RD = nullptr; 10052 10053 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10054 << SS.getRange(); 10055 10056 // If we have a complete, non-dependent source type, try to suggest a 10057 // way to get the same effect. 10058 if (!RD) 10059 return true; 10060 10061 // Find what this using-declaration was referring to. 10062 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10063 R.setHideTags(false); 10064 R.suppressDiagnostics(); 10065 LookupQualifiedName(R, RD); 10066 10067 if (R.getAsSingle<TypeDecl>()) { 10068 if (getLangOpts().CPlusPlus11) { 10069 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10070 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10071 << 0 // alias declaration 10072 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10073 NameInfo.getName().getAsString() + 10074 " = "); 10075 } else { 10076 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10077 SourceLocation InsertLoc = 10078 getLocForEndOfToken(NameInfo.getLocEnd()); 10079 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10080 << 1 // typedef declaration 10081 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10082 << FixItHint::CreateInsertion( 10083 InsertLoc, " " + NameInfo.getName().getAsString()); 10084 } 10085 } else if (R.getAsSingle<VarDecl>()) { 10086 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10087 // repeating the type of the static data member here. 10088 FixItHint FixIt; 10089 if (getLangOpts().CPlusPlus11) { 10090 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10091 FixIt = FixItHint::CreateReplacement( 10092 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10093 } 10094 10095 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10096 << 2 // reference declaration 10097 << FixIt; 10098 } else if (R.getAsSingle<EnumConstantDecl>()) { 10099 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10100 // repeating the type of the enumeration here, and we can't do so if 10101 // the type is anonymous. 10102 FixItHint FixIt; 10103 if (getLangOpts().CPlusPlus11) { 10104 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10105 FixIt = FixItHint::CreateReplacement( 10106 UsingLoc, 10107 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10108 } 10109 10110 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10111 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10112 << FixIt; 10113 } 10114 return true; 10115 } 10116 10117 // Otherwise, this might be valid. 10118 return false; 10119 } 10120 10121 // The current scope is a record. 10122 10123 // If the named context is dependent, we can't decide much. 10124 if (!NamedContext) { 10125 // FIXME: in C++0x, we can diagnose if we can prove that the 10126 // nested-name-specifier does not refer to a base class, which is 10127 // still possible in some cases. 10128 10129 // Otherwise we have to conservatively report that things might be 10130 // okay. 10131 return false; 10132 } 10133 10134 if (!NamedContext->isRecord()) { 10135 // Ideally this would point at the last name in the specifier, 10136 // but we don't have that level of source info. 10137 Diag(SS.getRange().getBegin(), 10138 diag::err_using_decl_nested_name_specifier_is_not_class) 10139 << SS.getScopeRep() << SS.getRange(); 10140 return true; 10141 } 10142 10143 if (!NamedContext->isDependentContext() && 10144 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10145 return true; 10146 10147 if (getLangOpts().CPlusPlus11) { 10148 // C++11 [namespace.udecl]p3: 10149 // In a using-declaration used as a member-declaration, the 10150 // nested-name-specifier shall name a base class of the class 10151 // being defined. 10152 10153 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10154 cast<CXXRecordDecl>(NamedContext))) { 10155 if (CurContext == NamedContext) { 10156 Diag(NameLoc, 10157 diag::err_using_decl_nested_name_specifier_is_current_class) 10158 << SS.getRange(); 10159 return true; 10160 } 10161 10162 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10163 Diag(SS.getRange().getBegin(), 10164 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10165 << SS.getScopeRep() 10166 << cast<CXXRecordDecl>(CurContext) 10167 << SS.getRange(); 10168 } 10169 return true; 10170 } 10171 10172 return false; 10173 } 10174 10175 // C++03 [namespace.udecl]p4: 10176 // A using-declaration used as a member-declaration shall refer 10177 // to a member of a base class of the class being defined [etc.]. 10178 10179 // Salient point: SS doesn't have to name a base class as long as 10180 // lookup only finds members from base classes. Therefore we can 10181 // diagnose here only if we can prove that that can't happen, 10182 // i.e. if the class hierarchies provably don't intersect. 10183 10184 // TODO: it would be nice if "definitely valid" results were cached 10185 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10186 // need to be repeated. 10187 10188 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10189 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10190 Bases.insert(Base); 10191 return true; 10192 }; 10193 10194 // Collect all bases. Return false if we find a dependent base. 10195 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10196 return false; 10197 10198 // Returns true if the base is dependent or is one of the accumulated base 10199 // classes. 10200 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10201 return !Bases.count(Base); 10202 }; 10203 10204 // Return false if the class has a dependent base or if it or one 10205 // of its bases is present in the base set of the current context. 10206 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10207 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10208 return false; 10209 10210 Diag(SS.getRange().getBegin(), 10211 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10212 << SS.getScopeRep() 10213 << cast<CXXRecordDecl>(CurContext) 10214 << SS.getRange(); 10215 10216 return true; 10217 } 10218 10219 Decl *Sema::ActOnAliasDeclaration(Scope *S, 10220 AccessSpecifier AS, 10221 MultiTemplateParamsArg TemplateParamLists, 10222 SourceLocation UsingLoc, 10223 UnqualifiedId &Name, 10224 AttributeList *AttrList, 10225 TypeResult Type, 10226 Decl *DeclFromDeclSpec) { 10227 // Skip up to the relevant declaration scope. 10228 while (S->isTemplateParamScope()) 10229 S = S->getParent(); 10230 assert((S->getFlags() & Scope::DeclScope) && 10231 "got alias-declaration outside of declaration scope"); 10232 10233 if (Type.isInvalid()) 10234 return nullptr; 10235 10236 bool Invalid = false; 10237 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10238 TypeSourceInfo *TInfo = nullptr; 10239 GetTypeFromParser(Type.get(), &TInfo); 10240 10241 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10242 return nullptr; 10243 10244 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10245 UPPC_DeclarationType)) { 10246 Invalid = true; 10247 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10248 TInfo->getTypeLoc().getBeginLoc()); 10249 } 10250 10251 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10252 TemplateParamLists.size() 10253 ? forRedeclarationInCurContext() 10254 : ForVisibleRedeclaration); 10255 LookupName(Previous, S); 10256 10257 // Warn about shadowing the name of a template parameter. 10258 if (Previous.isSingleResult() && 10259 Previous.getFoundDecl()->isTemplateParameter()) { 10260 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10261 Previous.clear(); 10262 } 10263 10264 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10265 "name in alias declaration must be an identifier"); 10266 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10267 Name.StartLocation, 10268 Name.Identifier, TInfo); 10269 10270 NewTD->setAccess(AS); 10271 10272 if (Invalid) 10273 NewTD->setInvalidDecl(); 10274 10275 ProcessDeclAttributeList(S, NewTD, AttrList); 10276 AddPragmaAttributes(S, NewTD); 10277 10278 CheckTypedefForVariablyModifiedType(S, NewTD); 10279 Invalid |= NewTD->isInvalidDecl(); 10280 10281 bool Redeclaration = false; 10282 10283 NamedDecl *NewND; 10284 if (TemplateParamLists.size()) { 10285 TypeAliasTemplateDecl *OldDecl = nullptr; 10286 TemplateParameterList *OldTemplateParams = nullptr; 10287 10288 if (TemplateParamLists.size() != 1) { 10289 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10290 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10291 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10292 } 10293 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10294 10295 // Check that we can declare a template here. 10296 if (CheckTemplateDeclScope(S, TemplateParams)) 10297 return nullptr; 10298 10299 // Only consider previous declarations in the same scope. 10300 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10301 /*ExplicitInstantiationOrSpecialization*/false); 10302 if (!Previous.empty()) { 10303 Redeclaration = true; 10304 10305 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10306 if (!OldDecl && !Invalid) { 10307 Diag(UsingLoc, diag::err_redefinition_different_kind) 10308 << Name.Identifier; 10309 10310 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10311 if (OldD->getLocation().isValid()) 10312 Diag(OldD->getLocation(), diag::note_previous_definition); 10313 10314 Invalid = true; 10315 } 10316 10317 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10318 if (TemplateParameterListsAreEqual(TemplateParams, 10319 OldDecl->getTemplateParameters(), 10320 /*Complain=*/true, 10321 TPL_TemplateMatch)) 10322 OldTemplateParams = OldDecl->getTemplateParameters(); 10323 else 10324 Invalid = true; 10325 10326 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10327 if (!Invalid && 10328 !Context.hasSameType(OldTD->getUnderlyingType(), 10329 NewTD->getUnderlyingType())) { 10330 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10331 // but we can't reasonably accept it. 10332 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10333 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10334 if (OldTD->getLocation().isValid()) 10335 Diag(OldTD->getLocation(), diag::note_previous_definition); 10336 Invalid = true; 10337 } 10338 } 10339 } 10340 10341 // Merge any previous default template arguments into our parameters, 10342 // and check the parameter list. 10343 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10344 TPC_TypeAliasTemplate)) 10345 return nullptr; 10346 10347 TypeAliasTemplateDecl *NewDecl = 10348 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10349 Name.Identifier, TemplateParams, 10350 NewTD); 10351 NewTD->setDescribedAliasTemplate(NewDecl); 10352 10353 NewDecl->setAccess(AS); 10354 10355 if (Invalid) 10356 NewDecl->setInvalidDecl(); 10357 else if (OldDecl) { 10358 NewDecl->setPreviousDecl(OldDecl); 10359 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10360 } 10361 10362 NewND = NewDecl; 10363 } else { 10364 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10365 setTagNameForLinkagePurposes(TD, NewTD); 10366 handleTagNumbering(TD, S); 10367 } 10368 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10369 NewND = NewTD; 10370 } 10371 10372 PushOnScopeChains(NewND, S); 10373 ActOnDocumentableDecl(NewND); 10374 return NewND; 10375 } 10376 10377 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10378 SourceLocation AliasLoc, 10379 IdentifierInfo *Alias, CXXScopeSpec &SS, 10380 SourceLocation IdentLoc, 10381 IdentifierInfo *Ident) { 10382 10383 // Lookup the namespace name. 10384 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10385 LookupParsedName(R, S, &SS); 10386 10387 if (R.isAmbiguous()) 10388 return nullptr; 10389 10390 if (R.empty()) { 10391 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10392 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10393 return nullptr; 10394 } 10395 } 10396 assert(!R.isAmbiguous() && !R.empty()); 10397 NamedDecl *ND = R.getRepresentativeDecl(); 10398 10399 // Check if we have a previous declaration with the same name. 10400 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10401 ForVisibleRedeclaration); 10402 LookupName(PrevR, S); 10403 10404 // Check we're not shadowing a template parameter. 10405 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10406 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10407 PrevR.clear(); 10408 } 10409 10410 // Filter out any other lookup result from an enclosing scope. 10411 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10412 /*AllowInlineNamespace*/false); 10413 10414 // Find the previous declaration and check that we can redeclare it. 10415 NamespaceAliasDecl *Prev = nullptr; 10416 if (PrevR.isSingleResult()) { 10417 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10418 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10419 // We already have an alias with the same name that points to the same 10420 // namespace; check that it matches. 10421 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10422 Prev = AD; 10423 } else if (isVisible(PrevDecl)) { 10424 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10425 << Alias; 10426 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10427 << AD->getNamespace(); 10428 return nullptr; 10429 } 10430 } else if (isVisible(PrevDecl)) { 10431 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10432 ? diag::err_redefinition 10433 : diag::err_redefinition_different_kind; 10434 Diag(AliasLoc, DiagID) << Alias; 10435 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10436 return nullptr; 10437 } 10438 } 10439 10440 // The use of a nested name specifier may trigger deprecation warnings. 10441 DiagnoseUseOfDecl(ND, IdentLoc); 10442 10443 NamespaceAliasDecl *AliasDecl = 10444 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10445 Alias, SS.getWithLocInContext(Context), 10446 IdentLoc, ND); 10447 if (Prev) 10448 AliasDecl->setPreviousDecl(Prev); 10449 10450 PushOnScopeChains(AliasDecl, S); 10451 return AliasDecl; 10452 } 10453 10454 namespace { 10455 struct SpecialMemberExceptionSpecInfo 10456 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10457 SourceLocation Loc; 10458 Sema::ImplicitExceptionSpecification ExceptSpec; 10459 10460 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10461 Sema::CXXSpecialMember CSM, 10462 Sema::InheritedConstructorInfo *ICI, 10463 SourceLocation Loc) 10464 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10465 10466 bool visitBase(CXXBaseSpecifier *Base); 10467 bool visitField(FieldDecl *FD); 10468 10469 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10470 unsigned Quals); 10471 10472 void visitSubobjectCall(Subobject Subobj, 10473 Sema::SpecialMemberOverloadResult SMOR); 10474 }; 10475 } 10476 10477 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10478 auto *RT = Base->getType()->getAs<RecordType>(); 10479 if (!RT) 10480 return false; 10481 10482 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10483 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10484 if (auto *BaseCtor = SMOR.getMethod()) { 10485 visitSubobjectCall(Base, BaseCtor); 10486 return false; 10487 } 10488 10489 visitClassSubobject(BaseClass, Base, 0); 10490 return false; 10491 } 10492 10493 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10494 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10495 Expr *E = FD->getInClassInitializer(); 10496 if (!E) 10497 // FIXME: It's a little wasteful to build and throw away a 10498 // CXXDefaultInitExpr here. 10499 // FIXME: We should have a single context note pointing at Loc, and 10500 // this location should be MD->getLocation() instead, since that's 10501 // the location where we actually use the default init expression. 10502 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10503 if (E) 10504 ExceptSpec.CalledExpr(E); 10505 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10506 ->getAs<RecordType>()) { 10507 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10508 FD->getType().getCVRQualifiers()); 10509 } 10510 return false; 10511 } 10512 10513 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10514 Subobject Subobj, 10515 unsigned Quals) { 10516 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10517 bool IsMutable = Field && Field->isMutable(); 10518 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10519 } 10520 10521 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10522 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10523 // Note, if lookup fails, it doesn't matter what exception specification we 10524 // choose because the special member will be deleted. 10525 if (CXXMethodDecl *MD = SMOR.getMethod()) 10526 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10527 } 10528 10529 static Sema::ImplicitExceptionSpecification 10530 ComputeDefaultedSpecialMemberExceptionSpec( 10531 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10532 Sema::InheritedConstructorInfo *ICI) { 10533 CXXRecordDecl *ClassDecl = MD->getParent(); 10534 10535 // C++ [except.spec]p14: 10536 // An implicitly declared special member function (Clause 12) shall have an 10537 // exception-specification. [...] 10538 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10539 if (ClassDecl->isInvalidDecl()) 10540 return Info.ExceptSpec; 10541 10542 // C++1z [except.spec]p7: 10543 // [Look for exceptions thrown by] a constructor selected [...] to 10544 // initialize a potentially constructed subobject, 10545 // C++1z [except.spec]p8: 10546 // The exception specification for an implicitly-declared destructor, or a 10547 // destructor without a noexcept-specifier, is potentially-throwing if and 10548 // only if any of the destructors for any of its potentially constructed 10549 // subojects is potentially throwing. 10550 // FIXME: We respect the first rule but ignore the "potentially constructed" 10551 // in the second rule to resolve a core issue (no number yet) that would have 10552 // us reject: 10553 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10554 // struct B : A {}; 10555 // struct C : B { void f(); }; 10556 // ... due to giving B::~B() a non-throwing exception specification. 10557 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10558 : Info.VisitAllBases); 10559 10560 return Info.ExceptSpec; 10561 } 10562 10563 namespace { 10564 /// RAII object to register a special member as being currently declared. 10565 struct DeclaringSpecialMember { 10566 Sema &S; 10567 Sema::SpecialMemberDecl D; 10568 Sema::ContextRAII SavedContext; 10569 bool WasAlreadyBeingDeclared; 10570 10571 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10572 : S(S), D(RD, CSM), SavedContext(S, RD) { 10573 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10574 if (WasAlreadyBeingDeclared) 10575 // This almost never happens, but if it does, ensure that our cache 10576 // doesn't contain a stale result. 10577 S.SpecialMemberCache.clear(); 10578 else { 10579 // Register a note to be produced if we encounter an error while 10580 // declaring the special member. 10581 Sema::CodeSynthesisContext Ctx; 10582 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10583 // FIXME: We don't have a location to use here. Using the class's 10584 // location maintains the fiction that we declare all special members 10585 // with the class, but (1) it's not clear that lying about that helps our 10586 // users understand what's going on, and (2) there may be outer contexts 10587 // on the stack (some of which are relevant) and printing them exposes 10588 // our lies. 10589 Ctx.PointOfInstantiation = RD->getLocation(); 10590 Ctx.Entity = RD; 10591 Ctx.SpecialMember = CSM; 10592 S.pushCodeSynthesisContext(Ctx); 10593 } 10594 } 10595 ~DeclaringSpecialMember() { 10596 if (!WasAlreadyBeingDeclared) { 10597 S.SpecialMembersBeingDeclared.erase(D); 10598 S.popCodeSynthesisContext(); 10599 } 10600 } 10601 10602 /// \brief Are we already trying to declare this special member? 10603 bool isAlreadyBeingDeclared() const { 10604 return WasAlreadyBeingDeclared; 10605 } 10606 }; 10607 } 10608 10609 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10610 // Look up any existing declarations, but don't trigger declaration of all 10611 // implicit special members with this name. 10612 DeclarationName Name = FD->getDeclName(); 10613 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10614 ForExternalRedeclaration); 10615 for (auto *D : FD->getParent()->lookup(Name)) 10616 if (auto *Acceptable = R.getAcceptableDecl(D)) 10617 R.addDecl(Acceptable); 10618 R.resolveKind(); 10619 R.suppressDiagnostics(); 10620 10621 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10622 } 10623 10624 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10625 CXXRecordDecl *ClassDecl) { 10626 // C++ [class.ctor]p5: 10627 // A default constructor for a class X is a constructor of class X 10628 // that can be called without an argument. If there is no 10629 // user-declared constructor for class X, a default constructor is 10630 // implicitly declared. An implicitly-declared default constructor 10631 // is an inline public member of its class. 10632 assert(ClassDecl->needsImplicitDefaultConstructor() && 10633 "Should not build implicit default constructor!"); 10634 10635 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10636 if (DSM.isAlreadyBeingDeclared()) 10637 return nullptr; 10638 10639 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10640 CXXDefaultConstructor, 10641 false); 10642 10643 // Create the actual constructor declaration. 10644 CanQualType ClassType 10645 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10646 SourceLocation ClassLoc = ClassDecl->getLocation(); 10647 DeclarationName Name 10648 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10649 DeclarationNameInfo NameInfo(Name, ClassLoc); 10650 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10651 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10652 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10653 /*isImplicitlyDeclared=*/true, Constexpr); 10654 DefaultCon->setAccess(AS_public); 10655 DefaultCon->setDefaulted(); 10656 10657 if (getLangOpts().CUDA) { 10658 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10659 DefaultCon, 10660 /* ConstRHS */ false, 10661 /* Diagnose */ false); 10662 } 10663 10664 // Build an exception specification pointing back at this constructor. 10665 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10666 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10667 10668 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10669 // constructors is easy to compute. 10670 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10671 10672 // Note that we have declared this constructor. 10673 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10674 10675 Scope *S = getScopeForContext(ClassDecl); 10676 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10677 10678 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10679 SetDeclDeleted(DefaultCon, ClassLoc); 10680 10681 if (S) 10682 PushOnScopeChains(DefaultCon, S, false); 10683 ClassDecl->addDecl(DefaultCon); 10684 10685 return DefaultCon; 10686 } 10687 10688 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10689 CXXConstructorDecl *Constructor) { 10690 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10691 !Constructor->doesThisDeclarationHaveABody() && 10692 !Constructor->isDeleted()) && 10693 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10694 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10695 return; 10696 10697 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10698 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10699 10700 SynthesizedFunctionScope Scope(*this, Constructor); 10701 10702 // The exception specification is needed because we are defining the 10703 // function. 10704 ResolveExceptionSpec(CurrentLocation, 10705 Constructor->getType()->castAs<FunctionProtoType>()); 10706 MarkVTableUsed(CurrentLocation, ClassDecl); 10707 10708 // Add a context note for diagnostics produced after this point. 10709 Scope.addContextNote(CurrentLocation); 10710 10711 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10712 Constructor->setInvalidDecl(); 10713 return; 10714 } 10715 10716 SourceLocation Loc = Constructor->getLocEnd().isValid() 10717 ? Constructor->getLocEnd() 10718 : Constructor->getLocation(); 10719 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10720 Constructor->markUsed(Context); 10721 10722 if (ASTMutationListener *L = getASTMutationListener()) { 10723 L->CompletedImplicitDefinition(Constructor); 10724 } 10725 10726 DiagnoseUninitializedFields(*this, Constructor); 10727 } 10728 10729 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10730 // Perform any delayed checks on exception specifications. 10731 CheckDelayedMemberExceptionSpecs(); 10732 } 10733 10734 /// Find or create the fake constructor we synthesize to model constructing an 10735 /// object of a derived class via a constructor of a base class. 10736 CXXConstructorDecl * 10737 Sema::findInheritingConstructor(SourceLocation Loc, 10738 CXXConstructorDecl *BaseCtor, 10739 ConstructorUsingShadowDecl *Shadow) { 10740 CXXRecordDecl *Derived = Shadow->getParent(); 10741 SourceLocation UsingLoc = Shadow->getLocation(); 10742 10743 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10744 // For now we use the name of the base class constructor as a member of the 10745 // derived class to indicate a (fake) inherited constructor name. 10746 DeclarationName Name = BaseCtor->getDeclName(); 10747 10748 // Check to see if we already have a fake constructor for this inherited 10749 // constructor call. 10750 for (NamedDecl *Ctor : Derived->lookup(Name)) 10751 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10752 ->getInheritedConstructor() 10753 .getConstructor(), 10754 BaseCtor)) 10755 return cast<CXXConstructorDecl>(Ctor); 10756 10757 DeclarationNameInfo NameInfo(Name, UsingLoc); 10758 TypeSourceInfo *TInfo = 10759 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10760 FunctionProtoTypeLoc ProtoLoc = 10761 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10762 10763 // Check the inherited constructor is valid and find the list of base classes 10764 // from which it was inherited. 10765 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10766 10767 bool Constexpr = 10768 BaseCtor->isConstexpr() && 10769 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10770 false, BaseCtor, &ICI); 10771 10772 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10773 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10774 BaseCtor->isExplicit(), /*Inline=*/true, 10775 /*ImplicitlyDeclared=*/true, Constexpr, 10776 InheritedConstructor(Shadow, BaseCtor)); 10777 if (Shadow->isInvalidDecl()) 10778 DerivedCtor->setInvalidDecl(); 10779 10780 // Build an unevaluated exception specification for this fake constructor. 10781 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10782 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10783 EPI.ExceptionSpec.Type = EST_Unevaluated; 10784 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10785 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10786 FPT->getParamTypes(), EPI)); 10787 10788 // Build the parameter declarations. 10789 SmallVector<ParmVarDecl *, 16> ParamDecls; 10790 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10791 TypeSourceInfo *TInfo = 10792 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10793 ParmVarDecl *PD = ParmVarDecl::Create( 10794 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10795 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10796 PD->setScopeInfo(0, I); 10797 PD->setImplicit(); 10798 // Ensure attributes are propagated onto parameters (this matters for 10799 // format, pass_object_size, ...). 10800 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10801 ParamDecls.push_back(PD); 10802 ProtoLoc.setParam(I, PD); 10803 } 10804 10805 // Set up the new constructor. 10806 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10807 DerivedCtor->setAccess(BaseCtor->getAccess()); 10808 DerivedCtor->setParams(ParamDecls); 10809 Derived->addDecl(DerivedCtor); 10810 10811 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10812 SetDeclDeleted(DerivedCtor, UsingLoc); 10813 10814 return DerivedCtor; 10815 } 10816 10817 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10818 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10819 Ctor->getInheritedConstructor().getShadowDecl()); 10820 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10821 /*Diagnose*/true); 10822 } 10823 10824 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10825 CXXConstructorDecl *Constructor) { 10826 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10827 assert(Constructor->getInheritedConstructor() && 10828 !Constructor->doesThisDeclarationHaveABody() && 10829 !Constructor->isDeleted()); 10830 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10831 return; 10832 10833 // Initializations are performed "as if by a defaulted default constructor", 10834 // so enter the appropriate scope. 10835 SynthesizedFunctionScope Scope(*this, Constructor); 10836 10837 // The exception specification is needed because we are defining the 10838 // function. 10839 ResolveExceptionSpec(CurrentLocation, 10840 Constructor->getType()->castAs<FunctionProtoType>()); 10841 MarkVTableUsed(CurrentLocation, ClassDecl); 10842 10843 // Add a context note for diagnostics produced after this point. 10844 Scope.addContextNote(CurrentLocation); 10845 10846 ConstructorUsingShadowDecl *Shadow = 10847 Constructor->getInheritedConstructor().getShadowDecl(); 10848 CXXConstructorDecl *InheritedCtor = 10849 Constructor->getInheritedConstructor().getConstructor(); 10850 10851 // [class.inhctor.init]p1: 10852 // initialization proceeds as if a defaulted default constructor is used to 10853 // initialize the D object and each base class subobject from which the 10854 // constructor was inherited 10855 10856 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10857 CXXRecordDecl *RD = Shadow->getParent(); 10858 SourceLocation InitLoc = Shadow->getLocation(); 10859 10860 // Build explicit initializers for all base classes from which the 10861 // constructor was inherited. 10862 SmallVector<CXXCtorInitializer*, 8> Inits; 10863 for (bool VBase : {false, true}) { 10864 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10865 if (B.isVirtual() != VBase) 10866 continue; 10867 10868 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10869 if (!BaseRD) 10870 continue; 10871 10872 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10873 if (!BaseCtor.first) 10874 continue; 10875 10876 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10877 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10878 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10879 10880 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10881 Inits.push_back(new (Context) CXXCtorInitializer( 10882 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10883 SourceLocation())); 10884 } 10885 } 10886 10887 // We now proceed as if for a defaulted default constructor, with the relevant 10888 // initializers replaced. 10889 10890 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 10891 Constructor->setInvalidDecl(); 10892 return; 10893 } 10894 10895 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10896 Constructor->markUsed(Context); 10897 10898 if (ASTMutationListener *L = getASTMutationListener()) { 10899 L->CompletedImplicitDefinition(Constructor); 10900 } 10901 10902 DiagnoseUninitializedFields(*this, Constructor); 10903 } 10904 10905 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10906 // C++ [class.dtor]p2: 10907 // If a class has no user-declared destructor, a destructor is 10908 // declared implicitly. An implicitly-declared destructor is an 10909 // inline public member of its class. 10910 assert(ClassDecl->needsImplicitDestructor()); 10911 10912 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10913 if (DSM.isAlreadyBeingDeclared()) 10914 return nullptr; 10915 10916 // Create the actual destructor declaration. 10917 CanQualType ClassType 10918 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10919 SourceLocation ClassLoc = ClassDecl->getLocation(); 10920 DeclarationName Name 10921 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10922 DeclarationNameInfo NameInfo(Name, ClassLoc); 10923 CXXDestructorDecl *Destructor 10924 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10925 QualType(), nullptr, /*isInline=*/true, 10926 /*isImplicitlyDeclared=*/true); 10927 Destructor->setAccess(AS_public); 10928 Destructor->setDefaulted(); 10929 10930 if (getLangOpts().CUDA) { 10931 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10932 Destructor, 10933 /* ConstRHS */ false, 10934 /* Diagnose */ false); 10935 } 10936 10937 // Build an exception specification pointing back at this destructor. 10938 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10939 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10940 10941 // We don't need to use SpecialMemberIsTrivial here; triviality for 10942 // destructors is easy to compute. 10943 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10944 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 10945 ClassDecl->hasTrivialDestructorForCall()); 10946 10947 // Note that we have declared this destructor. 10948 ++ASTContext::NumImplicitDestructorsDeclared; 10949 10950 Scope *S = getScopeForContext(ClassDecl); 10951 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10952 10953 // We can't check whether an implicit destructor is deleted before we complete 10954 // the definition of the class, because its validity depends on the alignment 10955 // of the class. We'll check this from ActOnFields once the class is complete. 10956 if (ClassDecl->isCompleteDefinition() && 10957 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10958 SetDeclDeleted(Destructor, ClassLoc); 10959 10960 // Introduce this destructor into its scope. 10961 if (S) 10962 PushOnScopeChains(Destructor, S, false); 10963 ClassDecl->addDecl(Destructor); 10964 10965 return Destructor; 10966 } 10967 10968 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10969 CXXDestructorDecl *Destructor) { 10970 assert((Destructor->isDefaulted() && 10971 !Destructor->doesThisDeclarationHaveABody() && 10972 !Destructor->isDeleted()) && 10973 "DefineImplicitDestructor - call it for implicit default dtor"); 10974 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 10975 return; 10976 10977 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10978 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10979 10980 SynthesizedFunctionScope Scope(*this, Destructor); 10981 10982 // The exception specification is needed because we are defining the 10983 // function. 10984 ResolveExceptionSpec(CurrentLocation, 10985 Destructor->getType()->castAs<FunctionProtoType>()); 10986 MarkVTableUsed(CurrentLocation, ClassDecl); 10987 10988 // Add a context note for diagnostics produced after this point. 10989 Scope.addContextNote(CurrentLocation); 10990 10991 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10992 Destructor->getParent()); 10993 10994 if (CheckDestructor(Destructor)) { 10995 Destructor->setInvalidDecl(); 10996 return; 10997 } 10998 10999 SourceLocation Loc = Destructor->getLocEnd().isValid() 11000 ? Destructor->getLocEnd() 11001 : Destructor->getLocation(); 11002 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11003 Destructor->markUsed(Context); 11004 11005 if (ASTMutationListener *L = getASTMutationListener()) { 11006 L->CompletedImplicitDefinition(Destructor); 11007 } 11008 } 11009 11010 /// \brief Perform any semantic analysis which needs to be delayed until all 11011 /// pending class member declarations have been parsed. 11012 void Sema::ActOnFinishCXXMemberDecls() { 11013 // If the context is an invalid C++ class, just suppress these checks. 11014 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11015 if (Record->isInvalidDecl()) { 11016 DelayedDefaultedMemberExceptionSpecs.clear(); 11017 DelayedExceptionSpecChecks.clear(); 11018 return; 11019 } 11020 checkForMultipleExportedDefaultConstructors(*this, Record); 11021 } 11022 } 11023 11024 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11025 referenceDLLExportedClassMethods(); 11026 } 11027 11028 void Sema::referenceDLLExportedClassMethods() { 11029 if (!DelayedDllExportClasses.empty()) { 11030 // Calling ReferenceDllExportedMembers might cause the current function to 11031 // be called again, so use a local copy of DelayedDllExportClasses. 11032 SmallVector<CXXRecordDecl *, 4> WorkList; 11033 std::swap(DelayedDllExportClasses, WorkList); 11034 for (CXXRecordDecl *Class : WorkList) 11035 ReferenceDllExportedMembers(*this, Class); 11036 } 11037 } 11038 11039 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 11040 CXXDestructorDecl *Destructor) { 11041 assert(getLangOpts().CPlusPlus11 && 11042 "adjusting dtor exception specs was introduced in c++11"); 11043 11044 // C++11 [class.dtor]p3: 11045 // A declaration of a destructor that does not have an exception- 11046 // specification is implicitly considered to have the same exception- 11047 // specification as an implicit declaration. 11048 const FunctionProtoType *DtorType = Destructor->getType()-> 11049 getAs<FunctionProtoType>(); 11050 if (DtorType->hasExceptionSpec()) 11051 return; 11052 11053 // Replace the destructor's type, building off the existing one. Fortunately, 11054 // the only thing of interest in the destructor type is its extended info. 11055 // The return and arguments are fixed. 11056 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11057 EPI.ExceptionSpec.Type = EST_Unevaluated; 11058 EPI.ExceptionSpec.SourceDecl = Destructor; 11059 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11060 11061 // FIXME: If the destructor has a body that could throw, and the newly created 11062 // spec doesn't allow exceptions, we should emit a warning, because this 11063 // change in behavior can break conforming C++03 programs at runtime. 11064 // However, we don't have a body or an exception specification yet, so it 11065 // needs to be done somewhere else. 11066 } 11067 11068 namespace { 11069 /// \brief An abstract base class for all helper classes used in building the 11070 // copy/move operators. These classes serve as factory functions and help us 11071 // avoid using the same Expr* in the AST twice. 11072 class ExprBuilder { 11073 ExprBuilder(const ExprBuilder&) = delete; 11074 ExprBuilder &operator=(const ExprBuilder&) = delete; 11075 11076 protected: 11077 static Expr *assertNotNull(Expr *E) { 11078 assert(E && "Expression construction must not fail."); 11079 return E; 11080 } 11081 11082 public: 11083 ExprBuilder() {} 11084 virtual ~ExprBuilder() {} 11085 11086 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11087 }; 11088 11089 class RefBuilder: public ExprBuilder { 11090 VarDecl *Var; 11091 QualType VarType; 11092 11093 public: 11094 Expr *build(Sema &S, SourceLocation Loc) const override { 11095 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 11096 } 11097 11098 RefBuilder(VarDecl *Var, QualType VarType) 11099 : Var(Var), VarType(VarType) {} 11100 }; 11101 11102 class ThisBuilder: public ExprBuilder { 11103 public: 11104 Expr *build(Sema &S, SourceLocation Loc) const override { 11105 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11106 } 11107 }; 11108 11109 class CastBuilder: public ExprBuilder { 11110 const ExprBuilder &Builder; 11111 QualType Type; 11112 ExprValueKind Kind; 11113 const CXXCastPath &Path; 11114 11115 public: 11116 Expr *build(Sema &S, SourceLocation Loc) const override { 11117 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11118 CK_UncheckedDerivedToBase, Kind, 11119 &Path).get()); 11120 } 11121 11122 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11123 const CXXCastPath &Path) 11124 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11125 }; 11126 11127 class DerefBuilder: public ExprBuilder { 11128 const ExprBuilder &Builder; 11129 11130 public: 11131 Expr *build(Sema &S, SourceLocation Loc) const override { 11132 return assertNotNull( 11133 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11134 } 11135 11136 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11137 }; 11138 11139 class MemberBuilder: public ExprBuilder { 11140 const ExprBuilder &Builder; 11141 QualType Type; 11142 CXXScopeSpec SS; 11143 bool IsArrow; 11144 LookupResult &MemberLookup; 11145 11146 public: 11147 Expr *build(Sema &S, SourceLocation Loc) const override { 11148 return assertNotNull(S.BuildMemberReferenceExpr( 11149 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11150 nullptr, MemberLookup, nullptr, nullptr).get()); 11151 } 11152 11153 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11154 LookupResult &MemberLookup) 11155 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11156 MemberLookup(MemberLookup) {} 11157 }; 11158 11159 class MoveCastBuilder: public ExprBuilder { 11160 const ExprBuilder &Builder; 11161 11162 public: 11163 Expr *build(Sema &S, SourceLocation Loc) const override { 11164 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11165 } 11166 11167 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11168 }; 11169 11170 class LvalueConvBuilder: public ExprBuilder { 11171 const ExprBuilder &Builder; 11172 11173 public: 11174 Expr *build(Sema &S, SourceLocation Loc) const override { 11175 return assertNotNull( 11176 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11177 } 11178 11179 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11180 }; 11181 11182 class SubscriptBuilder: public ExprBuilder { 11183 const ExprBuilder &Base; 11184 const ExprBuilder &Index; 11185 11186 public: 11187 Expr *build(Sema &S, SourceLocation Loc) const override { 11188 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11189 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11190 } 11191 11192 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11193 : Base(Base), Index(Index) {} 11194 }; 11195 11196 } // end anonymous namespace 11197 11198 /// When generating a defaulted copy or move assignment operator, if a field 11199 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11200 /// do so. This optimization only applies for arrays of scalars, and for arrays 11201 /// of class type where the selected copy/move-assignment operator is trivial. 11202 static StmtResult 11203 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11204 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11205 // Compute the size of the memory buffer to be copied. 11206 QualType SizeType = S.Context.getSizeType(); 11207 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11208 S.Context.getTypeSizeInChars(T).getQuantity()); 11209 11210 // Take the address of the field references for "from" and "to". We 11211 // directly construct UnaryOperators here because semantic analysis 11212 // does not permit us to take the address of an xvalue. 11213 Expr *From = FromB.build(S, Loc); 11214 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11215 S.Context.getPointerType(From->getType()), 11216 VK_RValue, OK_Ordinary, Loc, false); 11217 Expr *To = ToB.build(S, Loc); 11218 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11219 S.Context.getPointerType(To->getType()), 11220 VK_RValue, OK_Ordinary, Loc, false); 11221 11222 const Type *E = T->getBaseElementTypeUnsafe(); 11223 bool NeedsCollectableMemCpy = 11224 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11225 11226 // Create a reference to the __builtin_objc_memmove_collectable function 11227 StringRef MemCpyName = NeedsCollectableMemCpy ? 11228 "__builtin_objc_memmove_collectable" : 11229 "__builtin_memcpy"; 11230 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11231 Sema::LookupOrdinaryName); 11232 S.LookupName(R, S.TUScope, true); 11233 11234 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11235 if (!MemCpy) 11236 // Something went horribly wrong earlier, and we will have complained 11237 // about it. 11238 return StmtError(); 11239 11240 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11241 VK_RValue, Loc, nullptr); 11242 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11243 11244 Expr *CallArgs[] = { 11245 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11246 }; 11247 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11248 Loc, CallArgs, Loc); 11249 11250 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11251 return Call.getAs<Stmt>(); 11252 } 11253 11254 /// \brief Builds a statement that copies/moves the given entity from \p From to 11255 /// \c To. 11256 /// 11257 /// This routine is used to copy/move the members of a class with an 11258 /// implicitly-declared copy/move assignment operator. When the entities being 11259 /// copied are arrays, this routine builds for loops to copy them. 11260 /// 11261 /// \param S The Sema object used for type-checking. 11262 /// 11263 /// \param Loc The location where the implicit copy/move is being generated. 11264 /// 11265 /// \param T The type of the expressions being copied/moved. Both expressions 11266 /// must have this type. 11267 /// 11268 /// \param To The expression we are copying/moving to. 11269 /// 11270 /// \param From The expression we are copying/moving from. 11271 /// 11272 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11273 /// Otherwise, it's a non-static member subobject. 11274 /// 11275 /// \param Copying Whether we're copying or moving. 11276 /// 11277 /// \param Depth Internal parameter recording the depth of the recursion. 11278 /// 11279 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11280 /// if a memcpy should be used instead. 11281 static StmtResult 11282 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11283 const ExprBuilder &To, const ExprBuilder &From, 11284 bool CopyingBaseSubobject, bool Copying, 11285 unsigned Depth = 0) { 11286 // C++11 [class.copy]p28: 11287 // Each subobject is assigned in the manner appropriate to its type: 11288 // 11289 // - if the subobject is of class type, as if by a call to operator= with 11290 // the subobject as the object expression and the corresponding 11291 // subobject of x as a single function argument (as if by explicit 11292 // qualification; that is, ignoring any possible virtual overriding 11293 // functions in more derived classes); 11294 // 11295 // C++03 [class.copy]p13: 11296 // - if the subobject is of class type, the copy assignment operator for 11297 // the class is used (as if by explicit qualification; that is, 11298 // ignoring any possible virtual overriding functions in more derived 11299 // classes); 11300 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11301 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11302 11303 // Look for operator=. 11304 DeclarationName Name 11305 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11306 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11307 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11308 11309 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11310 // operator. 11311 if (!S.getLangOpts().CPlusPlus11) { 11312 LookupResult::Filter F = OpLookup.makeFilter(); 11313 while (F.hasNext()) { 11314 NamedDecl *D = F.next(); 11315 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11316 if (Method->isCopyAssignmentOperator() || 11317 (!Copying && Method->isMoveAssignmentOperator())) 11318 continue; 11319 11320 F.erase(); 11321 } 11322 F.done(); 11323 } 11324 11325 // Suppress the protected check (C++ [class.protected]) for each of the 11326 // assignment operators we found. This strange dance is required when 11327 // we're assigning via a base classes's copy-assignment operator. To 11328 // ensure that we're getting the right base class subobject (without 11329 // ambiguities), we need to cast "this" to that subobject type; to 11330 // ensure that we don't go through the virtual call mechanism, we need 11331 // to qualify the operator= name with the base class (see below). However, 11332 // this means that if the base class has a protected copy assignment 11333 // operator, the protected member access check will fail. So, we 11334 // rewrite "protected" access to "public" access in this case, since we 11335 // know by construction that we're calling from a derived class. 11336 if (CopyingBaseSubobject) { 11337 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11338 L != LEnd; ++L) { 11339 if (L.getAccess() == AS_protected) 11340 L.setAccess(AS_public); 11341 } 11342 } 11343 11344 // Create the nested-name-specifier that will be used to qualify the 11345 // reference to operator=; this is required to suppress the virtual 11346 // call mechanism. 11347 CXXScopeSpec SS; 11348 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11349 SS.MakeTrivial(S.Context, 11350 NestedNameSpecifier::Create(S.Context, nullptr, false, 11351 CanonicalT), 11352 Loc); 11353 11354 // Create the reference to operator=. 11355 ExprResult OpEqualRef 11356 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11357 SS, /*TemplateKWLoc=*/SourceLocation(), 11358 /*FirstQualifierInScope=*/nullptr, 11359 OpLookup, 11360 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11361 /*SuppressQualifierCheck=*/true); 11362 if (OpEqualRef.isInvalid()) 11363 return StmtError(); 11364 11365 // Build the call to the assignment operator. 11366 11367 Expr *FromInst = From.build(S, Loc); 11368 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11369 OpEqualRef.getAs<Expr>(), 11370 Loc, FromInst, Loc); 11371 if (Call.isInvalid()) 11372 return StmtError(); 11373 11374 // If we built a call to a trivial 'operator=' while copying an array, 11375 // bail out. We'll replace the whole shebang with a memcpy. 11376 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11377 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11378 return StmtResult((Stmt*)nullptr); 11379 11380 // Convert to an expression-statement, and clean up any produced 11381 // temporaries. 11382 return S.ActOnExprStmt(Call); 11383 } 11384 11385 // - if the subobject is of scalar type, the built-in assignment 11386 // operator is used. 11387 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11388 if (!ArrayTy) { 11389 ExprResult Assignment = S.CreateBuiltinBinOp( 11390 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11391 if (Assignment.isInvalid()) 11392 return StmtError(); 11393 return S.ActOnExprStmt(Assignment); 11394 } 11395 11396 // - if the subobject is an array, each element is assigned, in the 11397 // manner appropriate to the element type; 11398 11399 // Construct a loop over the array bounds, e.g., 11400 // 11401 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11402 // 11403 // that will copy each of the array elements. 11404 QualType SizeType = S.Context.getSizeType(); 11405 11406 // Create the iteration variable. 11407 IdentifierInfo *IterationVarName = nullptr; 11408 { 11409 SmallString<8> Str; 11410 llvm::raw_svector_ostream OS(Str); 11411 OS << "__i" << Depth; 11412 IterationVarName = &S.Context.Idents.get(OS.str()); 11413 } 11414 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11415 IterationVarName, SizeType, 11416 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11417 SC_None); 11418 11419 // Initialize the iteration variable to zero. 11420 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11421 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11422 11423 // Creates a reference to the iteration variable. 11424 RefBuilder IterationVarRef(IterationVar, SizeType); 11425 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11426 11427 // Create the DeclStmt that holds the iteration variable. 11428 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11429 11430 // Subscript the "from" and "to" expressions with the iteration variable. 11431 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11432 MoveCastBuilder FromIndexMove(FromIndexCopy); 11433 const ExprBuilder *FromIndex; 11434 if (Copying) 11435 FromIndex = &FromIndexCopy; 11436 else 11437 FromIndex = &FromIndexMove; 11438 11439 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11440 11441 // Build the copy/move for an individual element of the array. 11442 StmtResult Copy = 11443 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11444 ToIndex, *FromIndex, CopyingBaseSubobject, 11445 Copying, Depth + 1); 11446 // Bail out if copying fails or if we determined that we should use memcpy. 11447 if (Copy.isInvalid() || !Copy.get()) 11448 return Copy; 11449 11450 // Create the comparison against the array bound. 11451 llvm::APInt Upper 11452 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11453 Expr *Comparison 11454 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11455 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11456 BO_NE, S.Context.BoolTy, 11457 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11458 11459 // Create the pre-increment of the iteration variable. We can determine 11460 // whether the increment will overflow based on the value of the array 11461 // bound. 11462 Expr *Increment = new (S.Context) 11463 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11464 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11465 11466 // Construct the loop that copies all elements of this array. 11467 return S.ActOnForStmt( 11468 Loc, Loc, InitStmt, 11469 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11470 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11471 } 11472 11473 static StmtResult 11474 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11475 const ExprBuilder &To, const ExprBuilder &From, 11476 bool CopyingBaseSubobject, bool Copying) { 11477 // Maybe we should use a memcpy? 11478 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11479 T.isTriviallyCopyableType(S.Context)) 11480 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11481 11482 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11483 CopyingBaseSubobject, 11484 Copying, 0)); 11485 11486 // If we ended up picking a trivial assignment operator for an array of a 11487 // non-trivially-copyable class type, just emit a memcpy. 11488 if (!Result.isInvalid() && !Result.get()) 11489 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11490 11491 return Result; 11492 } 11493 11494 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11495 // Note: The following rules are largely analoguous to the copy 11496 // constructor rules. Note that virtual bases are not taken into account 11497 // for determining the argument type of the operator. Note also that 11498 // operators taking an object instead of a reference are allowed. 11499 assert(ClassDecl->needsImplicitCopyAssignment()); 11500 11501 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11502 if (DSM.isAlreadyBeingDeclared()) 11503 return nullptr; 11504 11505 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11506 QualType RetType = Context.getLValueReferenceType(ArgType); 11507 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11508 if (Const) 11509 ArgType = ArgType.withConst(); 11510 ArgType = Context.getLValueReferenceType(ArgType); 11511 11512 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11513 CXXCopyAssignment, 11514 Const); 11515 11516 // An implicitly-declared copy assignment operator is an inline public 11517 // member of its class. 11518 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11519 SourceLocation ClassLoc = ClassDecl->getLocation(); 11520 DeclarationNameInfo NameInfo(Name, ClassLoc); 11521 CXXMethodDecl *CopyAssignment = 11522 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11523 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11524 /*isInline=*/true, Constexpr, SourceLocation()); 11525 CopyAssignment->setAccess(AS_public); 11526 CopyAssignment->setDefaulted(); 11527 CopyAssignment->setImplicit(); 11528 11529 if (getLangOpts().CUDA) { 11530 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11531 CopyAssignment, 11532 /* ConstRHS */ Const, 11533 /* Diagnose */ false); 11534 } 11535 11536 // Build an exception specification pointing back at this member. 11537 FunctionProtoType::ExtProtoInfo EPI = 11538 getImplicitMethodEPI(*this, CopyAssignment); 11539 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11540 11541 // Add the parameter to the operator. 11542 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11543 ClassLoc, ClassLoc, 11544 /*Id=*/nullptr, ArgType, 11545 /*TInfo=*/nullptr, SC_None, 11546 nullptr); 11547 CopyAssignment->setParams(FromParam); 11548 11549 CopyAssignment->setTrivial( 11550 ClassDecl->needsOverloadResolutionForCopyAssignment() 11551 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11552 : ClassDecl->hasTrivialCopyAssignment()); 11553 11554 // Note that we have added this copy-assignment operator. 11555 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11556 11557 Scope *S = getScopeForContext(ClassDecl); 11558 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11559 11560 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11561 SetDeclDeleted(CopyAssignment, ClassLoc); 11562 11563 if (S) 11564 PushOnScopeChains(CopyAssignment, S, false); 11565 ClassDecl->addDecl(CopyAssignment); 11566 11567 return CopyAssignment; 11568 } 11569 11570 /// Diagnose an implicit copy operation for a class which is odr-used, but 11571 /// which is deprecated because the class has a user-declared copy constructor, 11572 /// copy assignment operator, or destructor. 11573 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11574 assert(CopyOp->isImplicit()); 11575 11576 CXXRecordDecl *RD = CopyOp->getParent(); 11577 CXXMethodDecl *UserDeclaredOperation = nullptr; 11578 11579 // In Microsoft mode, assignment operations don't affect constructors and 11580 // vice versa. 11581 if (RD->hasUserDeclaredDestructor()) { 11582 UserDeclaredOperation = RD->getDestructor(); 11583 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11584 RD->hasUserDeclaredCopyConstructor() && 11585 !S.getLangOpts().MSVCCompat) { 11586 // Find any user-declared copy constructor. 11587 for (auto *I : RD->ctors()) { 11588 if (I->isCopyConstructor()) { 11589 UserDeclaredOperation = I; 11590 break; 11591 } 11592 } 11593 assert(UserDeclaredOperation); 11594 } else if (isa<CXXConstructorDecl>(CopyOp) && 11595 RD->hasUserDeclaredCopyAssignment() && 11596 !S.getLangOpts().MSVCCompat) { 11597 // Find any user-declared move assignment operator. 11598 for (auto *I : RD->methods()) { 11599 if (I->isCopyAssignmentOperator()) { 11600 UserDeclaredOperation = I; 11601 break; 11602 } 11603 } 11604 assert(UserDeclaredOperation); 11605 } 11606 11607 if (UserDeclaredOperation) { 11608 S.Diag(UserDeclaredOperation->getLocation(), 11609 diag::warn_deprecated_copy_operation) 11610 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11611 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11612 } 11613 } 11614 11615 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11616 CXXMethodDecl *CopyAssignOperator) { 11617 assert((CopyAssignOperator->isDefaulted() && 11618 CopyAssignOperator->isOverloadedOperator() && 11619 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11620 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11621 !CopyAssignOperator->isDeleted()) && 11622 "DefineImplicitCopyAssignment called for wrong function"); 11623 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11624 return; 11625 11626 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11627 if (ClassDecl->isInvalidDecl()) { 11628 CopyAssignOperator->setInvalidDecl(); 11629 return; 11630 } 11631 11632 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11633 11634 // The exception specification is needed because we are defining the 11635 // function. 11636 ResolveExceptionSpec(CurrentLocation, 11637 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11638 11639 // Add a context note for diagnostics produced after this point. 11640 Scope.addContextNote(CurrentLocation); 11641 11642 // C++11 [class.copy]p18: 11643 // The [definition of an implicitly declared copy assignment operator] is 11644 // deprecated if the class has a user-declared copy constructor or a 11645 // user-declared destructor. 11646 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11647 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11648 11649 // C++0x [class.copy]p30: 11650 // The implicitly-defined or explicitly-defaulted copy assignment operator 11651 // for a non-union class X performs memberwise copy assignment of its 11652 // subobjects. The direct base classes of X are assigned first, in the 11653 // order of their declaration in the base-specifier-list, and then the 11654 // immediate non-static data members of X are assigned, in the order in 11655 // which they were declared in the class definition. 11656 11657 // The statements that form the synthesized function body. 11658 SmallVector<Stmt*, 8> Statements; 11659 11660 // The parameter for the "other" object, which we are copying from. 11661 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11662 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11663 QualType OtherRefType = Other->getType(); 11664 if (const LValueReferenceType *OtherRef 11665 = OtherRefType->getAs<LValueReferenceType>()) { 11666 OtherRefType = OtherRef->getPointeeType(); 11667 OtherQuals = OtherRefType.getQualifiers(); 11668 } 11669 11670 // Our location for everything implicitly-generated. 11671 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11672 ? CopyAssignOperator->getLocEnd() 11673 : CopyAssignOperator->getLocation(); 11674 11675 // Builds a DeclRefExpr for the "other" object. 11676 RefBuilder OtherRef(Other, OtherRefType); 11677 11678 // Builds the "this" pointer. 11679 ThisBuilder This; 11680 11681 // Assign base classes. 11682 bool Invalid = false; 11683 for (auto &Base : ClassDecl->bases()) { 11684 // Form the assignment: 11685 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11686 QualType BaseType = Base.getType().getUnqualifiedType(); 11687 if (!BaseType->isRecordType()) { 11688 Invalid = true; 11689 continue; 11690 } 11691 11692 CXXCastPath BasePath; 11693 BasePath.push_back(&Base); 11694 11695 // Construct the "from" expression, which is an implicit cast to the 11696 // appropriately-qualified base type. 11697 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11698 VK_LValue, BasePath); 11699 11700 // Dereference "this". 11701 DerefBuilder DerefThis(This); 11702 CastBuilder To(DerefThis, 11703 Context.getCVRQualifiedType( 11704 BaseType, CopyAssignOperator->getTypeQualifiers()), 11705 VK_LValue, BasePath); 11706 11707 // Build the copy. 11708 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11709 To, From, 11710 /*CopyingBaseSubobject=*/true, 11711 /*Copying=*/true); 11712 if (Copy.isInvalid()) { 11713 CopyAssignOperator->setInvalidDecl(); 11714 return; 11715 } 11716 11717 // Success! Record the copy. 11718 Statements.push_back(Copy.getAs<Expr>()); 11719 } 11720 11721 // Assign non-static members. 11722 for (auto *Field : ClassDecl->fields()) { 11723 // FIXME: We should form some kind of AST representation for the implied 11724 // memcpy in a union copy operation. 11725 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11726 continue; 11727 11728 if (Field->isInvalidDecl()) { 11729 Invalid = true; 11730 continue; 11731 } 11732 11733 // Check for members of reference type; we can't copy those. 11734 if (Field->getType()->isReferenceType()) { 11735 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11736 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11737 Diag(Field->getLocation(), diag::note_declared_at); 11738 Invalid = true; 11739 continue; 11740 } 11741 11742 // Check for members of const-qualified, non-class type. 11743 QualType BaseType = Context.getBaseElementType(Field->getType()); 11744 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11745 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11746 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11747 Diag(Field->getLocation(), diag::note_declared_at); 11748 Invalid = true; 11749 continue; 11750 } 11751 11752 // Suppress assigning zero-width bitfields. 11753 if (Field->isZeroLengthBitField(Context)) 11754 continue; 11755 11756 QualType FieldType = Field->getType().getNonReferenceType(); 11757 if (FieldType->isIncompleteArrayType()) { 11758 assert(ClassDecl->hasFlexibleArrayMember() && 11759 "Incomplete array type is not valid"); 11760 continue; 11761 } 11762 11763 // Build references to the field in the object we're copying from and to. 11764 CXXScopeSpec SS; // Intentionally empty 11765 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11766 LookupMemberName); 11767 MemberLookup.addDecl(Field); 11768 MemberLookup.resolveKind(); 11769 11770 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11771 11772 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11773 11774 // Build the copy of this field. 11775 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11776 To, From, 11777 /*CopyingBaseSubobject=*/false, 11778 /*Copying=*/true); 11779 if (Copy.isInvalid()) { 11780 CopyAssignOperator->setInvalidDecl(); 11781 return; 11782 } 11783 11784 // Success! Record the copy. 11785 Statements.push_back(Copy.getAs<Stmt>()); 11786 } 11787 11788 if (!Invalid) { 11789 // Add a "return *this;" 11790 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11791 11792 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11793 if (Return.isInvalid()) 11794 Invalid = true; 11795 else 11796 Statements.push_back(Return.getAs<Stmt>()); 11797 } 11798 11799 if (Invalid) { 11800 CopyAssignOperator->setInvalidDecl(); 11801 return; 11802 } 11803 11804 StmtResult Body; 11805 { 11806 CompoundScopeRAII CompoundScope(*this); 11807 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11808 /*isStmtExpr=*/false); 11809 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11810 } 11811 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11812 CopyAssignOperator->markUsed(Context); 11813 11814 if (ASTMutationListener *L = getASTMutationListener()) { 11815 L->CompletedImplicitDefinition(CopyAssignOperator); 11816 } 11817 } 11818 11819 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11820 assert(ClassDecl->needsImplicitMoveAssignment()); 11821 11822 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11823 if (DSM.isAlreadyBeingDeclared()) 11824 return nullptr; 11825 11826 // Note: The following rules are largely analoguous to the move 11827 // constructor rules. 11828 11829 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11830 QualType RetType = Context.getLValueReferenceType(ArgType); 11831 ArgType = Context.getRValueReferenceType(ArgType); 11832 11833 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11834 CXXMoveAssignment, 11835 false); 11836 11837 // An implicitly-declared move assignment operator is an inline public 11838 // member of its class. 11839 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11840 SourceLocation ClassLoc = ClassDecl->getLocation(); 11841 DeclarationNameInfo NameInfo(Name, ClassLoc); 11842 CXXMethodDecl *MoveAssignment = 11843 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11844 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11845 /*isInline=*/true, Constexpr, SourceLocation()); 11846 MoveAssignment->setAccess(AS_public); 11847 MoveAssignment->setDefaulted(); 11848 MoveAssignment->setImplicit(); 11849 11850 if (getLangOpts().CUDA) { 11851 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11852 MoveAssignment, 11853 /* ConstRHS */ false, 11854 /* Diagnose */ false); 11855 } 11856 11857 // Build an exception specification pointing back at this member. 11858 FunctionProtoType::ExtProtoInfo EPI = 11859 getImplicitMethodEPI(*this, MoveAssignment); 11860 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11861 11862 // Add the parameter to the operator. 11863 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11864 ClassLoc, ClassLoc, 11865 /*Id=*/nullptr, ArgType, 11866 /*TInfo=*/nullptr, SC_None, 11867 nullptr); 11868 MoveAssignment->setParams(FromParam); 11869 11870 MoveAssignment->setTrivial( 11871 ClassDecl->needsOverloadResolutionForMoveAssignment() 11872 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11873 : ClassDecl->hasTrivialMoveAssignment()); 11874 11875 // Note that we have added this copy-assignment operator. 11876 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11877 11878 Scope *S = getScopeForContext(ClassDecl); 11879 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11880 11881 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11882 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11883 SetDeclDeleted(MoveAssignment, ClassLoc); 11884 } 11885 11886 if (S) 11887 PushOnScopeChains(MoveAssignment, S, false); 11888 ClassDecl->addDecl(MoveAssignment); 11889 11890 return MoveAssignment; 11891 } 11892 11893 /// Check if we're implicitly defining a move assignment operator for a class 11894 /// with virtual bases. Such a move assignment might move-assign the virtual 11895 /// base multiple times. 11896 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11897 SourceLocation CurrentLocation) { 11898 assert(!Class->isDependentContext() && "should not define dependent move"); 11899 11900 // Only a virtual base could get implicitly move-assigned multiple times. 11901 // Only a non-trivial move assignment can observe this. We only want to 11902 // diagnose if we implicitly define an assignment operator that assigns 11903 // two base classes, both of which move-assign the same virtual base. 11904 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11905 Class->getNumBases() < 2) 11906 return; 11907 11908 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11909 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11910 VBaseMap VBases; 11911 11912 for (auto &BI : Class->bases()) { 11913 Worklist.push_back(&BI); 11914 while (!Worklist.empty()) { 11915 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11916 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11917 11918 // If the base has no non-trivial move assignment operators, 11919 // we don't care about moves from it. 11920 if (!Base->hasNonTrivialMoveAssignment()) 11921 continue; 11922 11923 // If there's nothing virtual here, skip it. 11924 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11925 continue; 11926 11927 // If we're not actually going to call a move assignment for this base, 11928 // or the selected move assignment is trivial, skip it. 11929 Sema::SpecialMemberOverloadResult SMOR = 11930 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11931 /*ConstArg*/false, /*VolatileArg*/false, 11932 /*RValueThis*/true, /*ConstThis*/false, 11933 /*VolatileThis*/false); 11934 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 11935 !SMOR.getMethod()->isMoveAssignmentOperator()) 11936 continue; 11937 11938 if (BaseSpec->isVirtual()) { 11939 // We're going to move-assign this virtual base, and its move 11940 // assignment operator is not trivial. If this can happen for 11941 // multiple distinct direct bases of Class, diagnose it. (If it 11942 // only happens in one base, we'll diagnose it when synthesizing 11943 // that base class's move assignment operator.) 11944 CXXBaseSpecifier *&Existing = 11945 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11946 .first->second; 11947 if (Existing && Existing != &BI) { 11948 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11949 << Class << Base; 11950 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11951 << (Base->getCanonicalDecl() == 11952 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11953 << Base << Existing->getType() << Existing->getSourceRange(); 11954 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11955 << (Base->getCanonicalDecl() == 11956 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11957 << Base << BI.getType() << BaseSpec->getSourceRange(); 11958 11959 // Only diagnose each vbase once. 11960 Existing = nullptr; 11961 } 11962 } else { 11963 // Only walk over bases that have defaulted move assignment operators. 11964 // We assume that any user-provided move assignment operator handles 11965 // the multiple-moves-of-vbase case itself somehow. 11966 if (!SMOR.getMethod()->isDefaulted()) 11967 continue; 11968 11969 // We're going to move the base classes of Base. Add them to the list. 11970 for (auto &BI : Base->bases()) 11971 Worklist.push_back(&BI); 11972 } 11973 } 11974 } 11975 } 11976 11977 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11978 CXXMethodDecl *MoveAssignOperator) { 11979 assert((MoveAssignOperator->isDefaulted() && 11980 MoveAssignOperator->isOverloadedOperator() && 11981 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11982 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11983 !MoveAssignOperator->isDeleted()) && 11984 "DefineImplicitMoveAssignment called for wrong function"); 11985 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 11986 return; 11987 11988 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11989 if (ClassDecl->isInvalidDecl()) { 11990 MoveAssignOperator->setInvalidDecl(); 11991 return; 11992 } 11993 11994 // C++0x [class.copy]p28: 11995 // The implicitly-defined or move assignment operator for a non-union class 11996 // X performs memberwise move assignment of its subobjects. The direct base 11997 // classes of X are assigned first, in the order of their declaration in the 11998 // base-specifier-list, and then the immediate non-static data members of X 11999 // are assigned, in the order in which they were declared in the class 12000 // definition. 12001 12002 // Issue a warning if our implicit move assignment operator will move 12003 // from a virtual base more than once. 12004 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12005 12006 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12007 12008 // The exception specification is needed because we are defining the 12009 // function. 12010 ResolveExceptionSpec(CurrentLocation, 12011 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12012 12013 // Add a context note for diagnostics produced after this point. 12014 Scope.addContextNote(CurrentLocation); 12015 12016 // The statements that form the synthesized function body. 12017 SmallVector<Stmt*, 8> Statements; 12018 12019 // The parameter for the "other" object, which we are move from. 12020 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12021 QualType OtherRefType = Other->getType()-> 12022 getAs<RValueReferenceType>()->getPointeeType(); 12023 assert(!OtherRefType.getQualifiers() && 12024 "Bad argument type of defaulted move assignment"); 12025 12026 // Our location for everything implicitly-generated. 12027 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 12028 ? MoveAssignOperator->getLocEnd() 12029 : MoveAssignOperator->getLocation(); 12030 12031 // Builds a reference to the "other" object. 12032 RefBuilder OtherRef(Other, OtherRefType); 12033 // Cast to rvalue. 12034 MoveCastBuilder MoveOther(OtherRef); 12035 12036 // Builds the "this" pointer. 12037 ThisBuilder This; 12038 12039 // Assign base classes. 12040 bool Invalid = false; 12041 for (auto &Base : ClassDecl->bases()) { 12042 // C++11 [class.copy]p28: 12043 // It is unspecified whether subobjects representing virtual base classes 12044 // are assigned more than once by the implicitly-defined copy assignment 12045 // operator. 12046 // FIXME: Do not assign to a vbase that will be assigned by some other base 12047 // class. For a move-assignment, this can result in the vbase being moved 12048 // multiple times. 12049 12050 // Form the assignment: 12051 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12052 QualType BaseType = Base.getType().getUnqualifiedType(); 12053 if (!BaseType->isRecordType()) { 12054 Invalid = true; 12055 continue; 12056 } 12057 12058 CXXCastPath BasePath; 12059 BasePath.push_back(&Base); 12060 12061 // Construct the "from" expression, which is an implicit cast to the 12062 // appropriately-qualified base type. 12063 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12064 12065 // Dereference "this". 12066 DerefBuilder DerefThis(This); 12067 12068 // Implicitly cast "this" to the appropriately-qualified base type. 12069 CastBuilder To(DerefThis, 12070 Context.getCVRQualifiedType( 12071 BaseType, MoveAssignOperator->getTypeQualifiers()), 12072 VK_LValue, BasePath); 12073 12074 // Build the move. 12075 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12076 To, From, 12077 /*CopyingBaseSubobject=*/true, 12078 /*Copying=*/false); 12079 if (Move.isInvalid()) { 12080 MoveAssignOperator->setInvalidDecl(); 12081 return; 12082 } 12083 12084 // Success! Record the move. 12085 Statements.push_back(Move.getAs<Expr>()); 12086 } 12087 12088 // Assign non-static members. 12089 for (auto *Field : ClassDecl->fields()) { 12090 // FIXME: We should form some kind of AST representation for the implied 12091 // memcpy in a union copy operation. 12092 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12093 continue; 12094 12095 if (Field->isInvalidDecl()) { 12096 Invalid = true; 12097 continue; 12098 } 12099 12100 // Check for members of reference type; we can't move those. 12101 if (Field->getType()->isReferenceType()) { 12102 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12103 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12104 Diag(Field->getLocation(), diag::note_declared_at); 12105 Invalid = true; 12106 continue; 12107 } 12108 12109 // Check for members of const-qualified, non-class type. 12110 QualType BaseType = Context.getBaseElementType(Field->getType()); 12111 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12112 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12113 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12114 Diag(Field->getLocation(), diag::note_declared_at); 12115 Invalid = true; 12116 continue; 12117 } 12118 12119 // Suppress assigning zero-width bitfields. 12120 if (Field->isZeroLengthBitField(Context)) 12121 continue; 12122 12123 QualType FieldType = Field->getType().getNonReferenceType(); 12124 if (FieldType->isIncompleteArrayType()) { 12125 assert(ClassDecl->hasFlexibleArrayMember() && 12126 "Incomplete array type is not valid"); 12127 continue; 12128 } 12129 12130 // Build references to the field in the object we're copying from and to. 12131 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12132 LookupMemberName); 12133 MemberLookup.addDecl(Field); 12134 MemberLookup.resolveKind(); 12135 MemberBuilder From(MoveOther, OtherRefType, 12136 /*IsArrow=*/false, MemberLookup); 12137 MemberBuilder To(This, getCurrentThisType(), 12138 /*IsArrow=*/true, MemberLookup); 12139 12140 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12141 "Member reference with rvalue base must be rvalue except for reference " 12142 "members, which aren't allowed for move assignment."); 12143 12144 // Build the move of this field. 12145 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12146 To, From, 12147 /*CopyingBaseSubobject=*/false, 12148 /*Copying=*/false); 12149 if (Move.isInvalid()) { 12150 MoveAssignOperator->setInvalidDecl(); 12151 return; 12152 } 12153 12154 // Success! Record the copy. 12155 Statements.push_back(Move.getAs<Stmt>()); 12156 } 12157 12158 if (!Invalid) { 12159 // Add a "return *this;" 12160 ExprResult ThisObj = 12161 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12162 12163 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12164 if (Return.isInvalid()) 12165 Invalid = true; 12166 else 12167 Statements.push_back(Return.getAs<Stmt>()); 12168 } 12169 12170 if (Invalid) { 12171 MoveAssignOperator->setInvalidDecl(); 12172 return; 12173 } 12174 12175 StmtResult Body; 12176 { 12177 CompoundScopeRAII CompoundScope(*this); 12178 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12179 /*isStmtExpr=*/false); 12180 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12181 } 12182 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12183 MoveAssignOperator->markUsed(Context); 12184 12185 if (ASTMutationListener *L = getASTMutationListener()) { 12186 L->CompletedImplicitDefinition(MoveAssignOperator); 12187 } 12188 } 12189 12190 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12191 CXXRecordDecl *ClassDecl) { 12192 // C++ [class.copy]p4: 12193 // If the class definition does not explicitly declare a copy 12194 // constructor, one is declared implicitly. 12195 assert(ClassDecl->needsImplicitCopyConstructor()); 12196 12197 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12198 if (DSM.isAlreadyBeingDeclared()) 12199 return nullptr; 12200 12201 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12202 QualType ArgType = ClassType; 12203 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12204 if (Const) 12205 ArgType = ArgType.withConst(); 12206 ArgType = Context.getLValueReferenceType(ArgType); 12207 12208 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12209 CXXCopyConstructor, 12210 Const); 12211 12212 DeclarationName Name 12213 = Context.DeclarationNames.getCXXConstructorName( 12214 Context.getCanonicalType(ClassType)); 12215 SourceLocation ClassLoc = ClassDecl->getLocation(); 12216 DeclarationNameInfo NameInfo(Name, ClassLoc); 12217 12218 // An implicitly-declared copy constructor is an inline public 12219 // member of its class. 12220 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12221 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12222 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12223 Constexpr); 12224 CopyConstructor->setAccess(AS_public); 12225 CopyConstructor->setDefaulted(); 12226 12227 if (getLangOpts().CUDA) { 12228 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12229 CopyConstructor, 12230 /* ConstRHS */ Const, 12231 /* Diagnose */ false); 12232 } 12233 12234 // Build an exception specification pointing back at this member. 12235 FunctionProtoType::ExtProtoInfo EPI = 12236 getImplicitMethodEPI(*this, CopyConstructor); 12237 CopyConstructor->setType( 12238 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12239 12240 // Add the parameter to the constructor. 12241 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12242 ClassLoc, ClassLoc, 12243 /*IdentifierInfo=*/nullptr, 12244 ArgType, /*TInfo=*/nullptr, 12245 SC_None, nullptr); 12246 CopyConstructor->setParams(FromParam); 12247 12248 CopyConstructor->setTrivial( 12249 ClassDecl->needsOverloadResolutionForCopyConstructor() 12250 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12251 : ClassDecl->hasTrivialCopyConstructor()); 12252 12253 CopyConstructor->setTrivialForCall( 12254 ClassDecl->hasAttr<TrivialABIAttr>() || 12255 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12256 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12257 TAH_ConsiderTrivialABI) 12258 : ClassDecl->hasTrivialCopyConstructorForCall())); 12259 12260 // Note that we have declared this constructor. 12261 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12262 12263 Scope *S = getScopeForContext(ClassDecl); 12264 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12265 12266 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12267 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12268 SetDeclDeleted(CopyConstructor, ClassLoc); 12269 } 12270 12271 if (S) 12272 PushOnScopeChains(CopyConstructor, S, false); 12273 ClassDecl->addDecl(CopyConstructor); 12274 12275 return CopyConstructor; 12276 } 12277 12278 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12279 CXXConstructorDecl *CopyConstructor) { 12280 assert((CopyConstructor->isDefaulted() && 12281 CopyConstructor->isCopyConstructor() && 12282 !CopyConstructor->doesThisDeclarationHaveABody() && 12283 !CopyConstructor->isDeleted()) && 12284 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12285 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12286 return; 12287 12288 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12289 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12290 12291 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12292 12293 // The exception specification is needed because we are defining the 12294 // function. 12295 ResolveExceptionSpec(CurrentLocation, 12296 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12297 MarkVTableUsed(CurrentLocation, ClassDecl); 12298 12299 // Add a context note for diagnostics produced after this point. 12300 Scope.addContextNote(CurrentLocation); 12301 12302 // C++11 [class.copy]p7: 12303 // The [definition of an implicitly declared copy constructor] is 12304 // deprecated if the class has a user-declared copy assignment operator 12305 // or a user-declared destructor. 12306 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12307 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12308 12309 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12310 CopyConstructor->setInvalidDecl(); 12311 } else { 12312 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12313 ? CopyConstructor->getLocEnd() 12314 : CopyConstructor->getLocation(); 12315 Sema::CompoundScopeRAII CompoundScope(*this); 12316 CopyConstructor->setBody( 12317 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12318 CopyConstructor->markUsed(Context); 12319 } 12320 12321 if (ASTMutationListener *L = getASTMutationListener()) { 12322 L->CompletedImplicitDefinition(CopyConstructor); 12323 } 12324 } 12325 12326 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12327 CXXRecordDecl *ClassDecl) { 12328 assert(ClassDecl->needsImplicitMoveConstructor()); 12329 12330 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12331 if (DSM.isAlreadyBeingDeclared()) 12332 return nullptr; 12333 12334 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12335 QualType ArgType = Context.getRValueReferenceType(ClassType); 12336 12337 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12338 CXXMoveConstructor, 12339 false); 12340 12341 DeclarationName Name 12342 = Context.DeclarationNames.getCXXConstructorName( 12343 Context.getCanonicalType(ClassType)); 12344 SourceLocation ClassLoc = ClassDecl->getLocation(); 12345 DeclarationNameInfo NameInfo(Name, ClassLoc); 12346 12347 // C++11 [class.copy]p11: 12348 // An implicitly-declared copy/move constructor is an inline public 12349 // member of its class. 12350 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12351 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12352 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12353 Constexpr); 12354 MoveConstructor->setAccess(AS_public); 12355 MoveConstructor->setDefaulted(); 12356 12357 if (getLangOpts().CUDA) { 12358 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12359 MoveConstructor, 12360 /* ConstRHS */ false, 12361 /* Diagnose */ false); 12362 } 12363 12364 // Build an exception specification pointing back at this member. 12365 FunctionProtoType::ExtProtoInfo EPI = 12366 getImplicitMethodEPI(*this, MoveConstructor); 12367 MoveConstructor->setType( 12368 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12369 12370 // Add the parameter to the constructor. 12371 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12372 ClassLoc, ClassLoc, 12373 /*IdentifierInfo=*/nullptr, 12374 ArgType, /*TInfo=*/nullptr, 12375 SC_None, nullptr); 12376 MoveConstructor->setParams(FromParam); 12377 12378 MoveConstructor->setTrivial( 12379 ClassDecl->needsOverloadResolutionForMoveConstructor() 12380 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12381 : ClassDecl->hasTrivialMoveConstructor()); 12382 12383 MoveConstructor->setTrivialForCall( 12384 ClassDecl->hasAttr<TrivialABIAttr>() || 12385 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12386 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12387 TAH_ConsiderTrivialABI) 12388 : ClassDecl->hasTrivialMoveConstructorForCall())); 12389 12390 // Note that we have declared this constructor. 12391 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12392 12393 Scope *S = getScopeForContext(ClassDecl); 12394 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12395 12396 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12397 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12398 SetDeclDeleted(MoveConstructor, ClassLoc); 12399 } 12400 12401 if (S) 12402 PushOnScopeChains(MoveConstructor, S, false); 12403 ClassDecl->addDecl(MoveConstructor); 12404 12405 return MoveConstructor; 12406 } 12407 12408 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12409 CXXConstructorDecl *MoveConstructor) { 12410 assert((MoveConstructor->isDefaulted() && 12411 MoveConstructor->isMoveConstructor() && 12412 !MoveConstructor->doesThisDeclarationHaveABody() && 12413 !MoveConstructor->isDeleted()) && 12414 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12415 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12416 return; 12417 12418 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12419 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12420 12421 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12422 12423 // The exception specification is needed because we are defining the 12424 // function. 12425 ResolveExceptionSpec(CurrentLocation, 12426 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12427 MarkVTableUsed(CurrentLocation, ClassDecl); 12428 12429 // Add a context note for diagnostics produced after this point. 12430 Scope.addContextNote(CurrentLocation); 12431 12432 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12433 MoveConstructor->setInvalidDecl(); 12434 } else { 12435 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12436 ? MoveConstructor->getLocEnd() 12437 : MoveConstructor->getLocation(); 12438 Sema::CompoundScopeRAII CompoundScope(*this); 12439 MoveConstructor->setBody(ActOnCompoundStmt( 12440 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12441 MoveConstructor->markUsed(Context); 12442 } 12443 12444 if (ASTMutationListener *L = getASTMutationListener()) { 12445 L->CompletedImplicitDefinition(MoveConstructor); 12446 } 12447 } 12448 12449 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12450 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12451 } 12452 12453 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12454 SourceLocation CurrentLocation, 12455 CXXConversionDecl *Conv) { 12456 SynthesizedFunctionScope Scope(*this, Conv); 12457 assert(!Conv->getReturnType()->isUndeducedType()); 12458 12459 CXXRecordDecl *Lambda = Conv->getParent(); 12460 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12461 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12462 12463 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12464 CallOp = InstantiateFunctionDeclaration( 12465 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12466 if (!CallOp) 12467 return; 12468 12469 Invoker = InstantiateFunctionDeclaration( 12470 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12471 if (!Invoker) 12472 return; 12473 } 12474 12475 if (CallOp->isInvalidDecl()) 12476 return; 12477 12478 // Mark the call operator referenced (and add to pending instantiations 12479 // if necessary). 12480 // For both the conversion and static-invoker template specializations 12481 // we construct their body's in this function, so no need to add them 12482 // to the PendingInstantiations. 12483 MarkFunctionReferenced(CurrentLocation, CallOp); 12484 12485 // Fill in the __invoke function with a dummy implementation. IR generation 12486 // will fill in the actual details. Update its type in case it contained 12487 // an 'auto'. 12488 Invoker->markUsed(Context); 12489 Invoker->setReferenced(); 12490 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12491 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12492 12493 // Construct the body of the conversion function { return __invoke; }. 12494 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12495 VK_LValue, Conv->getLocation()).get(); 12496 assert(FunctionRef && "Can't refer to __invoke function?"); 12497 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12498 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12499 Conv->getLocation())); 12500 Conv->markUsed(Context); 12501 Conv->setReferenced(); 12502 12503 if (ASTMutationListener *L = getASTMutationListener()) { 12504 L->CompletedImplicitDefinition(Conv); 12505 L->CompletedImplicitDefinition(Invoker); 12506 } 12507 } 12508 12509 12510 12511 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12512 SourceLocation CurrentLocation, 12513 CXXConversionDecl *Conv) 12514 { 12515 assert(!Conv->getParent()->isGenericLambda()); 12516 12517 SynthesizedFunctionScope Scope(*this, Conv); 12518 12519 // Copy-initialize the lambda object as needed to capture it. 12520 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12521 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12522 12523 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12524 Conv->getLocation(), 12525 Conv, DerefThis); 12526 12527 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12528 // behavior. Note that only the general conversion function does this 12529 // (since it's unusable otherwise); in the case where we inline the 12530 // block literal, it has block literal lifetime semantics. 12531 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12532 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12533 CK_CopyAndAutoreleaseBlockObject, 12534 BuildBlock.get(), nullptr, VK_RValue); 12535 12536 if (BuildBlock.isInvalid()) { 12537 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12538 Conv->setInvalidDecl(); 12539 return; 12540 } 12541 12542 // Create the return statement that returns the block from the conversion 12543 // function. 12544 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12545 if (Return.isInvalid()) { 12546 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12547 Conv->setInvalidDecl(); 12548 return; 12549 } 12550 12551 // Set the body of the conversion function. 12552 Stmt *ReturnS = Return.get(); 12553 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12554 Conv->getLocation())); 12555 Conv->markUsed(Context); 12556 12557 // We're done; notify the mutation listener, if any. 12558 if (ASTMutationListener *L = getASTMutationListener()) { 12559 L->CompletedImplicitDefinition(Conv); 12560 } 12561 } 12562 12563 /// \brief Determine whether the given list arguments contains exactly one 12564 /// "real" (non-default) argument. 12565 static bool hasOneRealArgument(MultiExprArg Args) { 12566 switch (Args.size()) { 12567 case 0: 12568 return false; 12569 12570 default: 12571 if (!Args[1]->isDefaultArgument()) 12572 return false; 12573 12574 LLVM_FALLTHROUGH; 12575 case 1: 12576 return !Args[0]->isDefaultArgument(); 12577 } 12578 12579 return false; 12580 } 12581 12582 ExprResult 12583 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12584 NamedDecl *FoundDecl, 12585 CXXConstructorDecl *Constructor, 12586 MultiExprArg ExprArgs, 12587 bool HadMultipleCandidates, 12588 bool IsListInitialization, 12589 bool IsStdInitListInitialization, 12590 bool RequiresZeroInit, 12591 unsigned ConstructKind, 12592 SourceRange ParenRange) { 12593 bool Elidable = false; 12594 12595 // C++0x [class.copy]p34: 12596 // When certain criteria are met, an implementation is allowed to 12597 // omit the copy/move construction of a class object, even if the 12598 // copy/move constructor and/or destructor for the object have 12599 // side effects. [...] 12600 // - when a temporary class object that has not been bound to a 12601 // reference (12.2) would be copied/moved to a class object 12602 // with the same cv-unqualified type, the copy/move operation 12603 // can be omitted by constructing the temporary object 12604 // directly into the target of the omitted copy/move 12605 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12606 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12607 Expr *SubExpr = ExprArgs[0]; 12608 Elidable = SubExpr->isTemporaryObject( 12609 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12610 } 12611 12612 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12613 FoundDecl, Constructor, 12614 Elidable, ExprArgs, HadMultipleCandidates, 12615 IsListInitialization, 12616 IsStdInitListInitialization, RequiresZeroInit, 12617 ConstructKind, ParenRange); 12618 } 12619 12620 ExprResult 12621 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12622 NamedDecl *FoundDecl, 12623 CXXConstructorDecl *Constructor, 12624 bool Elidable, 12625 MultiExprArg ExprArgs, 12626 bool HadMultipleCandidates, 12627 bool IsListInitialization, 12628 bool IsStdInitListInitialization, 12629 bool RequiresZeroInit, 12630 unsigned ConstructKind, 12631 SourceRange ParenRange) { 12632 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12633 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12634 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12635 return ExprError(); 12636 } 12637 12638 return BuildCXXConstructExpr( 12639 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12640 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12641 RequiresZeroInit, ConstructKind, ParenRange); 12642 } 12643 12644 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12645 /// including handling of its default argument expressions. 12646 ExprResult 12647 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12648 CXXConstructorDecl *Constructor, 12649 bool Elidable, 12650 MultiExprArg ExprArgs, 12651 bool HadMultipleCandidates, 12652 bool IsListInitialization, 12653 bool IsStdInitListInitialization, 12654 bool RequiresZeroInit, 12655 unsigned ConstructKind, 12656 SourceRange ParenRange) { 12657 assert(declaresSameEntity( 12658 Constructor->getParent(), 12659 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12660 "given constructor for wrong type"); 12661 MarkFunctionReferenced(ConstructLoc, Constructor); 12662 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12663 return ExprError(); 12664 12665 return CXXConstructExpr::Create( 12666 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12667 ExprArgs, HadMultipleCandidates, IsListInitialization, 12668 IsStdInitListInitialization, RequiresZeroInit, 12669 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12670 ParenRange); 12671 } 12672 12673 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12674 assert(Field->hasInClassInitializer()); 12675 12676 // If we already have the in-class initializer nothing needs to be done. 12677 if (Field->getInClassInitializer()) 12678 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12679 12680 // If we might have already tried and failed to instantiate, don't try again. 12681 if (Field->isInvalidDecl()) 12682 return ExprError(); 12683 12684 // Maybe we haven't instantiated the in-class initializer. Go check the 12685 // pattern FieldDecl to see if it has one. 12686 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12687 12688 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12689 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12690 DeclContext::lookup_result Lookup = 12691 ClassPattern->lookup(Field->getDeclName()); 12692 12693 // Lookup can return at most two results: the pattern for the field, or the 12694 // injected class name of the parent record. No other member can have the 12695 // same name as the field. 12696 // In modules mode, lookup can return multiple results (coming from 12697 // different modules). 12698 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12699 "more than two lookup results for field name"); 12700 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12701 if (!Pattern) { 12702 assert(isa<CXXRecordDecl>(Lookup[0]) && 12703 "cannot have other non-field member with same name"); 12704 for (auto L : Lookup) 12705 if (isa<FieldDecl>(L)) { 12706 Pattern = cast<FieldDecl>(L); 12707 break; 12708 } 12709 assert(Pattern && "We must have set the Pattern!"); 12710 } 12711 12712 if (!Pattern->hasInClassInitializer() || 12713 InstantiateInClassInitializer(Loc, Field, Pattern, 12714 getTemplateInstantiationArgs(Field))) { 12715 // Don't diagnose this again. 12716 Field->setInvalidDecl(); 12717 return ExprError(); 12718 } 12719 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12720 } 12721 12722 // DR1351: 12723 // If the brace-or-equal-initializer of a non-static data member 12724 // invokes a defaulted default constructor of its class or of an 12725 // enclosing class in a potentially evaluated subexpression, the 12726 // program is ill-formed. 12727 // 12728 // This resolution is unworkable: the exception specification of the 12729 // default constructor can be needed in an unevaluated context, in 12730 // particular, in the operand of a noexcept-expression, and we can be 12731 // unable to compute an exception specification for an enclosed class. 12732 // 12733 // Any attempt to resolve the exception specification of a defaulted default 12734 // constructor before the initializer is lexically complete will ultimately 12735 // come here at which point we can diagnose it. 12736 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12737 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12738 << OutermostClass << Field; 12739 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12740 // Recover by marking the field invalid, unless we're in a SFINAE context. 12741 if (!isSFINAEContext()) 12742 Field->setInvalidDecl(); 12743 return ExprError(); 12744 } 12745 12746 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12747 if (VD->isInvalidDecl()) return; 12748 12749 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12750 if (ClassDecl->isInvalidDecl()) return; 12751 if (ClassDecl->hasIrrelevantDestructor()) return; 12752 if (ClassDecl->isDependentContext()) return; 12753 12754 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12755 MarkFunctionReferenced(VD->getLocation(), Destructor); 12756 CheckDestructorAccess(VD->getLocation(), Destructor, 12757 PDiag(diag::err_access_dtor_var) 12758 << VD->getDeclName() 12759 << VD->getType()); 12760 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12761 12762 if (Destructor->isTrivial()) return; 12763 if (!VD->hasGlobalStorage()) return; 12764 12765 // Emit warning for non-trivial dtor in global scope (a real global, 12766 // class-static, function-static). 12767 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12768 12769 // TODO: this should be re-enabled for static locals by !CXAAtExit 12770 if (!VD->isStaticLocal()) 12771 Diag(VD->getLocation(), diag::warn_global_destructor); 12772 } 12773 12774 /// \brief Given a constructor and the set of arguments provided for the 12775 /// constructor, convert the arguments and add any required default arguments 12776 /// to form a proper call to this constructor. 12777 /// 12778 /// \returns true if an error occurred, false otherwise. 12779 bool 12780 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12781 MultiExprArg ArgsPtr, 12782 SourceLocation Loc, 12783 SmallVectorImpl<Expr*> &ConvertedArgs, 12784 bool AllowExplicit, 12785 bool IsListInitialization) { 12786 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12787 unsigned NumArgs = ArgsPtr.size(); 12788 Expr **Args = ArgsPtr.data(); 12789 12790 const FunctionProtoType *Proto 12791 = Constructor->getType()->getAs<FunctionProtoType>(); 12792 assert(Proto && "Constructor without a prototype?"); 12793 unsigned NumParams = Proto->getNumParams(); 12794 12795 // If too few arguments are available, we'll fill in the rest with defaults. 12796 if (NumArgs < NumParams) 12797 ConvertedArgs.reserve(NumParams); 12798 else 12799 ConvertedArgs.reserve(NumArgs); 12800 12801 VariadicCallType CallType = 12802 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12803 SmallVector<Expr *, 8> AllArgs; 12804 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12805 Proto, 0, 12806 llvm::makeArrayRef(Args, NumArgs), 12807 AllArgs, 12808 CallType, AllowExplicit, 12809 IsListInitialization); 12810 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12811 12812 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12813 12814 CheckConstructorCall(Constructor, 12815 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12816 Proto, Loc); 12817 12818 return Invalid; 12819 } 12820 12821 static inline bool 12822 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12823 const FunctionDecl *FnDecl) { 12824 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12825 if (isa<NamespaceDecl>(DC)) { 12826 return SemaRef.Diag(FnDecl->getLocation(), 12827 diag::err_operator_new_delete_declared_in_namespace) 12828 << FnDecl->getDeclName(); 12829 } 12830 12831 if (isa<TranslationUnitDecl>(DC) && 12832 FnDecl->getStorageClass() == SC_Static) { 12833 return SemaRef.Diag(FnDecl->getLocation(), 12834 diag::err_operator_new_delete_declared_static) 12835 << FnDecl->getDeclName(); 12836 } 12837 12838 return false; 12839 } 12840 12841 static inline bool 12842 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12843 CanQualType ExpectedResultType, 12844 CanQualType ExpectedFirstParamType, 12845 unsigned DependentParamTypeDiag, 12846 unsigned InvalidParamTypeDiag) { 12847 QualType ResultType = 12848 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12849 12850 // Check that the result type is not dependent. 12851 if (ResultType->isDependentType()) 12852 return SemaRef.Diag(FnDecl->getLocation(), 12853 diag::err_operator_new_delete_dependent_result_type) 12854 << FnDecl->getDeclName() << ExpectedResultType; 12855 12856 // Check that the result type is what we expect. 12857 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12858 return SemaRef.Diag(FnDecl->getLocation(), 12859 diag::err_operator_new_delete_invalid_result_type) 12860 << FnDecl->getDeclName() << ExpectedResultType; 12861 12862 // A function template must have at least 2 parameters. 12863 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12864 return SemaRef.Diag(FnDecl->getLocation(), 12865 diag::err_operator_new_delete_template_too_few_parameters) 12866 << FnDecl->getDeclName(); 12867 12868 // The function decl must have at least 1 parameter. 12869 if (FnDecl->getNumParams() == 0) 12870 return SemaRef.Diag(FnDecl->getLocation(), 12871 diag::err_operator_new_delete_too_few_parameters) 12872 << FnDecl->getDeclName(); 12873 12874 // Check the first parameter type is not dependent. 12875 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12876 if (FirstParamType->isDependentType()) 12877 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12878 << FnDecl->getDeclName() << ExpectedFirstParamType; 12879 12880 // Check that the first parameter type is what we expect. 12881 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12882 ExpectedFirstParamType) 12883 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12884 << FnDecl->getDeclName() << ExpectedFirstParamType; 12885 12886 return false; 12887 } 12888 12889 static bool 12890 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12891 // C++ [basic.stc.dynamic.allocation]p1: 12892 // A program is ill-formed if an allocation function is declared in a 12893 // namespace scope other than global scope or declared static in global 12894 // scope. 12895 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12896 return true; 12897 12898 CanQualType SizeTy = 12899 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12900 12901 // C++ [basic.stc.dynamic.allocation]p1: 12902 // The return type shall be void*. The first parameter shall have type 12903 // std::size_t. 12904 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12905 SizeTy, 12906 diag::err_operator_new_dependent_param_type, 12907 diag::err_operator_new_param_type)) 12908 return true; 12909 12910 // C++ [basic.stc.dynamic.allocation]p1: 12911 // The first parameter shall not have an associated default argument. 12912 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12913 return SemaRef.Diag(FnDecl->getLocation(), 12914 diag::err_operator_new_default_arg) 12915 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12916 12917 return false; 12918 } 12919 12920 static bool 12921 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12922 // C++ [basic.stc.dynamic.deallocation]p1: 12923 // A program is ill-formed if deallocation functions are declared in a 12924 // namespace scope other than global scope or declared static in global 12925 // scope. 12926 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12927 return true; 12928 12929 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 12930 12931 // C++ P0722: 12932 // Within a class C, the first parameter of a destroying operator delete 12933 // shall be of type C *. The first parameter of any other deallocation 12934 // function shall be of type void *. 12935 CanQualType ExpectedFirstParamType = 12936 MD && MD->isDestroyingOperatorDelete() 12937 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 12938 SemaRef.Context.getRecordType(MD->getParent()))) 12939 : SemaRef.Context.VoidPtrTy; 12940 12941 // C++ [basic.stc.dynamic.deallocation]p2: 12942 // Each deallocation function shall return void 12943 if (CheckOperatorNewDeleteTypes( 12944 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 12945 diag::err_operator_delete_dependent_param_type, 12946 diag::err_operator_delete_param_type)) 12947 return true; 12948 12949 // C++ P0722: 12950 // A destroying operator delete shall be a usual deallocation function. 12951 if (MD && !MD->getParent()->isDependentContext() && 12952 MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) { 12953 SemaRef.Diag(MD->getLocation(), 12954 diag::err_destroying_operator_delete_not_usual); 12955 return true; 12956 } 12957 12958 return false; 12959 } 12960 12961 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12962 /// of this overloaded operator is well-formed. If so, returns false; 12963 /// otherwise, emits appropriate diagnostics and returns true. 12964 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12965 assert(FnDecl && FnDecl->isOverloadedOperator() && 12966 "Expected an overloaded operator declaration"); 12967 12968 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12969 12970 // C++ [over.oper]p5: 12971 // The allocation and deallocation functions, operator new, 12972 // operator new[], operator delete and operator delete[], are 12973 // described completely in 3.7.3. The attributes and restrictions 12974 // found in the rest of this subclause do not apply to them unless 12975 // explicitly stated in 3.7.3. 12976 if (Op == OO_Delete || Op == OO_Array_Delete) 12977 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12978 12979 if (Op == OO_New || Op == OO_Array_New) 12980 return CheckOperatorNewDeclaration(*this, FnDecl); 12981 12982 // C++ [over.oper]p6: 12983 // An operator function shall either be a non-static member 12984 // function or be a non-member function and have at least one 12985 // parameter whose type is a class, a reference to a class, an 12986 // enumeration, or a reference to an enumeration. 12987 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12988 if (MethodDecl->isStatic()) 12989 return Diag(FnDecl->getLocation(), 12990 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12991 } else { 12992 bool ClassOrEnumParam = false; 12993 for (auto Param : FnDecl->parameters()) { 12994 QualType ParamType = Param->getType().getNonReferenceType(); 12995 if (ParamType->isDependentType() || ParamType->isRecordType() || 12996 ParamType->isEnumeralType()) { 12997 ClassOrEnumParam = true; 12998 break; 12999 } 13000 } 13001 13002 if (!ClassOrEnumParam) 13003 return Diag(FnDecl->getLocation(), 13004 diag::err_operator_overload_needs_class_or_enum) 13005 << FnDecl->getDeclName(); 13006 } 13007 13008 // C++ [over.oper]p8: 13009 // An operator function cannot have default arguments (8.3.6), 13010 // except where explicitly stated below. 13011 // 13012 // Only the function-call operator allows default arguments 13013 // (C++ [over.call]p1). 13014 if (Op != OO_Call) { 13015 for (auto Param : FnDecl->parameters()) { 13016 if (Param->hasDefaultArg()) 13017 return Diag(Param->getLocation(), 13018 diag::err_operator_overload_default_arg) 13019 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13020 } 13021 } 13022 13023 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13024 { false, false, false } 13025 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13026 , { Unary, Binary, MemberOnly } 13027 #include "clang/Basic/OperatorKinds.def" 13028 }; 13029 13030 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13031 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13032 bool MustBeMemberOperator = OperatorUses[Op][2]; 13033 13034 // C++ [over.oper]p8: 13035 // [...] Operator functions cannot have more or fewer parameters 13036 // than the number required for the corresponding operator, as 13037 // described in the rest of this subclause. 13038 unsigned NumParams = FnDecl->getNumParams() 13039 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13040 if (Op != OO_Call && 13041 ((NumParams == 1 && !CanBeUnaryOperator) || 13042 (NumParams == 2 && !CanBeBinaryOperator) || 13043 (NumParams < 1) || (NumParams > 2))) { 13044 // We have the wrong number of parameters. 13045 unsigned ErrorKind; 13046 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13047 ErrorKind = 2; // 2 -> unary or binary. 13048 } else if (CanBeUnaryOperator) { 13049 ErrorKind = 0; // 0 -> unary 13050 } else { 13051 assert(CanBeBinaryOperator && 13052 "All non-call overloaded operators are unary or binary!"); 13053 ErrorKind = 1; // 1 -> binary 13054 } 13055 13056 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13057 << FnDecl->getDeclName() << NumParams << ErrorKind; 13058 } 13059 13060 // Overloaded operators other than operator() cannot be variadic. 13061 if (Op != OO_Call && 13062 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13063 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13064 << FnDecl->getDeclName(); 13065 } 13066 13067 // Some operators must be non-static member functions. 13068 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13069 return Diag(FnDecl->getLocation(), 13070 diag::err_operator_overload_must_be_member) 13071 << FnDecl->getDeclName(); 13072 } 13073 13074 // C++ [over.inc]p1: 13075 // The user-defined function called operator++ implements the 13076 // prefix and postfix ++ operator. If this function is a member 13077 // function with no parameters, or a non-member function with one 13078 // parameter of class or enumeration type, it defines the prefix 13079 // increment operator ++ for objects of that type. If the function 13080 // is a member function with one parameter (which shall be of type 13081 // int) or a non-member function with two parameters (the second 13082 // of which shall be of type int), it defines the postfix 13083 // increment operator ++ for objects of that type. 13084 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13085 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13086 QualType ParamType = LastParam->getType(); 13087 13088 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13089 !ParamType->isDependentType()) 13090 return Diag(LastParam->getLocation(), 13091 diag::err_operator_overload_post_incdec_must_be_int) 13092 << LastParam->getType() << (Op == OO_MinusMinus); 13093 } 13094 13095 return false; 13096 } 13097 13098 static bool 13099 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13100 FunctionTemplateDecl *TpDecl) { 13101 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13102 13103 // Must have one or two template parameters. 13104 if (TemplateParams->size() == 1) { 13105 NonTypeTemplateParmDecl *PmDecl = 13106 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13107 13108 // The template parameter must be a char parameter pack. 13109 if (PmDecl && PmDecl->isTemplateParameterPack() && 13110 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13111 return false; 13112 13113 } else if (TemplateParams->size() == 2) { 13114 TemplateTypeParmDecl *PmType = 13115 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13116 NonTypeTemplateParmDecl *PmArgs = 13117 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13118 13119 // The second template parameter must be a parameter pack with the 13120 // first template parameter as its type. 13121 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13122 PmArgs->isTemplateParameterPack()) { 13123 const TemplateTypeParmType *TArgs = 13124 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13125 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13126 TArgs->getIndex() == PmType->getIndex()) { 13127 if (!SemaRef.inTemplateInstantiation()) 13128 SemaRef.Diag(TpDecl->getLocation(), 13129 diag::ext_string_literal_operator_template); 13130 return false; 13131 } 13132 } 13133 } 13134 13135 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13136 diag::err_literal_operator_template) 13137 << TpDecl->getTemplateParameters()->getSourceRange(); 13138 return true; 13139 } 13140 13141 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13142 /// of this literal operator function is well-formed. If so, returns 13143 /// false; otherwise, emits appropriate diagnostics and returns true. 13144 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13145 if (isa<CXXMethodDecl>(FnDecl)) { 13146 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13147 << FnDecl->getDeclName(); 13148 return true; 13149 } 13150 13151 if (FnDecl->isExternC()) { 13152 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13153 if (const LinkageSpecDecl *LSD = 13154 FnDecl->getDeclContext()->getExternCContext()) 13155 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13156 return true; 13157 } 13158 13159 // This might be the definition of a literal operator template. 13160 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13161 13162 // This might be a specialization of a literal operator template. 13163 if (!TpDecl) 13164 TpDecl = FnDecl->getPrimaryTemplate(); 13165 13166 // template <char...> type operator "" name() and 13167 // template <class T, T...> type operator "" name() are the only valid 13168 // template signatures, and the only valid signatures with no parameters. 13169 if (TpDecl) { 13170 if (FnDecl->param_size() != 0) { 13171 Diag(FnDecl->getLocation(), 13172 diag::err_literal_operator_template_with_params); 13173 return true; 13174 } 13175 13176 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13177 return true; 13178 13179 } else if (FnDecl->param_size() == 1) { 13180 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13181 13182 QualType ParamType = Param->getType().getUnqualifiedType(); 13183 13184 // Only unsigned long long int, long double, any character type, and const 13185 // char * are allowed as the only parameters. 13186 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13187 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13188 Context.hasSameType(ParamType, Context.CharTy) || 13189 Context.hasSameType(ParamType, Context.WideCharTy) || 13190 Context.hasSameType(ParamType, Context.Char16Ty) || 13191 Context.hasSameType(ParamType, Context.Char32Ty)) { 13192 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13193 QualType InnerType = Ptr->getPointeeType(); 13194 13195 // Pointer parameter must be a const char *. 13196 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13197 Context.CharTy) && 13198 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13199 Diag(Param->getSourceRange().getBegin(), 13200 diag::err_literal_operator_param) 13201 << ParamType << "'const char *'" << Param->getSourceRange(); 13202 return true; 13203 } 13204 13205 } else if (ParamType->isRealFloatingType()) { 13206 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13207 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13208 return true; 13209 13210 } else if (ParamType->isIntegerType()) { 13211 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13212 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13213 return true; 13214 13215 } else { 13216 Diag(Param->getSourceRange().getBegin(), 13217 diag::err_literal_operator_invalid_param) 13218 << ParamType << Param->getSourceRange(); 13219 return true; 13220 } 13221 13222 } else if (FnDecl->param_size() == 2) { 13223 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13224 13225 // First, verify that the first parameter is correct. 13226 13227 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13228 13229 // Two parameter function must have a pointer to const as a 13230 // first parameter; let's strip those qualifiers. 13231 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13232 13233 if (!PT) { 13234 Diag((*Param)->getSourceRange().getBegin(), 13235 diag::err_literal_operator_param) 13236 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13237 return true; 13238 } 13239 13240 QualType PointeeType = PT->getPointeeType(); 13241 // First parameter must be const 13242 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13243 Diag((*Param)->getSourceRange().getBegin(), 13244 diag::err_literal_operator_param) 13245 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13246 return true; 13247 } 13248 13249 QualType InnerType = PointeeType.getUnqualifiedType(); 13250 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 13251 // are allowed as the first parameter to a two-parameter function 13252 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13253 Context.hasSameType(InnerType, Context.WideCharTy) || 13254 Context.hasSameType(InnerType, Context.Char16Ty) || 13255 Context.hasSameType(InnerType, Context.Char32Ty))) { 13256 Diag((*Param)->getSourceRange().getBegin(), 13257 diag::err_literal_operator_param) 13258 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13259 return true; 13260 } 13261 13262 // Move on to the second and final parameter. 13263 ++Param; 13264 13265 // The second parameter must be a std::size_t. 13266 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13267 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13268 Diag((*Param)->getSourceRange().getBegin(), 13269 diag::err_literal_operator_param) 13270 << SecondParamType << Context.getSizeType() 13271 << (*Param)->getSourceRange(); 13272 return true; 13273 } 13274 } else { 13275 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13276 return true; 13277 } 13278 13279 // Parameters are good. 13280 13281 // A parameter-declaration-clause containing a default argument is not 13282 // equivalent to any of the permitted forms. 13283 for (auto Param : FnDecl->parameters()) { 13284 if (Param->hasDefaultArg()) { 13285 Diag(Param->getDefaultArgRange().getBegin(), 13286 diag::err_literal_operator_default_argument) 13287 << Param->getDefaultArgRange(); 13288 break; 13289 } 13290 } 13291 13292 StringRef LiteralName 13293 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13294 if (LiteralName[0] != '_' && 13295 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13296 // C++11 [usrlit.suffix]p1: 13297 // Literal suffix identifiers that do not start with an underscore 13298 // are reserved for future standardization. 13299 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13300 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13301 } 13302 13303 return false; 13304 } 13305 13306 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13307 /// linkage specification, including the language and (if present) 13308 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13309 /// language string literal. LBraceLoc, if valid, provides the location of 13310 /// the '{' brace. Otherwise, this linkage specification does not 13311 /// have any braces. 13312 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13313 Expr *LangStr, 13314 SourceLocation LBraceLoc) { 13315 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13316 if (!Lit->isAscii()) { 13317 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13318 << LangStr->getSourceRange(); 13319 return nullptr; 13320 } 13321 13322 StringRef Lang = Lit->getString(); 13323 LinkageSpecDecl::LanguageIDs Language; 13324 if (Lang == "C") 13325 Language = LinkageSpecDecl::lang_c; 13326 else if (Lang == "C++") 13327 Language = LinkageSpecDecl::lang_cxx; 13328 else { 13329 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13330 << LangStr->getSourceRange(); 13331 return nullptr; 13332 } 13333 13334 // FIXME: Add all the various semantics of linkage specifications 13335 13336 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13337 LangStr->getExprLoc(), Language, 13338 LBraceLoc.isValid()); 13339 CurContext->addDecl(D); 13340 PushDeclContext(S, D); 13341 return D; 13342 } 13343 13344 /// ActOnFinishLinkageSpecification - Complete the definition of 13345 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13346 /// valid, it's the position of the closing '}' brace in a linkage 13347 /// specification that uses braces. 13348 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13349 Decl *LinkageSpec, 13350 SourceLocation RBraceLoc) { 13351 if (RBraceLoc.isValid()) { 13352 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13353 LSDecl->setRBraceLoc(RBraceLoc); 13354 } 13355 PopDeclContext(); 13356 return LinkageSpec; 13357 } 13358 13359 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13360 AttributeList *AttrList, 13361 SourceLocation SemiLoc) { 13362 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13363 // Attribute declarations appertain to empty declaration so we handle 13364 // them here. 13365 if (AttrList) 13366 ProcessDeclAttributeList(S, ED, AttrList); 13367 13368 CurContext->addDecl(ED); 13369 return ED; 13370 } 13371 13372 /// \brief Perform semantic analysis for the variable declaration that 13373 /// occurs within a C++ catch clause, returning the newly-created 13374 /// variable. 13375 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13376 TypeSourceInfo *TInfo, 13377 SourceLocation StartLoc, 13378 SourceLocation Loc, 13379 IdentifierInfo *Name) { 13380 bool Invalid = false; 13381 QualType ExDeclType = TInfo->getType(); 13382 13383 // Arrays and functions decay. 13384 if (ExDeclType->isArrayType()) 13385 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13386 else if (ExDeclType->isFunctionType()) 13387 ExDeclType = Context.getPointerType(ExDeclType); 13388 13389 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13390 // The exception-declaration shall not denote a pointer or reference to an 13391 // incomplete type, other than [cv] void*. 13392 // N2844 forbids rvalue references. 13393 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13394 Diag(Loc, diag::err_catch_rvalue_ref); 13395 Invalid = true; 13396 } 13397 13398 if (ExDeclType->isVariablyModifiedType()) { 13399 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13400 Invalid = true; 13401 } 13402 13403 QualType BaseType = ExDeclType; 13404 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13405 unsigned DK = diag::err_catch_incomplete; 13406 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13407 BaseType = Ptr->getPointeeType(); 13408 Mode = 1; 13409 DK = diag::err_catch_incomplete_ptr; 13410 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13411 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13412 BaseType = Ref->getPointeeType(); 13413 Mode = 2; 13414 DK = diag::err_catch_incomplete_ref; 13415 } 13416 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13417 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13418 Invalid = true; 13419 13420 if (!Invalid && !ExDeclType->isDependentType() && 13421 RequireNonAbstractType(Loc, ExDeclType, 13422 diag::err_abstract_type_in_decl, 13423 AbstractVariableType)) 13424 Invalid = true; 13425 13426 // Only the non-fragile NeXT runtime currently supports C++ catches 13427 // of ObjC types, and no runtime supports catching ObjC types by value. 13428 if (!Invalid && getLangOpts().ObjC1) { 13429 QualType T = ExDeclType; 13430 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13431 T = RT->getPointeeType(); 13432 13433 if (T->isObjCObjectType()) { 13434 Diag(Loc, diag::err_objc_object_catch); 13435 Invalid = true; 13436 } else if (T->isObjCObjectPointerType()) { 13437 // FIXME: should this be a test for macosx-fragile specifically? 13438 if (getLangOpts().ObjCRuntime.isFragile()) 13439 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13440 } 13441 } 13442 13443 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13444 ExDeclType, TInfo, SC_None); 13445 ExDecl->setExceptionVariable(true); 13446 13447 // In ARC, infer 'retaining' for variables of retainable type. 13448 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13449 Invalid = true; 13450 13451 if (!Invalid && !ExDeclType->isDependentType()) { 13452 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13453 // Insulate this from anything else we might currently be parsing. 13454 EnterExpressionEvaluationContext scope( 13455 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13456 13457 // C++ [except.handle]p16: 13458 // The object declared in an exception-declaration or, if the 13459 // exception-declaration does not specify a name, a temporary (12.2) is 13460 // copy-initialized (8.5) from the exception object. [...] 13461 // The object is destroyed when the handler exits, after the destruction 13462 // of any automatic objects initialized within the handler. 13463 // 13464 // We just pretend to initialize the object with itself, then make sure 13465 // it can be destroyed later. 13466 QualType initType = Context.getExceptionObjectType(ExDeclType); 13467 13468 InitializedEntity entity = 13469 InitializedEntity::InitializeVariable(ExDecl); 13470 InitializationKind initKind = 13471 InitializationKind::CreateCopy(Loc, SourceLocation()); 13472 13473 Expr *opaqueValue = 13474 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13475 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13476 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13477 if (result.isInvalid()) 13478 Invalid = true; 13479 else { 13480 // If the constructor used was non-trivial, set this as the 13481 // "initializer". 13482 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13483 if (!construct->getConstructor()->isTrivial()) { 13484 Expr *init = MaybeCreateExprWithCleanups(construct); 13485 ExDecl->setInit(init); 13486 } 13487 13488 // And make sure it's destructable. 13489 FinalizeVarWithDestructor(ExDecl, recordType); 13490 } 13491 } 13492 } 13493 13494 if (Invalid) 13495 ExDecl->setInvalidDecl(); 13496 13497 return ExDecl; 13498 } 13499 13500 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13501 /// handler. 13502 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13503 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13504 bool Invalid = D.isInvalidType(); 13505 13506 // Check for unexpanded parameter packs. 13507 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13508 UPPC_ExceptionType)) { 13509 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13510 D.getIdentifierLoc()); 13511 Invalid = true; 13512 } 13513 13514 IdentifierInfo *II = D.getIdentifier(); 13515 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13516 LookupOrdinaryName, 13517 ForVisibleRedeclaration)) { 13518 // The scope should be freshly made just for us. There is just no way 13519 // it contains any previous declaration, except for function parameters in 13520 // a function-try-block's catch statement. 13521 assert(!S->isDeclScope(PrevDecl)); 13522 if (isDeclInScope(PrevDecl, CurContext, S)) { 13523 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13524 << D.getIdentifier(); 13525 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13526 Invalid = true; 13527 } else if (PrevDecl->isTemplateParameter()) 13528 // Maybe we will complain about the shadowed template parameter. 13529 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13530 } 13531 13532 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13533 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13534 << D.getCXXScopeSpec().getRange(); 13535 Invalid = true; 13536 } 13537 13538 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13539 D.getLocStart(), 13540 D.getIdentifierLoc(), 13541 D.getIdentifier()); 13542 if (Invalid) 13543 ExDecl->setInvalidDecl(); 13544 13545 // Add the exception declaration into this scope. 13546 if (II) 13547 PushOnScopeChains(ExDecl, S); 13548 else 13549 CurContext->addDecl(ExDecl); 13550 13551 ProcessDeclAttributes(S, ExDecl, D); 13552 return ExDecl; 13553 } 13554 13555 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13556 Expr *AssertExpr, 13557 Expr *AssertMessageExpr, 13558 SourceLocation RParenLoc) { 13559 StringLiteral *AssertMessage = 13560 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13561 13562 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13563 return nullptr; 13564 13565 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13566 AssertMessage, RParenLoc, false); 13567 } 13568 13569 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13570 Expr *AssertExpr, 13571 StringLiteral *AssertMessage, 13572 SourceLocation RParenLoc, 13573 bool Failed) { 13574 assert(AssertExpr != nullptr && "Expected non-null condition"); 13575 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13576 !Failed) { 13577 // In a static_assert-declaration, the constant-expression shall be a 13578 // constant expression that can be contextually converted to bool. 13579 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13580 if (Converted.isInvalid()) 13581 Failed = true; 13582 13583 llvm::APSInt Cond; 13584 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13585 diag::err_static_assert_expression_is_not_constant, 13586 /*AllowFold=*/false).isInvalid()) 13587 Failed = true; 13588 13589 if (!Failed && !Cond) { 13590 SmallString<256> MsgBuffer; 13591 llvm::raw_svector_ostream Msg(MsgBuffer); 13592 if (AssertMessage) 13593 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13594 13595 Expr *InnerCond = nullptr; 13596 std::string InnerCondDescription; 13597 std::tie(InnerCond, InnerCondDescription) = 13598 findFailedBooleanCondition(Converted.get(), 13599 /*AllowTopLevelCond=*/false); 13600 if (InnerCond) { 13601 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13602 << InnerCondDescription << !AssertMessage 13603 << Msg.str() << InnerCond->getSourceRange(); 13604 } else { 13605 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13606 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13607 } 13608 Failed = true; 13609 } 13610 } 13611 13612 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13613 /*DiscardedValue*/false, 13614 /*IsConstexpr*/true); 13615 if (FullAssertExpr.isInvalid()) 13616 Failed = true; 13617 else 13618 AssertExpr = FullAssertExpr.get(); 13619 13620 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13621 AssertExpr, AssertMessage, RParenLoc, 13622 Failed); 13623 13624 CurContext->addDecl(Decl); 13625 return Decl; 13626 } 13627 13628 /// \brief Perform semantic analysis of the given friend type declaration. 13629 /// 13630 /// \returns A friend declaration that. 13631 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13632 SourceLocation FriendLoc, 13633 TypeSourceInfo *TSInfo) { 13634 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13635 13636 QualType T = TSInfo->getType(); 13637 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13638 13639 // C++03 [class.friend]p2: 13640 // An elaborated-type-specifier shall be used in a friend declaration 13641 // for a class.* 13642 // 13643 // * The class-key of the elaborated-type-specifier is required. 13644 if (!CodeSynthesisContexts.empty()) { 13645 // Do not complain about the form of friend template types during any kind 13646 // of code synthesis. For template instantiation, we will have complained 13647 // when the template was defined. 13648 } else { 13649 if (!T->isElaboratedTypeSpecifier()) { 13650 // If we evaluated the type to a record type, suggest putting 13651 // a tag in front. 13652 if (const RecordType *RT = T->getAs<RecordType>()) { 13653 RecordDecl *RD = RT->getDecl(); 13654 13655 SmallString<16> InsertionText(" "); 13656 InsertionText += RD->getKindName(); 13657 13658 Diag(TypeRange.getBegin(), 13659 getLangOpts().CPlusPlus11 ? 13660 diag::warn_cxx98_compat_unelaborated_friend_type : 13661 diag::ext_unelaborated_friend_type) 13662 << (unsigned) RD->getTagKind() 13663 << T 13664 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13665 InsertionText); 13666 } else { 13667 Diag(FriendLoc, 13668 getLangOpts().CPlusPlus11 ? 13669 diag::warn_cxx98_compat_nonclass_type_friend : 13670 diag::ext_nonclass_type_friend) 13671 << T 13672 << TypeRange; 13673 } 13674 } else if (T->getAs<EnumType>()) { 13675 Diag(FriendLoc, 13676 getLangOpts().CPlusPlus11 ? 13677 diag::warn_cxx98_compat_enum_friend : 13678 diag::ext_enum_friend) 13679 << T 13680 << TypeRange; 13681 } 13682 13683 // C++11 [class.friend]p3: 13684 // A friend declaration that does not declare a function shall have one 13685 // of the following forms: 13686 // friend elaborated-type-specifier ; 13687 // friend simple-type-specifier ; 13688 // friend typename-specifier ; 13689 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13690 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13691 } 13692 13693 // If the type specifier in a friend declaration designates a (possibly 13694 // cv-qualified) class type, that class is declared as a friend; otherwise, 13695 // the friend declaration is ignored. 13696 return FriendDecl::Create(Context, CurContext, 13697 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13698 FriendLoc); 13699 } 13700 13701 /// Handle a friend tag declaration where the scope specifier was 13702 /// templated. 13703 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13704 unsigned TagSpec, SourceLocation TagLoc, 13705 CXXScopeSpec &SS, 13706 IdentifierInfo *Name, 13707 SourceLocation NameLoc, 13708 AttributeList *Attr, 13709 MultiTemplateParamsArg TempParamLists) { 13710 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13711 13712 bool IsMemberSpecialization = false; 13713 bool Invalid = false; 13714 13715 if (TemplateParameterList *TemplateParams = 13716 MatchTemplateParametersToScopeSpecifier( 13717 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13718 IsMemberSpecialization, Invalid)) { 13719 if (TemplateParams->size() > 0) { 13720 // This is a declaration of a class template. 13721 if (Invalid) 13722 return nullptr; 13723 13724 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13725 NameLoc, Attr, TemplateParams, AS_public, 13726 /*ModulePrivateLoc=*/SourceLocation(), 13727 FriendLoc, TempParamLists.size() - 1, 13728 TempParamLists.data()).get(); 13729 } else { 13730 // The "template<>" header is extraneous. 13731 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13732 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13733 IsMemberSpecialization = true; 13734 } 13735 } 13736 13737 if (Invalid) return nullptr; 13738 13739 bool isAllExplicitSpecializations = true; 13740 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13741 if (TempParamLists[I]->size()) { 13742 isAllExplicitSpecializations = false; 13743 break; 13744 } 13745 } 13746 13747 // FIXME: don't ignore attributes. 13748 13749 // If it's explicit specializations all the way down, just forget 13750 // about the template header and build an appropriate non-templated 13751 // friend. TODO: for source fidelity, remember the headers. 13752 if (isAllExplicitSpecializations) { 13753 if (SS.isEmpty()) { 13754 bool Owned = false; 13755 bool IsDependent = false; 13756 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13757 Attr, AS_public, 13758 /*ModulePrivateLoc=*/SourceLocation(), 13759 MultiTemplateParamsArg(), Owned, IsDependent, 13760 /*ScopedEnumKWLoc=*/SourceLocation(), 13761 /*ScopedEnumUsesClassTag=*/false, 13762 /*UnderlyingType=*/TypeResult(), 13763 /*IsTypeSpecifier=*/false, 13764 /*IsTemplateParamOrArg=*/false); 13765 } 13766 13767 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13768 ElaboratedTypeKeyword Keyword 13769 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13770 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13771 *Name, NameLoc); 13772 if (T.isNull()) 13773 return nullptr; 13774 13775 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13776 if (isa<DependentNameType>(T)) { 13777 DependentNameTypeLoc TL = 13778 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13779 TL.setElaboratedKeywordLoc(TagLoc); 13780 TL.setQualifierLoc(QualifierLoc); 13781 TL.setNameLoc(NameLoc); 13782 } else { 13783 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13784 TL.setElaboratedKeywordLoc(TagLoc); 13785 TL.setQualifierLoc(QualifierLoc); 13786 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13787 } 13788 13789 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13790 TSI, FriendLoc, TempParamLists); 13791 Friend->setAccess(AS_public); 13792 CurContext->addDecl(Friend); 13793 return Friend; 13794 } 13795 13796 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13797 13798 13799 13800 // Handle the case of a templated-scope friend class. e.g. 13801 // template <class T> class A<T>::B; 13802 // FIXME: we don't support these right now. 13803 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13804 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13805 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13806 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13807 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13808 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13809 TL.setElaboratedKeywordLoc(TagLoc); 13810 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13811 TL.setNameLoc(NameLoc); 13812 13813 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13814 TSI, FriendLoc, TempParamLists); 13815 Friend->setAccess(AS_public); 13816 Friend->setUnsupportedFriend(true); 13817 CurContext->addDecl(Friend); 13818 return Friend; 13819 } 13820 13821 13822 /// Handle a friend type declaration. This works in tandem with 13823 /// ActOnTag. 13824 /// 13825 /// Notes on friend class templates: 13826 /// 13827 /// We generally treat friend class declarations as if they were 13828 /// declaring a class. So, for example, the elaborated type specifier 13829 /// in a friend declaration is required to obey the restrictions of a 13830 /// class-head (i.e. no typedefs in the scope chain), template 13831 /// parameters are required to match up with simple template-ids, &c. 13832 /// However, unlike when declaring a template specialization, it's 13833 /// okay to refer to a template specialization without an empty 13834 /// template parameter declaration, e.g. 13835 /// friend class A<T>::B<unsigned>; 13836 /// We permit this as a special case; if there are any template 13837 /// parameters present at all, require proper matching, i.e. 13838 /// template <> template \<class T> friend class A<int>::B; 13839 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13840 MultiTemplateParamsArg TempParams) { 13841 SourceLocation Loc = DS.getLocStart(); 13842 13843 assert(DS.isFriendSpecified()); 13844 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13845 13846 // Try to convert the decl specifier to a type. This works for 13847 // friend templates because ActOnTag never produces a ClassTemplateDecl 13848 // for a TUK_Friend. 13849 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 13850 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13851 QualType T = TSI->getType(); 13852 if (TheDeclarator.isInvalidType()) 13853 return nullptr; 13854 13855 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13856 return nullptr; 13857 13858 // This is definitely an error in C++98. It's probably meant to 13859 // be forbidden in C++0x, too, but the specification is just 13860 // poorly written. 13861 // 13862 // The problem is with declarations like the following: 13863 // template <T> friend A<T>::foo; 13864 // where deciding whether a class C is a friend or not now hinges 13865 // on whether there exists an instantiation of A that causes 13866 // 'foo' to equal C. There are restrictions on class-heads 13867 // (which we declare (by fiat) elaborated friend declarations to 13868 // be) that makes this tractable. 13869 // 13870 // FIXME: handle "template <> friend class A<T>;", which 13871 // is possibly well-formed? Who even knows? 13872 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13873 Diag(Loc, diag::err_tagless_friend_type_template) 13874 << DS.getSourceRange(); 13875 return nullptr; 13876 } 13877 13878 // C++98 [class.friend]p1: A friend of a class is a function 13879 // or class that is not a member of the class . . . 13880 // This is fixed in DR77, which just barely didn't make the C++03 13881 // deadline. It's also a very silly restriction that seriously 13882 // affects inner classes and which nobody else seems to implement; 13883 // thus we never diagnose it, not even in -pedantic. 13884 // 13885 // But note that we could warn about it: it's always useless to 13886 // friend one of your own members (it's not, however, worthless to 13887 // friend a member of an arbitrary specialization of your template). 13888 13889 Decl *D; 13890 if (!TempParams.empty()) 13891 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13892 TempParams, 13893 TSI, 13894 DS.getFriendSpecLoc()); 13895 else 13896 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13897 13898 if (!D) 13899 return nullptr; 13900 13901 D->setAccess(AS_public); 13902 CurContext->addDecl(D); 13903 13904 return D; 13905 } 13906 13907 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13908 MultiTemplateParamsArg TemplateParams) { 13909 const DeclSpec &DS = D.getDeclSpec(); 13910 13911 assert(DS.isFriendSpecified()); 13912 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13913 13914 SourceLocation Loc = D.getIdentifierLoc(); 13915 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13916 13917 // C++ [class.friend]p1 13918 // A friend of a class is a function or class.... 13919 // Note that this sees through typedefs, which is intended. 13920 // It *doesn't* see through dependent types, which is correct 13921 // according to [temp.arg.type]p3: 13922 // If a declaration acquires a function type through a 13923 // type dependent on a template-parameter and this causes 13924 // a declaration that does not use the syntactic form of a 13925 // function declarator to have a function type, the program 13926 // is ill-formed. 13927 if (!TInfo->getType()->isFunctionType()) { 13928 Diag(Loc, diag::err_unexpected_friend); 13929 13930 // It might be worthwhile to try to recover by creating an 13931 // appropriate declaration. 13932 return nullptr; 13933 } 13934 13935 // C++ [namespace.memdef]p3 13936 // - If a friend declaration in a non-local class first declares a 13937 // class or function, the friend class or function is a member 13938 // of the innermost enclosing namespace. 13939 // - The name of the friend is not found by simple name lookup 13940 // until a matching declaration is provided in that namespace 13941 // scope (either before or after the class declaration granting 13942 // friendship). 13943 // - If a friend function is called, its name may be found by the 13944 // name lookup that considers functions from namespaces and 13945 // classes associated with the types of the function arguments. 13946 // - When looking for a prior declaration of a class or a function 13947 // declared as a friend, scopes outside the innermost enclosing 13948 // namespace scope are not considered. 13949 13950 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13951 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13952 DeclarationName Name = NameInfo.getName(); 13953 assert(Name); 13954 13955 // Check for unexpanded parameter packs. 13956 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13957 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13958 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13959 return nullptr; 13960 13961 // The context we found the declaration in, or in which we should 13962 // create the declaration. 13963 DeclContext *DC; 13964 Scope *DCScope = S; 13965 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13966 ForExternalRedeclaration); 13967 13968 // There are five cases here. 13969 // - There's no scope specifier and we're in a local class. Only look 13970 // for functions declared in the immediately-enclosing block scope. 13971 // We recover from invalid scope qualifiers as if they just weren't there. 13972 FunctionDecl *FunctionContainingLocalClass = nullptr; 13973 if ((SS.isInvalid() || !SS.isSet()) && 13974 (FunctionContainingLocalClass = 13975 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13976 // C++11 [class.friend]p11: 13977 // If a friend declaration appears in a local class and the name 13978 // specified is an unqualified name, a prior declaration is 13979 // looked up without considering scopes that are outside the 13980 // innermost enclosing non-class scope. For a friend function 13981 // declaration, if there is no prior declaration, the program is 13982 // ill-formed. 13983 13984 // Find the innermost enclosing non-class scope. This is the block 13985 // scope containing the local class definition (or for a nested class, 13986 // the outer local class). 13987 DCScope = S->getFnParent(); 13988 13989 // Look up the function name in the scope. 13990 Previous.clear(LookupLocalFriendName); 13991 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13992 13993 if (!Previous.empty()) { 13994 // All possible previous declarations must have the same context: 13995 // either they were declared at block scope or they are members of 13996 // one of the enclosing local classes. 13997 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13998 } else { 13999 // This is ill-formed, but provide the context that we would have 14000 // declared the function in, if we were permitted to, for error recovery. 14001 DC = FunctionContainingLocalClass; 14002 } 14003 adjustContextForLocalExternDecl(DC); 14004 14005 // C++ [class.friend]p6: 14006 // A function can be defined in a friend declaration of a class if and 14007 // only if the class is a non-local class (9.8), the function name is 14008 // unqualified, and the function has namespace scope. 14009 if (D.isFunctionDefinition()) { 14010 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14011 } 14012 14013 // - There's no scope specifier, in which case we just go to the 14014 // appropriate scope and look for a function or function template 14015 // there as appropriate. 14016 } else if (SS.isInvalid() || !SS.isSet()) { 14017 // C++11 [namespace.memdef]p3: 14018 // If the name in a friend declaration is neither qualified nor 14019 // a template-id and the declaration is a function or an 14020 // elaborated-type-specifier, the lookup to determine whether 14021 // the entity has been previously declared shall not consider 14022 // any scopes outside the innermost enclosing namespace. 14023 bool isTemplateId = 14024 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14025 14026 // Find the appropriate context according to the above. 14027 DC = CurContext; 14028 14029 // Skip class contexts. If someone can cite chapter and verse 14030 // for this behavior, that would be nice --- it's what GCC and 14031 // EDG do, and it seems like a reasonable intent, but the spec 14032 // really only says that checks for unqualified existing 14033 // declarations should stop at the nearest enclosing namespace, 14034 // not that they should only consider the nearest enclosing 14035 // namespace. 14036 while (DC->isRecord()) 14037 DC = DC->getParent(); 14038 14039 DeclContext *LookupDC = DC; 14040 while (LookupDC->isTransparentContext()) 14041 LookupDC = LookupDC->getParent(); 14042 14043 while (true) { 14044 LookupQualifiedName(Previous, LookupDC); 14045 14046 if (!Previous.empty()) { 14047 DC = LookupDC; 14048 break; 14049 } 14050 14051 if (isTemplateId) { 14052 if (isa<TranslationUnitDecl>(LookupDC)) break; 14053 } else { 14054 if (LookupDC->isFileContext()) break; 14055 } 14056 LookupDC = LookupDC->getParent(); 14057 } 14058 14059 DCScope = getScopeForDeclContext(S, DC); 14060 14061 // - There's a non-dependent scope specifier, in which case we 14062 // compute it and do a previous lookup there for a function 14063 // or function template. 14064 } else if (!SS.getScopeRep()->isDependent()) { 14065 DC = computeDeclContext(SS); 14066 if (!DC) return nullptr; 14067 14068 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14069 14070 LookupQualifiedName(Previous, DC); 14071 14072 // Ignore things found implicitly in the wrong scope. 14073 // TODO: better diagnostics for this case. Suggesting the right 14074 // qualified scope would be nice... 14075 LookupResult::Filter F = Previous.makeFilter(); 14076 while (F.hasNext()) { 14077 NamedDecl *D = F.next(); 14078 if (!DC->InEnclosingNamespaceSetOf( 14079 D->getDeclContext()->getRedeclContext())) 14080 F.erase(); 14081 } 14082 F.done(); 14083 14084 if (Previous.empty()) { 14085 D.setInvalidType(); 14086 Diag(Loc, diag::err_qualified_friend_not_found) 14087 << Name << TInfo->getType(); 14088 return nullptr; 14089 } 14090 14091 // C++ [class.friend]p1: A friend of a class is a function or 14092 // class that is not a member of the class . . . 14093 if (DC->Equals(CurContext)) 14094 Diag(DS.getFriendSpecLoc(), 14095 getLangOpts().CPlusPlus11 ? 14096 diag::warn_cxx98_compat_friend_is_member : 14097 diag::err_friend_is_member); 14098 14099 if (D.isFunctionDefinition()) { 14100 // C++ [class.friend]p6: 14101 // A function can be defined in a friend declaration of a class if and 14102 // only if the class is a non-local class (9.8), the function name is 14103 // unqualified, and the function has namespace scope. 14104 SemaDiagnosticBuilder DB 14105 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14106 14107 DB << SS.getScopeRep(); 14108 if (DC->isFileContext()) 14109 DB << FixItHint::CreateRemoval(SS.getRange()); 14110 SS.clear(); 14111 } 14112 14113 // - There's a scope specifier that does not match any template 14114 // parameter lists, in which case we use some arbitrary context, 14115 // create a method or method template, and wait for instantiation. 14116 // - There's a scope specifier that does match some template 14117 // parameter lists, which we don't handle right now. 14118 } else { 14119 if (D.isFunctionDefinition()) { 14120 // C++ [class.friend]p6: 14121 // A function can be defined in a friend declaration of a class if and 14122 // only if the class is a non-local class (9.8), the function name is 14123 // unqualified, and the function has namespace scope. 14124 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14125 << SS.getScopeRep(); 14126 } 14127 14128 DC = CurContext; 14129 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14130 } 14131 14132 if (!DC->isRecord()) { 14133 int DiagArg = -1; 14134 switch (D.getName().getKind()) { 14135 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14136 case UnqualifiedIdKind::IK_ConstructorName: 14137 DiagArg = 0; 14138 break; 14139 case UnqualifiedIdKind::IK_DestructorName: 14140 DiagArg = 1; 14141 break; 14142 case UnqualifiedIdKind::IK_ConversionFunctionId: 14143 DiagArg = 2; 14144 break; 14145 case UnqualifiedIdKind::IK_DeductionGuideName: 14146 DiagArg = 3; 14147 break; 14148 case UnqualifiedIdKind::IK_Identifier: 14149 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14150 case UnqualifiedIdKind::IK_LiteralOperatorId: 14151 case UnqualifiedIdKind::IK_OperatorFunctionId: 14152 case UnqualifiedIdKind::IK_TemplateId: 14153 break; 14154 } 14155 // This implies that it has to be an operator or function. 14156 if (DiagArg >= 0) { 14157 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14158 return nullptr; 14159 } 14160 } 14161 14162 // FIXME: This is an egregious hack to cope with cases where the scope stack 14163 // does not contain the declaration context, i.e., in an out-of-line 14164 // definition of a class. 14165 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14166 if (!DCScope) { 14167 FakeDCScope.setEntity(DC); 14168 DCScope = &FakeDCScope; 14169 } 14170 14171 bool AddToScope = true; 14172 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14173 TemplateParams, AddToScope); 14174 if (!ND) return nullptr; 14175 14176 assert(ND->getLexicalDeclContext() == CurContext); 14177 14178 // If we performed typo correction, we might have added a scope specifier 14179 // and changed the decl context. 14180 DC = ND->getDeclContext(); 14181 14182 // Add the function declaration to the appropriate lookup tables, 14183 // adjusting the redeclarations list as necessary. We don't 14184 // want to do this yet if the friending class is dependent. 14185 // 14186 // Also update the scope-based lookup if the target context's 14187 // lookup context is in lexical scope. 14188 if (!CurContext->isDependentContext()) { 14189 DC = DC->getRedeclContext(); 14190 DC->makeDeclVisibleInContext(ND); 14191 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14192 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14193 } 14194 14195 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14196 D.getIdentifierLoc(), ND, 14197 DS.getFriendSpecLoc()); 14198 FrD->setAccess(AS_public); 14199 CurContext->addDecl(FrD); 14200 14201 if (ND->isInvalidDecl()) { 14202 FrD->setInvalidDecl(); 14203 } else { 14204 if (DC->isRecord()) CheckFriendAccess(ND); 14205 14206 FunctionDecl *FD; 14207 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14208 FD = FTD->getTemplatedDecl(); 14209 else 14210 FD = cast<FunctionDecl>(ND); 14211 14212 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14213 // default argument expression, that declaration shall be a definition 14214 // and shall be the only declaration of the function or function 14215 // template in the translation unit. 14216 if (functionDeclHasDefaultArgument(FD)) { 14217 // We can't look at FD->getPreviousDecl() because it may not have been set 14218 // if we're in a dependent context. If the function is known to be a 14219 // redeclaration, we will have narrowed Previous down to the right decl. 14220 if (D.isRedeclaration()) { 14221 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14222 Diag(Previous.getRepresentativeDecl()->getLocation(), 14223 diag::note_previous_declaration); 14224 } else if (!D.isFunctionDefinition()) 14225 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14226 } 14227 14228 // Mark templated-scope function declarations as unsupported. 14229 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14230 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14231 << SS.getScopeRep() << SS.getRange() 14232 << cast<CXXRecordDecl>(CurContext); 14233 FrD->setUnsupportedFriend(true); 14234 } 14235 } 14236 14237 return ND; 14238 } 14239 14240 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14241 AdjustDeclIfTemplate(Dcl); 14242 14243 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14244 if (!Fn) { 14245 Diag(DelLoc, diag::err_deleted_non_function); 14246 return; 14247 } 14248 14249 // Deleted function does not have a body. 14250 Fn->setWillHaveBody(false); 14251 14252 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14253 // Don't consider the implicit declaration we generate for explicit 14254 // specializations. FIXME: Do not generate these implicit declarations. 14255 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14256 Prev->getPreviousDecl()) && 14257 !Prev->isDefined()) { 14258 Diag(DelLoc, diag::err_deleted_decl_not_first); 14259 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14260 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14261 : diag::note_previous_declaration); 14262 } 14263 // If the declaration wasn't the first, we delete the function anyway for 14264 // recovery. 14265 Fn = Fn->getCanonicalDecl(); 14266 } 14267 14268 // dllimport/dllexport cannot be deleted. 14269 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14270 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14271 Fn->setInvalidDecl(); 14272 } 14273 14274 if (Fn->isDeleted()) 14275 return; 14276 14277 // See if we're deleting a function which is already known to override a 14278 // non-deleted virtual function. 14279 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14280 bool IssuedDiagnostic = false; 14281 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14282 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14283 if (!IssuedDiagnostic) { 14284 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14285 IssuedDiagnostic = true; 14286 } 14287 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14288 } 14289 } 14290 // If this function was implicitly deleted because it was defaulted, 14291 // explain why it was deleted. 14292 if (IssuedDiagnostic && MD->isDefaulted()) 14293 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14294 /*Diagnose*/true); 14295 } 14296 14297 // C++11 [basic.start.main]p3: 14298 // A program that defines main as deleted [...] is ill-formed. 14299 if (Fn->isMain()) 14300 Diag(DelLoc, diag::err_deleted_main); 14301 14302 // C++11 [dcl.fct.def.delete]p4: 14303 // A deleted function is implicitly inline. 14304 Fn->setImplicitlyInline(); 14305 Fn->setDeletedAsWritten(); 14306 } 14307 14308 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14309 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14310 14311 if (MD) { 14312 if (MD->getParent()->isDependentType()) { 14313 MD->setDefaulted(); 14314 MD->setExplicitlyDefaulted(); 14315 return; 14316 } 14317 14318 CXXSpecialMember Member = getSpecialMember(MD); 14319 if (Member == CXXInvalid) { 14320 if (!MD->isInvalidDecl()) 14321 Diag(DefaultLoc, diag::err_default_special_members); 14322 return; 14323 } 14324 14325 MD->setDefaulted(); 14326 MD->setExplicitlyDefaulted(); 14327 14328 // Unset that we will have a body for this function. We might not, 14329 // if it turns out to be trivial, and we don't need this marking now 14330 // that we've marked it as defaulted. 14331 MD->setWillHaveBody(false); 14332 14333 // If this definition appears within the record, do the checking when 14334 // the record is complete. 14335 const FunctionDecl *Primary = MD; 14336 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14337 // Ask the template instantiation pattern that actually had the 14338 // '= default' on it. 14339 Primary = Pattern; 14340 14341 // If the method was defaulted on its first declaration, we will have 14342 // already performed the checking in CheckCompletedCXXClass. Such a 14343 // declaration doesn't trigger an implicit definition. 14344 if (Primary->getCanonicalDecl()->isDefaulted()) 14345 return; 14346 14347 CheckExplicitlyDefaultedSpecialMember(MD); 14348 14349 if (!MD->isInvalidDecl()) 14350 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14351 } else { 14352 Diag(DefaultLoc, diag::err_default_special_members); 14353 } 14354 } 14355 14356 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14357 for (Stmt *SubStmt : S->children()) { 14358 if (!SubStmt) 14359 continue; 14360 if (isa<ReturnStmt>(SubStmt)) 14361 Self.Diag(SubStmt->getLocStart(), 14362 diag::err_return_in_constructor_handler); 14363 if (!isa<Expr>(SubStmt)) 14364 SearchForReturnInStmt(Self, SubStmt); 14365 } 14366 } 14367 14368 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14369 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14370 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14371 SearchForReturnInStmt(*this, Handler); 14372 } 14373 } 14374 14375 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14376 const CXXMethodDecl *Old) { 14377 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14378 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14379 14380 if (OldFT->hasExtParameterInfos()) { 14381 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14382 // A parameter of the overriding method should be annotated with noescape 14383 // if the corresponding parameter of the overridden method is annotated. 14384 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14385 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14386 Diag(New->getParamDecl(I)->getLocation(), 14387 diag::warn_overriding_method_missing_noescape); 14388 Diag(Old->getParamDecl(I)->getLocation(), 14389 diag::note_overridden_marked_noescape); 14390 } 14391 } 14392 14393 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14394 14395 // If the calling conventions match, everything is fine 14396 if (NewCC == OldCC) 14397 return false; 14398 14399 // If the calling conventions mismatch because the new function is static, 14400 // suppress the calling convention mismatch error; the error about static 14401 // function override (err_static_overrides_virtual from 14402 // Sema::CheckFunctionDeclaration) is more clear. 14403 if (New->getStorageClass() == SC_Static) 14404 return false; 14405 14406 Diag(New->getLocation(), 14407 diag::err_conflicting_overriding_cc_attributes) 14408 << New->getDeclName() << New->getType() << Old->getType(); 14409 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14410 return true; 14411 } 14412 14413 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14414 const CXXMethodDecl *Old) { 14415 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14416 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14417 14418 if (Context.hasSameType(NewTy, OldTy) || 14419 NewTy->isDependentType() || OldTy->isDependentType()) 14420 return false; 14421 14422 // Check if the return types are covariant 14423 QualType NewClassTy, OldClassTy; 14424 14425 /// Both types must be pointers or references to classes. 14426 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14427 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14428 NewClassTy = NewPT->getPointeeType(); 14429 OldClassTy = OldPT->getPointeeType(); 14430 } 14431 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14432 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14433 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14434 NewClassTy = NewRT->getPointeeType(); 14435 OldClassTy = OldRT->getPointeeType(); 14436 } 14437 } 14438 } 14439 14440 // The return types aren't either both pointers or references to a class type. 14441 if (NewClassTy.isNull()) { 14442 Diag(New->getLocation(), 14443 diag::err_different_return_type_for_overriding_virtual_function) 14444 << New->getDeclName() << NewTy << OldTy 14445 << New->getReturnTypeSourceRange(); 14446 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14447 << Old->getReturnTypeSourceRange(); 14448 14449 return true; 14450 } 14451 14452 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14453 // C++14 [class.virtual]p8: 14454 // If the class type in the covariant return type of D::f differs from 14455 // that of B::f, the class type in the return type of D::f shall be 14456 // complete at the point of declaration of D::f or shall be the class 14457 // type D. 14458 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14459 if (!RT->isBeingDefined() && 14460 RequireCompleteType(New->getLocation(), NewClassTy, 14461 diag::err_covariant_return_incomplete, 14462 New->getDeclName())) 14463 return true; 14464 } 14465 14466 // Check if the new class derives from the old class. 14467 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14468 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14469 << New->getDeclName() << NewTy << OldTy 14470 << New->getReturnTypeSourceRange(); 14471 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14472 << Old->getReturnTypeSourceRange(); 14473 return true; 14474 } 14475 14476 // Check if we the conversion from derived to base is valid. 14477 if (CheckDerivedToBaseConversion( 14478 NewClassTy, OldClassTy, 14479 diag::err_covariant_return_inaccessible_base, 14480 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14481 New->getLocation(), New->getReturnTypeSourceRange(), 14482 New->getDeclName(), nullptr)) { 14483 // FIXME: this note won't trigger for delayed access control 14484 // diagnostics, and it's impossible to get an undelayed error 14485 // here from access control during the original parse because 14486 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14487 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14488 << Old->getReturnTypeSourceRange(); 14489 return true; 14490 } 14491 } 14492 14493 // The qualifiers of the return types must be the same. 14494 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14495 Diag(New->getLocation(), 14496 diag::err_covariant_return_type_different_qualifications) 14497 << New->getDeclName() << NewTy << OldTy 14498 << New->getReturnTypeSourceRange(); 14499 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14500 << Old->getReturnTypeSourceRange(); 14501 return true; 14502 } 14503 14504 14505 // The new class type must have the same or less qualifiers as the old type. 14506 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14507 Diag(New->getLocation(), 14508 diag::err_covariant_return_type_class_type_more_qualified) 14509 << New->getDeclName() << NewTy << OldTy 14510 << New->getReturnTypeSourceRange(); 14511 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14512 << Old->getReturnTypeSourceRange(); 14513 return true; 14514 } 14515 14516 return false; 14517 } 14518 14519 /// \brief Mark the given method pure. 14520 /// 14521 /// \param Method the method to be marked pure. 14522 /// 14523 /// \param InitRange the source range that covers the "0" initializer. 14524 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14525 SourceLocation EndLoc = InitRange.getEnd(); 14526 if (EndLoc.isValid()) 14527 Method->setRangeEnd(EndLoc); 14528 14529 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14530 Method->setPure(); 14531 return false; 14532 } 14533 14534 if (!Method->isInvalidDecl()) 14535 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14536 << Method->getDeclName() << InitRange; 14537 return true; 14538 } 14539 14540 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14541 if (D->getFriendObjectKind()) 14542 Diag(D->getLocation(), diag::err_pure_friend); 14543 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14544 CheckPureMethod(M, ZeroLoc); 14545 else 14546 Diag(D->getLocation(), diag::err_illegal_initializer); 14547 } 14548 14549 /// \brief Determine whether the given declaration is a global variable or 14550 /// static data member. 14551 static bool isNonlocalVariable(const Decl *D) { 14552 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14553 return Var->hasGlobalStorage(); 14554 14555 return false; 14556 } 14557 14558 /// Invoked when we are about to parse an initializer for the declaration 14559 /// 'Dcl'. 14560 /// 14561 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14562 /// static data member of class X, names should be looked up in the scope of 14563 /// class X. If the declaration had a scope specifier, a scope will have 14564 /// been created and passed in for this purpose. Otherwise, S will be null. 14565 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14566 // If there is no declaration, there was an error parsing it. 14567 if (!D || D->isInvalidDecl()) 14568 return; 14569 14570 // We will always have a nested name specifier here, but this declaration 14571 // might not be out of line if the specifier names the current namespace: 14572 // extern int n; 14573 // int ::n = 0; 14574 if (S && D->isOutOfLine()) 14575 EnterDeclaratorContext(S, D->getDeclContext()); 14576 14577 // If we are parsing the initializer for a static data member, push a 14578 // new expression evaluation context that is associated with this static 14579 // data member. 14580 if (isNonlocalVariable(D)) 14581 PushExpressionEvaluationContext( 14582 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14583 } 14584 14585 /// Invoked after we are finished parsing an initializer for the declaration D. 14586 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14587 // If there is no declaration, there was an error parsing it. 14588 if (!D || D->isInvalidDecl()) 14589 return; 14590 14591 if (isNonlocalVariable(D)) 14592 PopExpressionEvaluationContext(); 14593 14594 if (S && D->isOutOfLine()) 14595 ExitDeclaratorContext(S); 14596 } 14597 14598 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14599 /// C++ if/switch/while/for statement. 14600 /// e.g: "if (int x = f()) {...}" 14601 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14602 // C++ 6.4p2: 14603 // The declarator shall not specify a function or an array. 14604 // The type-specifier-seq shall not contain typedef and shall not declare a 14605 // new class or enumeration. 14606 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14607 "Parser allowed 'typedef' as storage class of condition decl."); 14608 14609 Decl *Dcl = ActOnDeclarator(S, D); 14610 if (!Dcl) 14611 return true; 14612 14613 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14614 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14615 << D.getSourceRange(); 14616 return true; 14617 } 14618 14619 return Dcl; 14620 } 14621 14622 void Sema::LoadExternalVTableUses() { 14623 if (!ExternalSource) 14624 return; 14625 14626 SmallVector<ExternalVTableUse, 4> VTables; 14627 ExternalSource->ReadUsedVTables(VTables); 14628 SmallVector<VTableUse, 4> NewUses; 14629 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14630 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14631 = VTablesUsed.find(VTables[I].Record); 14632 // Even if a definition wasn't required before, it may be required now. 14633 if (Pos != VTablesUsed.end()) { 14634 if (!Pos->second && VTables[I].DefinitionRequired) 14635 Pos->second = true; 14636 continue; 14637 } 14638 14639 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14640 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14641 } 14642 14643 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14644 } 14645 14646 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14647 bool DefinitionRequired) { 14648 // Ignore any vtable uses in unevaluated operands or for classes that do 14649 // not have a vtable. 14650 if (!Class->isDynamicClass() || Class->isDependentContext() || 14651 CurContext->isDependentContext() || isUnevaluatedContext()) 14652 return; 14653 14654 // Try to insert this class into the map. 14655 LoadExternalVTableUses(); 14656 Class = Class->getCanonicalDecl(); 14657 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14658 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14659 if (!Pos.second) { 14660 // If we already had an entry, check to see if we are promoting this vtable 14661 // to require a definition. If so, we need to reappend to the VTableUses 14662 // list, since we may have already processed the first entry. 14663 if (DefinitionRequired && !Pos.first->second) { 14664 Pos.first->second = true; 14665 } else { 14666 // Otherwise, we can early exit. 14667 return; 14668 } 14669 } else { 14670 // The Microsoft ABI requires that we perform the destructor body 14671 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14672 // the deleting destructor is emitted with the vtable, not with the 14673 // destructor definition as in the Itanium ABI. 14674 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14675 CXXDestructorDecl *DD = Class->getDestructor(); 14676 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14677 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14678 // If this is an out-of-line declaration, marking it referenced will 14679 // not do anything. Manually call CheckDestructor to look up operator 14680 // delete(). 14681 ContextRAII SavedContext(*this, DD); 14682 CheckDestructor(DD); 14683 } else { 14684 MarkFunctionReferenced(Loc, Class->getDestructor()); 14685 } 14686 } 14687 } 14688 } 14689 14690 // Local classes need to have their virtual members marked 14691 // immediately. For all other classes, we mark their virtual members 14692 // at the end of the translation unit. 14693 if (Class->isLocalClass()) 14694 MarkVirtualMembersReferenced(Loc, Class); 14695 else 14696 VTableUses.push_back(std::make_pair(Class, Loc)); 14697 } 14698 14699 bool Sema::DefineUsedVTables() { 14700 LoadExternalVTableUses(); 14701 if (VTableUses.empty()) 14702 return false; 14703 14704 // Note: The VTableUses vector could grow as a result of marking 14705 // the members of a class as "used", so we check the size each 14706 // time through the loop and prefer indices (which are stable) to 14707 // iterators (which are not). 14708 bool DefinedAnything = false; 14709 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14710 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14711 if (!Class) 14712 continue; 14713 TemplateSpecializationKind ClassTSK = 14714 Class->getTemplateSpecializationKind(); 14715 14716 SourceLocation Loc = VTableUses[I].second; 14717 14718 bool DefineVTable = true; 14719 14720 // If this class has a key function, but that key function is 14721 // defined in another translation unit, we don't need to emit the 14722 // vtable even though we're using it. 14723 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14724 if (KeyFunction && !KeyFunction->hasBody()) { 14725 // The key function is in another translation unit. 14726 DefineVTable = false; 14727 TemplateSpecializationKind TSK = 14728 KeyFunction->getTemplateSpecializationKind(); 14729 assert(TSK != TSK_ExplicitInstantiationDefinition && 14730 TSK != TSK_ImplicitInstantiation && 14731 "Instantiations don't have key functions"); 14732 (void)TSK; 14733 } else if (!KeyFunction) { 14734 // If we have a class with no key function that is the subject 14735 // of an explicit instantiation declaration, suppress the 14736 // vtable; it will live with the explicit instantiation 14737 // definition. 14738 bool IsExplicitInstantiationDeclaration = 14739 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14740 for (auto R : Class->redecls()) { 14741 TemplateSpecializationKind TSK 14742 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14743 if (TSK == TSK_ExplicitInstantiationDeclaration) 14744 IsExplicitInstantiationDeclaration = true; 14745 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14746 IsExplicitInstantiationDeclaration = false; 14747 break; 14748 } 14749 } 14750 14751 if (IsExplicitInstantiationDeclaration) 14752 DefineVTable = false; 14753 } 14754 14755 // The exception specifications for all virtual members may be needed even 14756 // if we are not providing an authoritative form of the vtable in this TU. 14757 // We may choose to emit it available_externally anyway. 14758 if (!DefineVTable) { 14759 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14760 continue; 14761 } 14762 14763 // Mark all of the virtual members of this class as referenced, so 14764 // that we can build a vtable. Then, tell the AST consumer that a 14765 // vtable for this class is required. 14766 DefinedAnything = true; 14767 MarkVirtualMembersReferenced(Loc, Class); 14768 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 14769 if (VTablesUsed[Canonical]) 14770 Consumer.HandleVTable(Class); 14771 14772 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14773 // no key function or the key function is inlined. Don't warn in C++ ABIs 14774 // that lack key functions, since the user won't be able to make one. 14775 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14776 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14777 const FunctionDecl *KeyFunctionDef = nullptr; 14778 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14779 KeyFunctionDef->isInlined())) { 14780 Diag(Class->getLocation(), 14781 ClassTSK == TSK_ExplicitInstantiationDefinition 14782 ? diag::warn_weak_template_vtable 14783 : diag::warn_weak_vtable) 14784 << Class; 14785 } 14786 } 14787 } 14788 VTableUses.clear(); 14789 14790 return DefinedAnything; 14791 } 14792 14793 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14794 const CXXRecordDecl *RD) { 14795 for (const auto *I : RD->methods()) 14796 if (I->isVirtual() && !I->isPure()) 14797 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14798 } 14799 14800 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14801 const CXXRecordDecl *RD) { 14802 // Mark all functions which will appear in RD's vtable as used. 14803 CXXFinalOverriderMap FinalOverriders; 14804 RD->getFinalOverriders(FinalOverriders); 14805 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14806 E = FinalOverriders.end(); 14807 I != E; ++I) { 14808 for (OverridingMethods::const_iterator OI = I->second.begin(), 14809 OE = I->second.end(); 14810 OI != OE; ++OI) { 14811 assert(OI->second.size() > 0 && "no final overrider"); 14812 CXXMethodDecl *Overrider = OI->second.front().Method; 14813 14814 // C++ [basic.def.odr]p2: 14815 // [...] A virtual member function is used if it is not pure. [...] 14816 if (!Overrider->isPure()) 14817 MarkFunctionReferenced(Loc, Overrider); 14818 } 14819 } 14820 14821 // Only classes that have virtual bases need a VTT. 14822 if (RD->getNumVBases() == 0) 14823 return; 14824 14825 for (const auto &I : RD->bases()) { 14826 const CXXRecordDecl *Base = 14827 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14828 if (Base->getNumVBases() == 0) 14829 continue; 14830 MarkVirtualMembersReferenced(Loc, Base); 14831 } 14832 } 14833 14834 /// SetIvarInitializers - This routine builds initialization ASTs for the 14835 /// Objective-C implementation whose ivars need be initialized. 14836 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14837 if (!getLangOpts().CPlusPlus) 14838 return; 14839 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14840 SmallVector<ObjCIvarDecl*, 8> ivars; 14841 CollectIvarsToConstructOrDestruct(OID, ivars); 14842 if (ivars.empty()) 14843 return; 14844 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14845 for (unsigned i = 0; i < ivars.size(); i++) { 14846 FieldDecl *Field = ivars[i]; 14847 if (Field->isInvalidDecl()) 14848 continue; 14849 14850 CXXCtorInitializer *Member; 14851 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14852 InitializationKind InitKind = 14853 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14854 14855 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14856 ExprResult MemberInit = 14857 InitSeq.Perform(*this, InitEntity, InitKind, None); 14858 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14859 // Note, MemberInit could actually come back empty if no initialization 14860 // is required (e.g., because it would call a trivial default constructor) 14861 if (!MemberInit.get() || MemberInit.isInvalid()) 14862 continue; 14863 14864 Member = 14865 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14866 SourceLocation(), 14867 MemberInit.getAs<Expr>(), 14868 SourceLocation()); 14869 AllToInit.push_back(Member); 14870 14871 // Be sure that the destructor is accessible and is marked as referenced. 14872 if (const RecordType *RecordTy = 14873 Context.getBaseElementType(Field->getType()) 14874 ->getAs<RecordType>()) { 14875 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14876 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14877 MarkFunctionReferenced(Field->getLocation(), Destructor); 14878 CheckDestructorAccess(Field->getLocation(), Destructor, 14879 PDiag(diag::err_access_dtor_ivar) 14880 << Context.getBaseElementType(Field->getType())); 14881 } 14882 } 14883 } 14884 ObjCImplementation->setIvarInitializers(Context, 14885 AllToInit.data(), AllToInit.size()); 14886 } 14887 } 14888 14889 static 14890 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14891 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14892 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14893 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14894 Sema &S) { 14895 if (Ctor->isInvalidDecl()) 14896 return; 14897 14898 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14899 14900 // Target may not be determinable yet, for instance if this is a dependent 14901 // call in an uninstantiated template. 14902 if (Target) { 14903 const FunctionDecl *FNTarget = nullptr; 14904 (void)Target->hasBody(FNTarget); 14905 Target = const_cast<CXXConstructorDecl*>( 14906 cast_or_null<CXXConstructorDecl>(FNTarget)); 14907 } 14908 14909 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14910 // Avoid dereferencing a null pointer here. 14911 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14912 14913 if (!Current.insert(Canonical).second) 14914 return; 14915 14916 // We know that beyond here, we aren't chaining into a cycle. 14917 if (!Target || !Target->isDelegatingConstructor() || 14918 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14919 Valid.insert(Current.begin(), Current.end()); 14920 Current.clear(); 14921 // We've hit a cycle. 14922 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14923 Current.count(TCanonical)) { 14924 // If we haven't diagnosed this cycle yet, do so now. 14925 if (!Invalid.count(TCanonical)) { 14926 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14927 diag::warn_delegating_ctor_cycle) 14928 << Ctor; 14929 14930 // Don't add a note for a function delegating directly to itself. 14931 if (TCanonical != Canonical) 14932 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14933 14934 CXXConstructorDecl *C = Target; 14935 while (C->getCanonicalDecl() != Canonical) { 14936 const FunctionDecl *FNTarget = nullptr; 14937 (void)C->getTargetConstructor()->hasBody(FNTarget); 14938 assert(FNTarget && "Ctor cycle through bodiless function"); 14939 14940 C = const_cast<CXXConstructorDecl*>( 14941 cast<CXXConstructorDecl>(FNTarget)); 14942 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14943 } 14944 } 14945 14946 Invalid.insert(Current.begin(), Current.end()); 14947 Current.clear(); 14948 } else { 14949 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14950 } 14951 } 14952 14953 14954 void Sema::CheckDelegatingCtorCycles() { 14955 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14956 14957 for (DelegatingCtorDeclsType::iterator 14958 I = DelegatingCtorDecls.begin(ExternalSource), 14959 E = DelegatingCtorDecls.end(); 14960 I != E; ++I) 14961 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14962 14963 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14964 CE = Invalid.end(); 14965 CI != CE; ++CI) 14966 (*CI)->setInvalidDecl(); 14967 } 14968 14969 namespace { 14970 /// \brief AST visitor that finds references to the 'this' expression. 14971 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14972 Sema &S; 14973 14974 public: 14975 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14976 14977 bool VisitCXXThisExpr(CXXThisExpr *E) { 14978 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14979 << E->isImplicit(); 14980 return false; 14981 } 14982 }; 14983 } 14984 14985 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14986 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14987 if (!TSInfo) 14988 return false; 14989 14990 TypeLoc TL = TSInfo->getTypeLoc(); 14991 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14992 if (!ProtoTL) 14993 return false; 14994 14995 // C++11 [expr.prim.general]p3: 14996 // [The expression this] shall not appear before the optional 14997 // cv-qualifier-seq and it shall not appear within the declaration of a 14998 // static member function (although its type and value category are defined 14999 // within a static member function as they are within a non-static member 15000 // function). [ Note: this is because declaration matching does not occur 15001 // until the complete declarator is known. - end note ] 15002 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15003 FindCXXThisExpr Finder(*this); 15004 15005 // If the return type came after the cv-qualifier-seq, check it now. 15006 if (Proto->hasTrailingReturn() && 15007 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15008 return true; 15009 15010 // Check the exception specification. 15011 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15012 return true; 15013 15014 return checkThisInStaticMemberFunctionAttributes(Method); 15015 } 15016 15017 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15018 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15019 if (!TSInfo) 15020 return false; 15021 15022 TypeLoc TL = TSInfo->getTypeLoc(); 15023 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15024 if (!ProtoTL) 15025 return false; 15026 15027 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15028 FindCXXThisExpr Finder(*this); 15029 15030 switch (Proto->getExceptionSpecType()) { 15031 case EST_Unparsed: 15032 case EST_Uninstantiated: 15033 case EST_Unevaluated: 15034 case EST_BasicNoexcept: 15035 case EST_DynamicNone: 15036 case EST_MSAny: 15037 case EST_None: 15038 break; 15039 15040 case EST_ComputedNoexcept: 15041 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15042 return true; 15043 LLVM_FALLTHROUGH; 15044 15045 case EST_Dynamic: 15046 for (const auto &E : Proto->exceptions()) { 15047 if (!Finder.TraverseType(E)) 15048 return true; 15049 } 15050 break; 15051 } 15052 15053 return false; 15054 } 15055 15056 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15057 FindCXXThisExpr Finder(*this); 15058 15059 // Check attributes. 15060 for (const auto *A : Method->attrs()) { 15061 // FIXME: This should be emitted by tblgen. 15062 Expr *Arg = nullptr; 15063 ArrayRef<Expr *> Args; 15064 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15065 Arg = G->getArg(); 15066 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15067 Arg = G->getArg(); 15068 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15069 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15070 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15071 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15072 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15073 Arg = ETLF->getSuccessValue(); 15074 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15075 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15076 Arg = STLF->getSuccessValue(); 15077 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15078 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15079 Arg = LR->getArg(); 15080 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15081 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15082 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15083 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15084 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15085 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15086 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15087 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15088 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15089 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15090 15091 if (Arg && !Finder.TraverseStmt(Arg)) 15092 return true; 15093 15094 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15095 if (!Finder.TraverseStmt(Args[I])) 15096 return true; 15097 } 15098 } 15099 15100 return false; 15101 } 15102 15103 void Sema::checkExceptionSpecification( 15104 bool IsTopLevel, ExceptionSpecificationType EST, 15105 ArrayRef<ParsedType> DynamicExceptions, 15106 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15107 SmallVectorImpl<QualType> &Exceptions, 15108 FunctionProtoType::ExceptionSpecInfo &ESI) { 15109 Exceptions.clear(); 15110 ESI.Type = EST; 15111 if (EST == EST_Dynamic) { 15112 Exceptions.reserve(DynamicExceptions.size()); 15113 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15114 // FIXME: Preserve type source info. 15115 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15116 15117 if (IsTopLevel) { 15118 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15119 collectUnexpandedParameterPacks(ET, Unexpanded); 15120 if (!Unexpanded.empty()) { 15121 DiagnoseUnexpandedParameterPacks( 15122 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15123 Unexpanded); 15124 continue; 15125 } 15126 } 15127 15128 // Check that the type is valid for an exception spec, and 15129 // drop it if not. 15130 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15131 Exceptions.push_back(ET); 15132 } 15133 ESI.Exceptions = Exceptions; 15134 return; 15135 } 15136 15137 if (EST == EST_ComputedNoexcept) { 15138 // If an error occurred, there's no expression here. 15139 if (NoexceptExpr) { 15140 assert((NoexceptExpr->isTypeDependent() || 15141 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15142 Context.BoolTy) && 15143 "Parser should have made sure that the expression is boolean"); 15144 if (IsTopLevel && NoexceptExpr && 15145 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15146 ESI.Type = EST_BasicNoexcept; 15147 return; 15148 } 15149 15150 if (!NoexceptExpr->isValueDependent()) { 15151 ExprResult Result = VerifyIntegerConstantExpression( 15152 NoexceptExpr, nullptr, diag::err_noexcept_needs_constant_expression, 15153 /*AllowFold*/ false); 15154 if (Result.isInvalid()) { 15155 ESI.Type = EST_BasicNoexcept; 15156 return; 15157 } 15158 NoexceptExpr = Result.get(); 15159 } 15160 ESI.NoexceptExpr = NoexceptExpr; 15161 } 15162 return; 15163 } 15164 } 15165 15166 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15167 ExceptionSpecificationType EST, 15168 SourceRange SpecificationRange, 15169 ArrayRef<ParsedType> DynamicExceptions, 15170 ArrayRef<SourceRange> DynamicExceptionRanges, 15171 Expr *NoexceptExpr) { 15172 if (!MethodD) 15173 return; 15174 15175 // Dig out the method we're referring to. 15176 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15177 MethodD = FunTmpl->getTemplatedDecl(); 15178 15179 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15180 if (!Method) 15181 return; 15182 15183 // Check the exception specification. 15184 llvm::SmallVector<QualType, 4> Exceptions; 15185 FunctionProtoType::ExceptionSpecInfo ESI; 15186 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15187 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15188 ESI); 15189 15190 // Update the exception specification on the function type. 15191 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15192 15193 if (Method->isStatic()) 15194 checkThisInStaticMemberFunctionExceptionSpec(Method); 15195 15196 if (Method->isVirtual()) { 15197 // Check overrides, which we previously had to delay. 15198 for (const CXXMethodDecl *O : Method->overridden_methods()) 15199 CheckOverridingFunctionExceptionSpec(Method, O); 15200 } 15201 } 15202 15203 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15204 /// 15205 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15206 SourceLocation DeclStart, 15207 Declarator &D, Expr *BitWidth, 15208 InClassInitStyle InitStyle, 15209 AccessSpecifier AS, 15210 AttributeList *MSPropertyAttr) { 15211 IdentifierInfo *II = D.getIdentifier(); 15212 if (!II) { 15213 Diag(DeclStart, diag::err_anonymous_property); 15214 return nullptr; 15215 } 15216 SourceLocation Loc = D.getIdentifierLoc(); 15217 15218 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15219 QualType T = TInfo->getType(); 15220 if (getLangOpts().CPlusPlus) { 15221 CheckExtraCXXDefaultArguments(D); 15222 15223 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15224 UPPC_DataMemberType)) { 15225 D.setInvalidType(); 15226 T = Context.IntTy; 15227 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15228 } 15229 } 15230 15231 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15232 15233 if (D.getDeclSpec().isInlineSpecified()) 15234 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15235 << getLangOpts().CPlusPlus17; 15236 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15237 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15238 diag::err_invalid_thread) 15239 << DeclSpec::getSpecifierName(TSCS); 15240 15241 // Check to see if this name was declared as a member previously 15242 NamedDecl *PrevDecl = nullptr; 15243 LookupResult Previous(*this, II, Loc, LookupMemberName, 15244 ForVisibleRedeclaration); 15245 LookupName(Previous, S); 15246 switch (Previous.getResultKind()) { 15247 case LookupResult::Found: 15248 case LookupResult::FoundUnresolvedValue: 15249 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15250 break; 15251 15252 case LookupResult::FoundOverloaded: 15253 PrevDecl = Previous.getRepresentativeDecl(); 15254 break; 15255 15256 case LookupResult::NotFound: 15257 case LookupResult::NotFoundInCurrentInstantiation: 15258 case LookupResult::Ambiguous: 15259 break; 15260 } 15261 15262 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15263 // Maybe we will complain about the shadowed template parameter. 15264 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15265 // Just pretend that we didn't see the previous declaration. 15266 PrevDecl = nullptr; 15267 } 15268 15269 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15270 PrevDecl = nullptr; 15271 15272 SourceLocation TSSL = D.getLocStart(); 15273 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 15274 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 15275 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 15276 ProcessDeclAttributes(TUScope, NewPD, D); 15277 NewPD->setAccess(AS); 15278 15279 if (NewPD->isInvalidDecl()) 15280 Record->setInvalidDecl(); 15281 15282 if (D.getDeclSpec().isModulePrivateSpecified()) 15283 NewPD->setModulePrivate(); 15284 15285 if (NewPD->isInvalidDecl() && PrevDecl) { 15286 // Don't introduce NewFD into scope; there's already something 15287 // with the same name in the same scope. 15288 } else if (II) { 15289 PushOnScopeChains(NewPD, S); 15290 } else 15291 Record->addDecl(NewPD); 15292 15293 return NewPD; 15294 } 15295